From 82598c9102ae8aa48719026dd2841e9de04800db Mon Sep 17 00:00:00 2001 From: Kemal Codes <74741855+techkayacodes@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:06:31 -0500 Subject: [PATCH 1/5] feat: add publish() to PromptClient --- priompt_sdk/client.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/priompt_sdk/client.py b/priompt_sdk/client.py index becd014..c5e8c07 100644 --- a/priompt_sdk/client.py +++ b/priompt_sdk/client.py @@ -2,6 +2,7 @@ import logging import os +import re import threading import time from urllib.parse import urlparse @@ -14,6 +15,16 @@ _TOKEN_SAFE = frozenset( b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" ) +_SLOT_RE = re.compile(r"\{\{|\}\}|\{([A-Za-z0-9_]+)\}") + + +def _derive_slots(template): + """Extract {slot} names in first-seen order, skipping escaped {{ / }}.""" + return list( + dict.fromkeys( + m.group(1) for m in _SLOT_RE.finditer(template) if m.group(1) is not None + ) + ) def _subject(uri): @@ -149,6 +160,35 @@ def diff(self, uri, new_template): metadata=self._md, ) + def publish(self, uri, template, slots=None, message="", branch=""): + """Validate and store a new prompt version on the server. Returns the + PublishPromptResponse (with `version_hash`). + + When `slots` is None, placeholder names are derived from `template` in + first-seen order (skipping escaped `{{` / `}}`). Pass `branch` to write + to a non-default branch instead of `"main"`. + """ + if slots is None: + slots = _derive_slots(template) + resp = self._stub.PublishPrompt( + prompt_pb2.PublishPromptRequest( + uri=uri, + template=template, + slots=slots, + message=message, + branch=branch, + ), + metadata=self._md, + ) + # Unpinned get() and list() only serve the "main" HEAD, so non-main + # branch publishes leave the local cache intact. + if self._cache_ttl and branch in ("", "main"): + self._cache.pop(uri, None) + for key in list(self._cache): + if isinstance(key, tuple) and key[0] == "list" and uri.startswith(key[1]): + self._cache.pop(key, None) + return resp + def subscribe(self, uri, on_change, reload=None): """Register as a subscriber: call on_change(version_hash, classification) whenever the prompt at `uri` is republished (push). `classification` is From c5c896ef04eb27db6cfcc9522649257164b10bb8 Mon Sep 17 00:00:00 2001 From: Kemal Codes <74741855+techkayacodes@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:18:02 -0500 Subject: [PATCH 2/5] test: add unit tests for PromptClient.publish() --- tests/test_client.py | 106 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 40e2c3f..f1316fe 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -12,7 +12,7 @@ import pytest from priompt_sdk import PromptClient -from priompt_sdk.client import _subject +from priompt_sdk.client import _derive_slots, _subject class FakeStub: @@ -23,6 +23,8 @@ def __init__(self): self.get_calls = 0 self.list_calls = 0 self.diff_calls = 0 + self.publish_calls = 0 + self.last_publish = None def GetPrompt(self, req, metadata=None): self.get_calls += 1 @@ -37,6 +39,11 @@ def DiffPrompt(self, req, metadata=None): self.diff_calls += 1 return f"diff:{req.uri}:{self.diff_calls}" + def PublishPrompt(self, req, metadata=None): + self.publish_calls += 1 + self.last_publish = (req, metadata) + return type("Resp", (), {"version_hash": f"pub:{req.uri}:{self.publish_calls}"}) + @pytest.fixture def clock(monkeypatch): @@ -364,4 +371,99 @@ async def connect_no_port(url, error_cb=None, **kw): with pytest.raises(ConnectionError) as exc2: c2.subscribe("priompt://x", lambda *_: None) assert "127.0.0.1:5222" in str(exc2.value) - assert "secret-token" not in str(exc2.value) \ No newline at end of file + assert "secret-token" not in str(exc2.value) + + +# --- publish: slot derivation and cache invalidation ---------------------- + +@pytest.mark.parametrize("template,expected", [ + ("Hi {name}, welcome to {org}!", ["name", "org"]), + ("{b} then {a} then {b} and {c} and {a}", ["b", "a", "c"]), + ("No placeholders here.", []), + ("Literal {{name}} and {{org}} braces.", []), + ("{{{name}}} {org} {{\"k\": \"{val}\"}}", ["name", "org", "val"]), + ("{user_id_1} and {Item2}", ["user_id_1", "Item2"]), +]) +def test_derive_slots(template, expected): + assert _derive_slots(template) == expected + + +def test_publish_derives_slots_and_forwards_fields(): + c = PromptClient("localhost:1", token="tok123") + c._stub = FakeStub() + resp = c.publish( + "priompt://acme/onboarding/welcome", + "Hi {name}, welcome to {org}! Bye {name}.", + message="friendlier greeting", + branch="draft", + ) + assert resp.version_hash == "pub:priompt://acme/onboarding/welcome:1" + req, md = c._stub.last_publish + assert req.uri == "priompt://acme/onboarding/welcome" + assert req.template == "Hi {name}, welcome to {org}! Bye {name}." + assert list(req.slots) == ["name", "org"] + assert req.message == "friendlier greeting" + assert req.branch == "draft" + assert md == [("authorization", "Bearer tok123")] + + +def test_publish_respects_explicit_slots(): + c = make_client() + c.publish("priompt://x", "Hi {name}!", slots=["custom"]) + req, _ = c._stub.last_publish + assert list(req.slots) == ["custom"] + + # An explicit empty list must not fall back to derivation. + c.publish("priompt://x", "Hi {name}!", slots=[]) + req, _ = c._stub.last_publish + assert list(req.slots) == [] + + +def test_publish_invalidates_get_and_matching_list_cache(clock): + c = make_client(cache_ttl=10) + uri = "priompt://acme/onboarding/welcome" + other = "priompt://acme/onboarding/goodbye" + + before_get = c.get(uri) + before_other = c.get(other) + before_all = c.list("") + before_acme = c.list("priompt://acme/") + before_unrelated = c.list("priompt://other/") + + c.publish(uri, "Hi {name}!") + + # Published URI and matching list prefixes are evicted and refetched. + assert c.get(uri) != before_get + assert c.list("") != before_all + assert c.list("priompt://acme/") != before_acme + # Unrelated get() and list() entries remain warm in the cache. + assert c.get(other) == before_other + assert c.list("priompt://other/") == before_unrelated + assert c._stub.get_calls == 3 + assert c._stub.list_calls == 5 + + +def test_publish_to_main_invalidates_cache(clock): + c = make_client(cache_ttl=10) + uri = "priompt://acme/onboarding/welcome" + before_get = c.get(uri) + before_list = c.list("priompt://acme/") + + c.publish(uri, "Hi {name}!", branch="main") + + assert c.get(uri) != before_get + assert c.list("priompt://acme/") != before_list + + +def test_publish_to_non_main_branch_keeps_cache(clock): + c = make_client(cache_ttl=10) + uri = "priompt://acme/onboarding/welcome" + before_get = c.get(uri) + before_list = c.list("priompt://acme/") + + c.publish(uri, "Hi {name}!", branch="experiment") + + assert c.get(uri) == before_get + assert c.list("priompt://acme/") == before_list + assert c._stub.get_calls == 1 + assert c._stub.list_calls == 1 From a2bab2dc6f795948c2bdab4d23993a0dee55c7e1 Mon Sep 17 00:00:00 2001 From: Kemal Codes <74741855+techkayacodes@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:51:36 -0500 Subject: [PATCH 3/5] docs: document PromptClient.publish() in README --- README.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b37fce4..0677c0f 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ notified the moment a prompt changes. 🐍 Your Python app β”‚ β–Ό - PromptClient (this library) ──gRPC: get / list / diff──▢ πŸ—„οΈ Priompt server - β”‚ β–² β”‚ - β”‚ └──────────── "prompt changed" push (NATS) β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + PromptClient (this library) ──gRPC: get/list/diff/publish──▢ πŸ—„οΈ Priompt server + β”‚ β–² β”‚ + β”‚ └────────────── "prompt changed" push (NATS) β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–Ό Optional local cache (cache_ttl seconds) ``` @@ -78,6 +78,7 @@ PromptClient(host=None, token=None, tls=False, ca_cert=None, client.get(uri, ref="") # fetch a prompt (ref = branch or commit hash to pin a version) client.list(prefix="") # browse a repo (URI prefix) like a folder client.diff(uri, new_template) # semantic diff: stored version vs. your draft +client.publish(uri, template, slots=None, message="", branch="") # publish a new prompt version client.subscribe(uri, on_change, reload=None) # be notified when the prompt changes client.close() ``` @@ -97,6 +98,17 @@ Pin a version (ignore future changes until *you* decide to upgrade): prompt = client.get("priompt://acme/support/agent", ref="1e8284f35650") ``` +Publish a new version (slots are derived automatically unless passed explicitly): + +```python +resp = client.publish( + "priompt://acme/onboarding/welcome", + "Hi {name}, welcome to {org}!", + message="friendlier greeting", +) +print(resp.version_hash) +``` + ## Live updates When someone publishes a new version, the server pushes a notification that From 7ed786e9e187f9791e3ae672adfd54cb8b4b0c17 Mon Sep 17 00:00:00 2001 From: Kemal Codes <74741855+techkayacodes@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:19:11 -0500 Subject: [PATCH 4/5] fix: prevent in-flight reads from repopulating stale cache after publish --- priompt_sdk/client.py | 45 +++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/priompt_sdk/client.py b/priompt_sdk/client.py index c5e8c07..1533a87 100644 --- a/priompt_sdk/client.py +++ b/priompt_sdk/client.py @@ -106,6 +106,8 @@ def __init__( # valid; TTL is the staleness bound (a change shows up within cache_ttl s). self._cache_ttl = cache_ttl self._cache = {} + self._cache_lock = threading.Lock() + self._cache_gen = 0 self._nats_url = nats_url # e.g. "nats://your-company.prompts.io:4222" def get(self, uri, ref=""): @@ -118,15 +120,21 @@ def get(self, uri, ref=""): return self._stub.GetPrompt( prompt_pb2.GetPromptRequest(uri=uri, ref=ref), metadata=self._md ) + gen = 0 if self._cache_ttl: - hit = self._cache.get(uri) - if hit and hit[1] > time.monotonic(): - return hit[0] + with self._cache_lock: + hit = self._cache.get(uri) + if hit and hit[1] > time.monotonic(): + return hit[0] + gen = self._cache_gen resp = self._stub.GetPrompt( prompt_pb2.GetPromptRequest(uri=uri), metadata=self._md ) if self._cache_ttl: - self._cache[uri] = (resp, time.monotonic() + 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) return resp def list(self, prefix=""): @@ -139,15 +147,21 @@ def list(self, prefix=""): newly published prompt under `prefix` won't appear yet. """ key = ("list", prefix) + gen = 0 if self._cache_ttl: - hit = self._cache.get(key) - if hit and hit[1] > time.monotonic(): - return hit[0] + with self._cache_lock: + hit = self._cache.get(key) + if hit and hit[1] > time.monotonic(): + return hit[0] + gen = self._cache_gen entries = self._stub.ListPrompts( prompt_pb2.ListPromptsRequest(prefix=prefix), metadata=self._md ).entries if self._cache_ttl: - self._cache[key] = (entries, time.monotonic() + 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) return entries def diff(self, uri, new_template): @@ -183,9 +197,14 @@ def publish(self, uri, template, slots=None, message="", branch=""): # Unpinned get() and list() only serve the "main" HEAD, so non-main # branch publishes leave the local cache intact. if self._cache_ttl and branch in ("", "main"): - self._cache.pop(uri, None) - for key in list(self._cache): - if isinstance(key, tuple) and key[0] == "list" and uri.startswith(key[1]): + with self._cache_lock: + self._cache_gen += 1 + self._cache.pop(uri, None) + for key in [ + k + for k in self._cache + if isinstance(k, tuple) and k[0] == "list" and uri.startswith(k[1]) + ]: self._cache.pop(key, None) return resp @@ -253,7 +272,9 @@ async def handler(msg): # 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: - self._cache.pop(uri, None) # drop stale cache + 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 on_change(version, classification) From 94f09b4cccde14d8dcd3a9a9c83e30dce0c5976c Mon Sep 17 00:00:00 2001 From: Kemal Codes <74741855+techkayacodes@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:48:53 -0500 Subject: [PATCH 5/5] test: add deterministic overlapping read/publish cache regression tests --- tests/test_client.py | 77 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/tests/test_client.py b/tests/test_client.py index f1316fe..1f874f0 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -467,3 +467,80 @@ def test_publish_to_non_main_branch_keeps_cache(clock): assert c.list("priompt://acme/") == before_list assert c._stub.get_calls == 1 assert c._stub.list_calls == 1 + + +def test_publish_prevents_in_flight_get_from_repopulating_stale_cache(clock): + """An in-flight get() that started before publish() must not write its + pre-publish response into the cache after publish() invalidates it.""" + read_started = threading.Event() + allow_read_finish = threading.Event() + + class BlockingGetStub(FakeStub): + def GetPrompt(self, req, metadata=None): + resp = super().GetPrompt(req, metadata=metadata) + if self.get_calls == 1: + read_started.set() + assert allow_read_finish.wait(5) + return resp + + c = PromptClient("localhost:1", cache_ttl=10) + c._stub = BlockingGetStub() + uri = "priompt://acme/onboarding/welcome" + stale_result = [] + + t = threading.Thread(target=lambda: stale_result.append(c.get(uri))) + t.start() + assert read_started.wait(5) + + c.publish(uri, "Hi {name}!") + allow_read_finish.set() + t.join(5) + assert not t.is_alive() + assert stale_result == [f"get:{uri}::1"] + + # Next read must refetch from the server instead of serving stale data. + fresh = c.get(uri) + assert fresh == f"get:{uri}::2" + assert c._stub.get_calls == 2 + # Subsequent reads populate and hit the cache normally. + assert c.get(uri) == fresh + assert c._stub.get_calls == 2 + + +def test_publish_prevents_in_flight_list_from_repopulating_stale_cache(clock): + """An in-flight list() that started before publish() must not write its + pre-publish entries into the cache after publish() invalidates it.""" + read_started = threading.Event() + allow_read_finish = threading.Event() + + class BlockingListStub(FakeStub): + def ListPrompts(self, req, metadata=None): + resp = super().ListPrompts(req, metadata=metadata) + if self.list_calls == 1: + read_started.set() + assert allow_read_finish.wait(5) + return resp + + c = PromptClient("localhost:1", cache_ttl=10) + c._stub = BlockingListStub() + prefix = "priompt://acme/" + uri = "priompt://acme/onboarding/welcome" + stale_result = [] + + t = threading.Thread(target=lambda: stale_result.append(c.list(prefix))) + t.start() + assert read_started.wait(5) + + c.publish(uri, "Hi {name}!") + allow_read_finish.set() + t.join(5) + assert not t.is_alive() + assert stale_result == [f"list:{prefix}:1"] + + # Next list() must refetch instead of serving the pre-publish snapshot. + fresh = c.list(prefix) + assert fresh == f"list:{prefix}:2" + assert c._stub.list_calls == 2 + # Subsequent list() calls hit the cache normally. + assert c.list(prefix) == fresh + assert c._stub.list_calls == 2