From 760fa16c109df7c24d5dea4190d0320bae5d73ee Mon Sep 17 00:00:00 2001 From: maoji-y <255648417+maoji-y@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:36:45 +0100 Subject: [PATCH] Notify subscribers when prompt reload fails --- README.md | 9 ++++++--- priompt_sdk/client.py | 32 +++++++++++++++++--------------- tests/test_client.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 0677c0f..5769f36 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/priompt_sdk/client.py b/priompt_sdk/client.py index 1533a87..71cf3bc 100644 --- a/priompt_sdk/client.py +++ b/priompt_sdk/client.py @@ -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 @@ -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) diff --git a/tests/test_client.py b/tests/test_client.py index 1f874f0..aaf6c18 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -7,6 +7,7 @@ key collision, a value handed back after its TTL expired. """ +import logging import threading import pytest @@ -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):