Skip to content
Merged
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
12 changes: 7 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Continuous integration after changes land on main.
# Continuous integration for pull requests and changes pushed to main.
#
# Jobs: lint (seconds), the test matrix, free-threaded Python with the stress suite, mypy,
# a packaging check, live Redis, PostgreSQL and SQL Server backends, a framework version
Expand All @@ -13,7 +13,9 @@ name: CI

on:
push:
branches: [main]
branches: [main, 'fix/**']
pull_request:
workflow_dispatch:

# A force-push should not leave the previous run burning minutes on a dead commit.
concurrency:
Expand Down Expand Up @@ -42,7 +44,7 @@ jobs:
cache-dependency-glob: "uv.lock"
python-version: "3.13"

- run: uv sync --group dev --frozen
- run: uv sync --no-default-groups --group core-test --frozen

- name: ruff check
run: uv run --no-sync ruff check src tests scripts/check_installed.py
Expand Down Expand Up @@ -107,7 +109,7 @@ jobs:
cache-dependency-glob: "uv.lock"
python-version: "3.14t"

- run: uv sync --group dev --frozen
- run: uv sync --no-default-groups --group core-test --frozen

- name: The GIL must really be off
run: uv run --no-sync python -c "import sys; assert not sys._is_gil_enabled()"
Expand Down Expand Up @@ -310,7 +312,7 @@ jobs:
tests/test_sql_result_store.py
- name: Install the Microsoft ODBC driver for SQL Server
run: |
curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg
curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --batch --yes --dearmor -o /usr/share/keyrings/microsoft-prod.gpg
curl -fsSL "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list" | sudo tee /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc
Expand Down
8 changes: 5 additions & 3 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# Build check for the documentation site.
#
# Read the Docs does the hosting (see .readthedocs.yaml). This workflow only catches
# breakage after changes land on main: `--strict` turns a broken link, a page missing
# from the nav or a docstring mkdocstrings cannot render into a failed check.
# breakage before merge and after changes land on main: `--strict` turns a broken link, a page
# missing from the nav or a docstring mkdocstrings cannot render into a failed check.
name: Docs

on:
push:
branches: [main]
branches: [main, 'fix/**']
pull_request:
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ Breaking changes are listed under **Breaking changes**, each with its migration.

## [Unreleased]

### Security

- Shared SQLite token windows now sample time after taking the writer lock and keep stored
timestamps from moving backward, preventing delayed transactions or clock rollback from
granting extra refill. Tagged cache invalidation now weakly tracks Redis clients (or their
cache stores when a client cannot be weakly referenced), so abandoned closed clients do not
stay alive and disrupt later invalidations. A synchronous shutdown callback that times out
exhausts the remaining finite drain budget before another callback can start.

## [0.4.0b2] - 2026-11-26

### Breaking changes
Expand Down
6 changes: 4 additions & 2 deletions docs/features/ai/shared-limits-and-cassettes.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import tempfile

from python_wrap.llm import token_rate_limit
from python_wrap.llm_shared import SQLiteTokenWindow
from python_wrap.testing import fake_clock

path = os.path.join(tempfile.mkdtemp(), "tokens.db")

Expand All @@ -28,8 +29,9 @@ limit = token_rate_limit(60_000, estimate=2_000, block=False, store=SQLiteTokenW
def complete(prompt: str) -> dict[str, object]:
return {"usage": {"input_tokens": 500, "output_tokens": 100}}

complete("hello") # reserves 2000, settles at the real 600, for the whole fleet
assert 59_000 < limit.available < 59_500
with fake_clock():
complete("hello") # reserves 2000, settles at the real 600, for the whole fleet
assert limit.available == 59_400
```

| Window | Shares across | Notes |
Expand Down
6 changes: 4 additions & 2 deletions docs/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2386,6 +2386,7 @@ import tempfile

from python_wrap.llm import token_rate_limit
from python_wrap.llm_shared import SQLiteTokenWindow
from python_wrap.testing import fake_clock

path = os.path.join(tempfile.mkdtemp(), "tokens.db")

Expand All @@ -2396,8 +2397,9 @@ limit = token_rate_limit(60_000, estimate=2_000, block=False, store=SQLiteTokenW
def complete(prompt: str) -> dict[str, object]:
return {"usage": {"input_tokens": 500, "output_tokens": 100}}

complete("hello") # reserves 2000, settles at the real 600, for the whole fleet
assert 59_000 < limit.available < 59_500
with fake_clock():
complete("hello") # reserves 2000, settles at the real 600, for the whole fleet
assert limit.available == 59_400
```

| Window | Shares across | Notes |
Expand Down
14 changes: 12 additions & 2 deletions examples/projects/llm_gateway/tests/test_llm_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ def clean_chaos() -> None:
chaos.clear()


@pytest.fixture
def signals_usable_for_layout(monkeypatch: pytest.MonkeyPatch) -> None:
import importlib

doctor_module = importlib.import_module("python_wrap.doctor")
monkeypatch.setattr(doctor_module, "_preemptive", lambda use_signals: use_signals is not False)


def test_happy_path_is_cached_traced_and_priced(tmp_path: Path) -> None:
gateway, tape = build_gateway(tmp_path / "audit.jsonl")
first = gateway.chat("acme", "What is a bulkhead?")
Expand Down Expand Up @@ -82,7 +90,9 @@ def test_healthy_stream_records_usage() -> None:
assert gateway.stack("acme").spend.spent().tokens > 0


def test_python_wrap_cli_surfaces(capsys: pytest.CaptureFixture[str]) -> None:
def test_python_wrap_cli_surfaces(
capsys: pytest.CaptureFixture[str], signals_usable_for_layout: None
) -> None:
assert python_wrap_cli(["doctor", "gateway_app.app:acme_chat"]) == 0 # no errors
report = capsys.readouterr().out
for layer in ("cache", "budget", "limiter", "fallback", "timeout"):
Expand All @@ -94,7 +104,7 @@ def test_python_wrap_cli_surfaces(capsys: pytest.CaptureFixture[str]) -> None:
assert "Budget" in capsys.readouterr().out


def test_doctor_findings_are_available_to_code() -> None:
def test_doctor_findings_are_available_to_code(signals_usable_for_layout: None) -> None:
gateway, _ = build_gateway()
codes = {finding.code for finding in gateway.doctor_findings("acme")}
assert codes <= {"PW006"} # budget sits outside the fallback chain on purpose
10 changes: 9 additions & 1 deletion examples/projects/support_agent/tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
MakeApp = Callable[..., SupportApp]


@pytest.fixture
def signals_usable_for_layout(monkeypatch: pytest.MonkeyPatch) -> None:
import importlib

doctor_module = importlib.import_module("python_wrap.doctor")
monkeypatch.setattr(doctor_module, "_preemptive", lambda use_signals: use_signals is not False)


def test_happy_path_refunds_and_emails(make_app: MakeApp) -> None:
app = make_app()
result = app.handle(TICKET, run_id="t-1")
Expand Down Expand Up @@ -117,7 +125,7 @@ def test_both_models_rate_limited_retries_after_retry_after(make_app: MakeApp, c
assert len(app.payments.refunds) == 1


def test_doctor_is_happy_with_the_stack(make_app: MakeApp) -> None:
def test_doctor_is_happy_with_the_stack(make_app: MakeApp, signals_usable_for_layout: None) -> None:
app = make_app()
llm_report = explain(app.ask)
assert llm_report.ok and llm_report.findings == (), str(llm_report)
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Issues = "https://github.com/LitePy/PythonWrap/issues"
Changelog = "https://github.com/LitePy/PythonWrap/blob/main/CHANGELOG.md"

[dependency-groups]
dev = [
core-test = [
"pytest>=9.2.0",
"pytest-cov>=6.0",
"pytest-asyncio>=1.4.1.post1",
Expand All @@ -71,6 +71,9 @@ dev = [
"mypy>=2.4.1",
"opentelemetry-api>=1.45.2",
"opentelemetry-sdk>=1.45.1",
]
dev = [
{ include-group = "core-test" },
"langchain-core>=0.3,<2",
]
docs = [
Expand Down
8 changes: 5 additions & 3 deletions src/python_wrap/async_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
_TAG_PREFIX,
CacheInfo,
_async_tag_clients,
_async_tag_store_owners,
_await_shared,
_decode,
_exception_types,
_make_key_builder,
_register_tag_client,
_shared_future,
_tag_versions,
_ttl_seconds,
Expand Down Expand Up @@ -513,11 +515,11 @@ async def main() -> None:
tag_client: Any = getattr(store, "client", None) if tags is not None else None
tag_async = tag_client is not None and _core.is_async(tag_client.get)
if tag_async:
_async_tag_clients[id(tag_client)] = tag_client
_register_tag_client(_async_tag_clients, _async_tag_store_owners, tag_client, store)
elif tag_client is not None:
from python_wrap.caching import _tag_clients
from python_wrap.caching import _tag_clients, _tag_store_owners

_tag_clients[id(tag_client)] = tag_client
_register_tag_client(_tag_clients, _tag_store_owners, tag_client, store)

async def versions(names: list[str]) -> dict[str, str] | None:
if not tag_async:
Expand Down
51 changes: 44 additions & 7 deletions src/python_wrap/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,8 +534,47 @@ def put(self, k: Hashable, entry: tuple[Any, float | None, bool, float | None])
# Bumped when _local_tags is cleared, so every entry written before reads as stale
# (never as fresh, which a plain eviction could cause).
_tag_epoch = [0]
_tag_clients: dict[int, Any] = {} # sync Redis clients of tagged shared caches
_async_tag_clients: dict[int, Any] = {} # redis.asyncio clients (amemoize)
# Weak on purpose: a client nothing else holds can no longer write through a store, so
# it needs no invalidation. A strong registry kept every client alive for the whole
# process, and one closed client made invalidate_tags fail for every tag.
_tag_clients: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
_async_tag_clients: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
_tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
_async_tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
_tag_registry_lock = threading.RLock()


def _register_tag_client(
registry: weakref.WeakValueDictionary[int, Any],
owner_registry: weakref.WeakValueDictionary[int, Any],
client: Any,
owner: Any,
) -> None:
try:
with _tag_registry_lock:
registry[id(client)] = client
except TypeError:
# Track the store instead when a compatible client disallows weak references.
# The memoized wrapper owns that store and it owns the client.
with _tag_registry_lock:
owner_registry[id(owner)] = owner


def _tag_client_targets(
registry: weakref.WeakValueDictionary[int, Any],
owner_registry: weakref.WeakValueDictionary[int, Any],
client: Any,
) -> list[Any]:
with _tag_registry_lock:
targets = dict(registry.items())
owners = list(owner_registry.values())
for owner in owners:
target = getattr(owner, "client", None)
if target is not None:
targets[id(target)] = target
if client is not None:
targets[id(client)] = client
return list(targets.values())


def _decode(value: Any) -> str:
Expand Down Expand Up @@ -569,8 +608,7 @@ def invalidate_tags(*names: str, client: Any = None) -> None:
for name in names:
token = uuid.uuid4().hex
_remember_local(name, token)
clients = {**_tag_clients, **({id(client): client} if client is not None else {})}
for target in clients.values():
for target in _tag_client_targets(_tag_clients, _tag_store_owners, client):
target.set(_TAG_PREFIX + digest(name), token)


Expand All @@ -579,8 +617,7 @@ async def ainvalidate_tags(*names: str, client: Any = None) -> None:
for name in names:
token = uuid.uuid4().hex
_remember_local(name, token)
clients = {**_async_tag_clients, **({id(client): client} if client is not None else {})}
for target in clients.values():
for target in _tag_client_targets(_async_tag_clients, _async_tag_store_owners, client):
await target.set(_TAG_PREFIX + digest(name), token)


Expand Down Expand Up @@ -764,7 +801,7 @@ def memoize(
lock_backend = lock # the name `lock` is reused below for the cache's own mutex
tag_client = getattr(store, "client", None) if tags is not None else None
if tag_client is not None:
_tag_clients[id(tag_client)] = tag_client
_register_tag_client(_tag_clients, _tag_store_owners, tag_client, store)
if maxsize is not None and maxsize < 1:
raise ValueError("maxsize must be a positive integer or None")
if store is not None:
Expand Down
14 changes: 13 additions & 1 deletion src/python_wrap/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ async def _await_value(awaitable: Awaitable[Any]) -> Any:
def _call_in_thread(fn: Callable[[], Any], remaining: float | None) -> bool:
"""Run ``fn`` (awaiting an awaitable result) in a daemon thread; False on timeout."""
outcome: list[BaseException] = []
deadline = None if remaining is None else time.monotonic() + remaining

if deadline is not None and _remaining(deadline) == 0:
return False

def target() -> None:
try:
Expand All @@ -165,7 +169,11 @@ def target() -> None:

thread = threading.Thread(target=target, name="python-wrap-shutdown", daemon=True)
thread.start()
thread.join(remaining)
while thread.is_alive():
left = _remaining(deadline)
if left == 0:
break
thread.join(left)
if thread.is_alive():
return False
if outcome:
Expand Down Expand Up @@ -411,6 +419,10 @@ def drain(self, timeout: float | None = 30, *, strict: bool = False) -> Shutdown
reports.append(
self._record(item.name, "ok" if finished else "timeout", None, began)
)
if item.kind == "callable" and left is not None and not finished:
# `_call_in_thread` can return just after the deadline while a
# coarse clock still reports a sliver left. Count it as spent.
deadline = time.monotonic()
return self._finish_strict(self._complete(reports, start), strict)

def _run_sync(self, item: _Item, remaining: float | None) -> bool:
Expand Down
10 changes: 5 additions & 5 deletions src/python_wrap/llm_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def _step(
if capacity > 0:
grown = capacity if level is None else level + max(now - stamp, 0.0) * rate
level = min(capacity, grown)
stamp = now
stamp = max(stamp, now)
result = 0.0
if op == "reserve":
assert level is not None
Expand All @@ -240,7 +240,7 @@ def _step(
elif op == "observe":
if a >= 0:
level = a if level is None else min(level, a)
stamp = now
stamp = max(stamp, now)
if b > 0:
blocked = max(blocked, now + b)
result = max(blocked - now, 0.0)
Expand All @@ -263,7 +263,7 @@ def _step(
local blocked=tonumber(h[3]) or 0
if cap>0 then
if level==nil then level=cap else level=math.min(cap, level+math.max(now-stamp,0)*rate) end
stamp=now
stamp=math.max(stamp,now)
end
local result=0
if op=='reserve' then
Expand All @@ -278,7 +278,7 @@ def _step(
elseif op=='observe' then
if a>=0 then
if level==nil then level=a else level=math.min(level,a) end
stamp=now
stamp=math.max(stamp,now)
end
if b>0 then blocked=math.max(blocked, now+b) end
result=math.max(blocked-now,0)
Expand Down Expand Up @@ -534,8 +534,8 @@ def path(self) -> str:
return self._file.path

def _once(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
now = _core.wall_time()
with self._file.connection() as conn:
now = _core.wall_time()
row = conn.execute(
"SELECT level, stamp, blocked FROM windows WHERE name=?", (self.name,)
).fetchone()
Expand Down
Loading
Loading