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
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```
Expand Down Expand Up @@ -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()
```
Expand All @@ -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
Expand Down
79 changes: 70 additions & 9 deletions priompt_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import os
import re
import threading
import time
from urllib.parse import urlparse
Expand All @@ -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):
Expand Down Expand Up @@ -95,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=""):
Expand All @@ -107,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=""):
Expand All @@ -128,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):
Expand All @@ -149,6 +174,40 @@ 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"):
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)
Comment on lines +199 to +208

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed! Coordinated cache reads, fills, and invalidations with self._cache_lock and a self._cache_gen generation counter so in-flight get() / list() calls that overlap a publish() (or subscribe() reload) won't repopulate self._cache with stale pre-publish responses, and added deterministic threading.Event-based regression tests for both get() and list() (42/42 passing locally).

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
Expand Down Expand Up @@ -213,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)

Expand Down
183 changes: 181 additions & 2 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -364,4 +371,176 @@ 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)
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


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
Loading