Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 48 additions & 19 deletions priompt_sdk/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Priompt Python adapter. Works with LangChain, LangGraph, or raw Python."""

from collections import OrderedDict
import logging
import os
import re
Expand Down Expand Up @@ -62,6 +63,7 @@ def __init__(
client_cert=None,
client_key=None,
cache_ttl=0,
cache_max_entries=1024,
nats_url=None,
url=None,
):
Expand Down Expand Up @@ -104,12 +106,49 @@ def __init__(
# Keys: a bare uri for get(); ("list", prefix) for list() so the two never
# collide. The server only returns validated prompts, so anything cached is
# valid; TTL is the staleness bound (a change shows up within cache_ttl s).
if cache_max_entries is not None and cache_max_entries <= 0:
raise ValueError("cache_max_entries must be positive or None")
self._cache_ttl = cache_ttl
self._cache = {}
self._cache_max_entries = cache_max_entries
self._cache = OrderedDict()
self._cache_lock = threading.Lock()
self._cache_gen = 0
self._nats_url = nats_url # e.g. "nats://your-company.prompts.io:4222"

def _cache_get(self, key):
"""Return (found, value, gen). Deletes expired entries on lookup."""
with self._cache_lock:
hit = self._cache.get(key)
if hit is not None:
if hit[1] > time.monotonic():
self._cache.move_to_end(key)
return True, hit[0], self._cache_gen
self._cache.pop(key, None)
return False, None, self._cache_gen

def _cache_set(self, key, value, gen):
"""Insert a cached entry if no invalidation raced, pruning expired and LRU entries."""
now = time.monotonic()
with self._cache_lock:
# Skip caching if an invalidation raced with this in-flight read.
if self._cache_gen != gen:
return
# Evict expired entries at the oldest end of the LRU order.
while self._cache:
oldest_key, (_, oldest_expiry) = next(iter(self._cache.items()))
if oldest_expiry > now:
break
self._cache.pop(oldest_key, None)
self._cache[key] = (value, now + self._cache_ttl)
self._cache.move_to_end(key)
if self._cache_max_entries is not None and len(self._cache) > self._cache_max_entries:
# Drop any remaining expired entries before evicting live LRU entries.
expired = [k for k, (_, exp) in self._cache.items() if exp <= now]
for k in expired:
self._cache.pop(k, None)
while len(self._cache) > self._cache_max_entries:
self._cache.popitem(last=False)

def get(self, uri, ref=""):
"""Fetch a prompt by priompt:// URI. Returns the GetPromptResponse.

Expand All @@ -122,19 +161,14 @@ def get(self, uri, ref=""):
)
gen = 0
if self._cache_ttl:
with self._cache_lock:
hit = self._cache.get(uri)
if hit and hit[1] > time.monotonic():
return hit[0]
gen = self._cache_gen
found, cached, gen = self._cache_get(uri)
if found:
return cached
resp = self._stub.GetPrompt(
prompt_pb2.GetPromptRequest(uri=uri), metadata=self._md
)
if self._cache_ttl:
with self._cache_lock:
# Skip caching if an invalidation raced with this in-flight read.
if self._cache_gen == gen:
self._cache[uri] = (resp, time.monotonic() + self._cache_ttl)
self._cache_set(uri, resp, gen)
return resp

def list(self, prefix=""):
Expand All @@ -149,19 +183,14 @@ def list(self, prefix=""):
key = ("list", prefix)
gen = 0
if self._cache_ttl:
with self._cache_lock:
hit = self._cache.get(key)
if hit and hit[1] > time.monotonic():
return hit[0]
gen = self._cache_gen
found, cached, gen = self._cache_get(key)
if found:
return cached
entries = self._stub.ListPrompts(
prompt_pb2.ListPromptsRequest(prefix=prefix), metadata=self._md
).entries
if self._cache_ttl:
with self._cache_lock:
# Skip caching if an invalidation raced with this in-flight read.
if self._cache_gen == gen:
self._cache[key] = (entries, time.monotonic() + self._cache_ttl)
self._cache_set(key, entries, gen)
return entries

def diff(self, uri, new_template):
Expand Down
69 changes: 69 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,72 @@ def ListPrompts(self, req, metadata=None):
# Subsequent list() calls hit the cache normally.
assert c.list(prefix) == fresh
assert c._stub.list_calls == 2


# --- cache eviction: expired cleanup and bounded LRU size -----------------


def test_expired_get_and_list_entries_are_evicted(clock):
c = make_client(cache_ttl=1)
for i in range(200):
c.get(f"priompt://acme/p{i}")
clock.advance(2)
# Every previous entry expired; only the latest remains.
assert len(c._cache) == 1

# Expired list() entries are also evicted as new prefixes arrive.
for i in range(50):
c.list(f"priompt://acme/ns{i}/")
clock.advance(2)
assert len(c._cache) == 1


def test_expired_entry_deleted_on_lookup_even_if_rpc_fails(clock):
class FailingOnSecondStub(FakeStub):
def GetPrompt(self, req, metadata=None):
if self.get_calls >= 1:
raise RuntimeError("transient error")
return super().GetPrompt(req, metadata=metadata)

c = PromptClient("localhost:1", cache_ttl=5)
c._stub = FailingOnSecondStub()
c.get("priompt://acme/p1")
assert "priompt://acme/p1" in c._cache

clock.advance(10)
with pytest.raises(RuntimeError, match="transient error"):
c.get("priompt://acme/p1")
# Lookup removed the stale entry before the RPC failed.
assert "priompt://acme/p1" not in c._cache


def test_cache_max_entries_evicts_least_recently_used(clock):
c = PromptClient("localhost:1", cache_ttl=60, cache_max_entries=3)
c._stub = FakeStub()

a = c.get("priompt://acme/a")
b = c.get("priompt://acme/b")
c_val = c.get("priompt://acme/c")
assert len(c._cache) == 3

# Touch "a" so "b" becomes least recently used.
assert c.get("priompt://acme/a") == a
d = c.get("priompt://acme/d")

assert len(c._cache) == 3
assert "priompt://acme/b" not in c._cache
assert c.get("priompt://acme/a") == a
assert c.get("priompt://acme/c") == c_val
assert c.get("priompt://acme/d") == d
assert c._stub.get_calls == 4

# Re-reading evicted "b" hits the server again.
assert c.get("priompt://acme/b") != b
assert c._stub.get_calls == 5


def test_cache_max_entries_rejects_non_positive():
with pytest.raises(ValueError, match="cache_max_entries"):
PromptClient("localhost:1", cache_ttl=10, cache_max_entries=0)
with pytest.raises(ValueError, match="cache_max_entries"):
PromptClient("localhost:1", cache_ttl=10, cache_max_entries=-5)
Loading