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
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,16 @@ def on_change(version, classification):
else:
alert_a_human(version) # structural, or unclassified — hold it

# reload= is the same policy for the client cache: an accepted change is fetched
# into the cache before on_change runs; a held one is not, so get() keeps
# returning the old version until cache_ttl expires. Default: hold everything.
# reload= applies the same policy to the client cache. The client tries to
# refresh accepted changes before on_change runs. Held changes keep the cached
# version until cache_ttl expires. The default policy holds every change.
client.subscribe("priompt://acme/support/agent", on_change,
reload=AUTO_RELOAD) # needs the [nats] extra
```

If the reload policy or automatic refresh fails, the client logs a warning and
still calls `on_change`.

**The verdict measures spread, not risk.** A one-line edit turning *"offer a
refund when reasonable"* into *"never offer a refund"* reads as a `localized
tweak` — correctly, since the rest of the prompt still means what it did — and
Expand Down
32 changes: 17 additions & 15 deletions priompt_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,11 @@ def subscribe(self, uri, on_change, reload=None):

`reload` is the reload policy for the client cache: a set of verdicts,
e.g. {"minor edit", "localized tweak", "new"}, or a function
(version_hash, classification) -> bool. A change it accepts is fetched
into the cache before on_change runs, so get() returns it at once. Any
other change is held: get() keeps returning the cached version until
cache_ttl expires. The default (None) holds every change.
(version_hash, classification) -> bool. With caching enabled, the
client tries to refresh accepted changes before on_change runs. A held
change keeps the cached version until cache_ttl expires. The default
(None) holds every change. If the policy or refresh raises, the client
logs a warning and still calls on_change.

Requires `pip install nats-py` and nats_url set on the client. Raises
ConnectionError if the broker can't be reached or refuses the
Expand Down Expand Up @@ -265,17 +266,18 @@ async def handler(msg):
classification = ev.get("classification", "")
except (ValueError, AttributeError):
version, classification = msg.data.decode(), "" # pre-0.7 bare-hash body
if callable(reload):
accept = reload(version, classification)
else:
accept = classification in (reload or ())
# Only an accepted change refreshes the cache; a held one
# keeps serving the cached version until cache_ttl expires.
if accept and self._cache_ttl:
with self._cache_lock:
self._cache_gen += 1
self._cache.pop(uri, None) # drop stale cache
self.get(uri) # refetch now so the next get() is warm
try:
if callable(reload):
accept = reload(version, classification)
else:
accept = classification in (reload or ())
if accept and self._cache_ttl:
with self._cache_lock:
self._cache_gen += 1
self._cache.pop(uri, None)
await asyncio.to_thread(self.get, uri)
except Exception as e:
log.warning("priompt reload %s: %s", uri, e)
on_change(version, classification)

await nc.subscribe(subject, cb=handler)
Expand Down
43 changes: 43 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
key collision, a value handed back after its TTL expired.
"""

import logging
import threading

import pytest
Expand Down Expand Up @@ -264,6 +265,48 @@ def test_reload_policy_can_be_a_function(clock, fake_nats):
assert c.get("priompt://x") != before


def test_failed_reload_policy_still_notifies(clock, fake_nats, caplog):
c = make_subscriber()
uri = "priompt://x"
before = c.get(uri)
seen = []

def failing_policy(version, classification):
raise ValueError("policy failed")

c.subscribe(uri, lambda v, cls: seen.append((v, cls)), reload=failing_policy)
fake_nats("v2", "minor edit")

assert seen == [("v2", "minor edit")]
assert c.get(uri) == before
assert c._stub.get_calls == 1
warning = ("priompt_sdk", logging.WARNING, f"priompt reload {uri}: policy failed")
assert warning in caplog.record_tuples


def test_failed_reload_refetch_still_notifies(clock, fake_nats, caplog):
class FailOnceStub(FakeStub):
def GetPrompt(self, req, metadata=None):
fresh = super().GetPrompt(req, metadata=metadata)
if self.get_calls == 2:
raise OSError("refetch failed")
return fresh

c = make_subscriber()
c._stub = FailOnceStub()
uri = "priompt://x"
c.get(uri)
seen = []
c.subscribe(uri, lambda v, cls: seen.append((v, cls)), reload={"minor edit"})
fake_nats("v2", "minor edit")

assert seen == [("v2", "minor edit")]
assert c._stub.get_calls == 2
warning = ("priompt_sdk", logging.WARNING, f"priompt reload {uri}: refetch failed")
assert warning in caplog.record_tuples
assert c.get(uri) == f"get:{uri}::3"


# --- stress: lock-free cache under concurrent readers ---------------------

def test_concurrent_gets_do_not_crash_or_corrupt(clock):
Expand Down