From 6840c426f1c38e32e766d07efd3f38678928fe44 Mon Sep 17 00:00:00 2001 From: Mahmoud Ahmed Date: Thu, 26 Nov 2026 14:03:03 +0200 Subject: [PATCH] fix: repair CI portability and shared state timing --- .github/workflows/ci.yml | 12 +- .github/workflows/docs.yml | 8 +- CHANGELOG.md | 9 ++ .../ai/shared-limits-and-cassettes.md | 6 +- docs/llms-full.txt | 6 +- .../llm_gateway/tests/test_llm_gateway.py | 14 +- .../support_agent/tests/test_agent.py | 10 +- pyproject.toml | 5 +- src/python_wrap/async_cache.py | 8 +- src/python_wrap/caching.py | 51 ++++++- src/python_wrap/lifecycle.py | 14 +- src/python_wrap/llm_shared.py | 10 +- tests/test_adapters_sdk.py | 3 +- tests/test_cache_coordination.py | 144 +++++++++++++++++- tests/test_doctor.py | 26 +++- tests/test_lifecycle.py | 25 +++ tests/test_llm_cassette.py | 3 + tests/test_llm_shared.py | 26 +++- tests/test_observability.py | 8 +- uv.lock | 21 +++ 20 files changed, 367 insertions(+), 42 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bdb5a38..e4d7262 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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: @@ -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 @@ -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()" @@ -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 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index ab3081b..7da8993 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -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 }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 996cac1..fe80257 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/features/ai/shared-limits-and-cassettes.md b/docs/features/ai/shared-limits-and-cassettes.md index 10eb9df..67430e2 100644 --- a/docs/features/ai/shared-limits-and-cassettes.md +++ b/docs/features/ai/shared-limits-and-cassettes.md @@ -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") @@ -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 | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index f2ab6ca..9d92b50 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -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") @@ -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 | diff --git a/examples/projects/llm_gateway/tests/test_llm_gateway.py b/examples/projects/llm_gateway/tests/test_llm_gateway.py index 60ddc96..ae035c7 100644 --- a/examples/projects/llm_gateway/tests/test_llm_gateway.py +++ b/examples/projects/llm_gateway/tests/test_llm_gateway.py @@ -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?") @@ -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"): @@ -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 diff --git a/examples/projects/support_agent/tests/test_agent.py b/examples/projects/support_agent/tests/test_agent.py index 34385c1..7d17cf9 100644 --- a/examples/projects/support_agent/tests/test_agent.py +++ b/examples/projects/support_agent/tests/test_agent.py @@ -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") @@ -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) diff --git a/pyproject.toml b/pyproject.toml index a87069b..521165e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", @@ -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 = [ diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 35b50eb..673b7fa 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -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, @@ -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: diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 589a274..992afda 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -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: @@ -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) @@ -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) @@ -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: diff --git a/src/python_wrap/lifecycle.py b/src/python_wrap/lifecycle.py index 97c4dcb..7509636 100644 --- a/src/python_wrap/lifecycle.py +++ b/src/python_wrap/lifecycle.py @@ -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: @@ -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: @@ -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: diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index 613a82d..d2b9033 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -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 @@ -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) @@ -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 @@ -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) @@ -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() diff --git a/tests/test_adapters_sdk.py b/tests/test_adapters_sdk.py index 508fdd1..25d6036 100644 --- a/tests/test_adapters_sdk.py +++ b/tests/test_adapters_sdk.py @@ -1506,6 +1506,7 @@ def test_limiter_wait_survives_float_precision_at_large_clock_values() -> None: def test_guarded_clients_example_runs() -> None: + import os import subprocess import sys from pathlib import Path @@ -1517,7 +1518,7 @@ def test_guarded_clients_example_runs() -> None: capture_output=True, text=True, timeout=30, - env={"PYTHONPATH": str(root / "src")}, + env={**os.environ, "PYTHONPATH": str(root / "src")}, check=False, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_cache_coordination.py b/tests/test_cache_coordination.py index 267683e..79ae2f4 100644 --- a/tests/test_cache_coordination.py +++ b/tests/test_cache_coordination.py @@ -3,16 +3,20 @@ from __future__ import annotations import asyncio +import gc +import json import threading import time +import weakref from concurrent.futures import ThreadPoolExecutor from typing import Any import pytest from python_wrap import ainvalidate_tags, amemoize, invalidate_tags, memoize -from python_wrap.async_cache import AsyncMemoryStore +from python_wrap.async_cache import AsyncMemoryStore, AsyncRedisStore from python_wrap.coordination import LocalLease +from python_wrap.stores import RedisStore from python_wrap.testing import fake_clock @@ -45,6 +49,80 @@ def __len__(self) -> int: return len(self.data) +class SyncRedis: + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.set_calls = 0 + self.closed = False + + def get(self, key: str) -> bytes | None: + return self.data.get(key) + + def set(self, key: str, value: bytes, **_: Any) -> bool: + if self.closed: + raise RuntimeError("client is closed") + self.set_calls += 1 + self.data[key] = value + return True + + def delete(self, *keys: str) -> int: + return sum(self.data.pop(key, None) is not None for key in keys) + + def scan_iter(self, **_: Any) -> Any: + return iter(self.data) + + def close(self) -> None: + self.closed = True + + +class AsyncRedis: + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.set_calls = 0 + self.closed = False + + async def get(self, key: str) -> bytes | None: + return self.data.get(key) + + async def set(self, key: str, value: bytes, **_: Any) -> bool: + if self.closed: + raise RuntimeError("client is closed") + self.set_calls += 1 + self.data[key] = value + return True + + async def delete(self, *keys: str) -> int: + return sum(self.data.pop(key, None) is not None for key in keys) + + def close(self) -> None: + self.closed = True + + +class SlottedRedis: + __slots__ = ("closed", "data", "set_calls") + + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.set_calls = 0 + self.closed = False + + def get(self, key: str) -> bytes | None: + return self.data.get(key) + + def set(self, key: str, value: bytes, **_: Any) -> bool: + if self.closed: + raise RuntimeError("client is closed") + self.set_calls += 1 + self.data[key] = value + return True + + def delete(self, *keys: str) -> int: + return sum(self.data.pop(key, None) is not None for key in keys) + + def scan_iter(self, **_: Any) -> Any: + return iter(self.data) + + def test_twenty_workers_missing_one_key_compute_once() -> None: store, calls = DictStore(), [] start = threading.Barrier(20) @@ -91,6 +169,70 @@ def orders(customer_id: int) -> int: assert calls == [7, 8, 7] +def test_redis_tag_registry_is_weak_and_explicit_client_is_deduplicated() -> None: + client = SyncRedis() + client_ref = weakref.ref(client) + store = RedisStore(client, "cache:", dumps=json.dumps, loads=json.loads) + calls: list[int] = [] + + @memoize(store=store, tags=lambda: ["t"]) + def value() -> int: + calls.append(1) + return len(calls) + + assert value() == 1 + client.set_calls = 0 + invalidate_tags("t", client=client) + assert client.set_calls == 1 + assert value() == 2 + + client.close() + del value, store, client + gc.collect() + assert client_ref() is None + invalidate_tags("after-gc") + + +def test_async_redis_tag_registry_is_weak_and_explicit_client_is_deduplicated() -> None: + client = AsyncRedis() + client_ref = weakref.ref(client) + store = AsyncRedisStore(client, "cache:", dumps=json.dumps, loads=json.loads) + calls: list[int] = [] + + @amemoize(store=store, tags=lambda: ["t"]) + async def value() -> int: + calls.append(1) + return len(calls) + + async def check(cache: Any, redis: AsyncRedis) -> None: + assert await cache() == 1 + redis.set_calls = 0 + await ainvalidate_tags("t", client=redis) + assert redis.set_calls == 1 + assert await cache() == 2 + + asyncio.run(check(value, client)) + client.close() + del value, store, client + gc.collect() + assert client_ref() is None + asyncio.run(ainvalidate_tags("after-gc")) + + +def test_tagged_slotted_redis_client_uses_weak_store_owner() -> None: + client = SlottedRedis() + store = RedisStore(client, "slotted:", dumps=json.dumps, loads=json.loads) + + @memoize(store=store, tags=lambda: ["slotted-tag"]) + def value() -> int: + return 1 + + assert value() == 1 + client.set_calls = 0 + invalidate_tags("slotted-tag") + assert client.set_calls == 1 + + def test_invalidation_during_compute_leaves_entry_stale() -> None: calls: list[int] = [] diff --git a/tests/test_doctor.py b/tests/test_doctor.py index d99b6e6..8a67f31 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -28,6 +28,14 @@ def codes(report: Report) -> list[str]: return [finding.code for finding in report.findings] +@pytest.fixture +def signals_usable_for_layout(monkeypatch): + 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_explain_lists_layers_in_canonical_order_with_settings(): budget = RetryBudget() stack = policy( @@ -122,7 +130,7 @@ def test_duplicate_retry_layers_multiply_attempts(): assert "PW007" in codes(report) -def test_doctor_walks_hand_stacked_decorators(): +def test_doctor_walks_hand_stacked_decorators(signals_usable_for_layout): @retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()) @timeout(2) @memoize @@ -136,7 +144,7 @@ def fetch(x: int) -> int: assert fetch(2) == 2 # inspecting did not break anything -def test_doctor_flags_retry_outside_breaker_order(): +def test_doctor_flags_retry_outside_breaker_order(signals_usable_for_layout): breaker = CircuitBreaker(name="b") @breaker @@ -168,7 +176,7 @@ def plain() -> None: ... assert report.layers == () and "no python-wrap layers" in str(report) -def test_presets_are_clean_and_ordered(): +def test_presets_are_clean_and_ordered(signals_usable_for_layout): for preset in ( http_client("svc"), db_call("db"), @@ -280,6 +288,18 @@ async def work() -> None: ... assert "PW009" not in codes(explain(policy(timeout=timeout(1, use_signals=False)))) +def test_pw009_when_signals_are_unavailable(monkeypatch): + import importlib + + timeouts = importlib.import_module("python_wrap.timeouts") + monkeypatch.setattr(timeouts, "_HAS_SETITIMER", False) + + @timeout(1) + def work() -> None: ... + + assert "PW009" in codes(doctor(work)) + + def test_pw009_off_main_thread(): import threading diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py index 97ae3b5..db19a5b 100644 --- a/tests/test_lifecycle.py +++ b/tests/test_lifecycle.py @@ -90,6 +90,31 @@ def test_slow_callable_times_out_and_budget_skips_the_rest(manager: ShutdownMana assert [i.name for i in report.timed_out] == ["slow", "skipped"] +def test_timeout_exhausts_budget_even_when_the_wait_returns_early( + manager: ShutdownManager, monkeypatch: pytest.MonkeyPatch +) -> None: + import threading + + called: list[str] = [] + manager.register(lambda: (called.append("slow"), threading.Event().wait(1)), name="slow") + manager.register(lambda: called.append("skipped"), name="skipped") + + original_join = threading.Thread.join + first_join = True + + def early_join(thread: threading.Thread, timeout: float | None = None) -> None: + nonlocal first_join + if thread.name == "python-wrap-shutdown" and first_join: + first_join = False + return + original_join(thread, timeout) + + monkeypatch.setattr(threading.Thread, "join", early_join) + report = manager.drain(timeout=0.05) + assert called == ["slow"] + assert [item.status for item in report.items] == ["timeout", "timeout"] + + def test_async_callable_in_sync_drain(manager: ShutdownManager) -> None: done: list[str] = [] diff --git a/tests/test_llm_cassette.py b/tests/test_llm_cassette.py index 115500d..7ca432e 100644 --- a/tests/test_llm_cassette.py +++ b/tests/test_llm_cassette.py @@ -287,6 +287,9 @@ def test_response_redaction_is_opt_in(self, path: str) -> None: text = Path(path).read_text() assert "pw-123456" not in text and "output_tokens" in text + @pytest.mark.skipif( + os.name == "nt", reason="POSIX file permission bits are not available on Windows" + ) def test_file_is_private(self, path: str) -> None: record(path, Wire(), Req({})) assert os.stat(path).st_mode & 0o077 == 0 diff --git a/tests/test_llm_shared.py b/tests/test_llm_shared.py index 3d43075..1bf742d 100644 --- a/tests/test_llm_shared.py +++ b/tests/test_llm_shared.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import contextlib import os import sqlite3 import subprocess @@ -124,6 +125,12 @@ def test_arbitrary_headers_never_raise(self, headers: dict[str, str]) -> None: class TestStep: + def test_clock_rollback_does_not_refill_the_same_interval_twice(self) -> None: + state, _ = _step(None, "reserve", 100, 0, 100, 1, 10.0) + state, _ = _step(state, "level", 0, 0, 100, 1, 5.0) + state, level = _step(state, "level", 0, 0, 100, 1, 10.0) + assert level == 0 + def test_new_bucket_is_full_and_reserve_takes_tokens(self) -> None: state, wait = _step(None, "reserve", 40, 0, 100, 1, 10.0) assert wait == 0 and state[0] == 60 @@ -247,7 +254,7 @@ def test_observe_headers_makes_every_worker_back_off(self, db: str, fake_clock: fake_clock.advance(7) assert b(lambda: "x")() == "x" - def test_remaining_header_lowers_shared_level(self, db: str) -> None: + def test_remaining_header_lowers_shared_level(self, db: str, fake_clock: Any) -> None: a = token_rate_limit(6000, estimate=10, store=SQLiteTokenWindow(db)) b = token_rate_limit(6000, estimate=10, store=SQLiteTokenWindow(db)) a.observe_headers({"x-ratelimit-remaining-tokens": "250"}) @@ -437,6 +444,23 @@ def ask() -> Any: ask() +def test_sqlite_samples_time_after_acquiring_the_write_lock( + db: str, fake_clock: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + window = SQLiteTokenWindow(db, fail_open=False) + assert window.reserve(10, 10, 1) == 0 + connection = window._file.connection + + @contextlib.contextmanager + def delayed_connection() -> Any: + with connection() as conn: + fake_clock.advance(10) + yield conn + + monkeypatch.setattr(window._file, "connection", delayed_connection) + assert window.reserve(10, 10, 1) == 0 + + # -------------------------------------------------------------- cross-process admission _WORKER = textwrap.dedent( diff --git a/tests/test_observability.py b/tests/test_observability.py index 87b6ff6..5024189 100644 --- a/tests/test_observability.py +++ b/tests/test_observability.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import Any + from python_wrap import memoize from python_wrap.observability import Telemetry @@ -128,9 +130,7 @@ def _points(reader, name): ] -def test_gave_up_counter_and_attempt_spans_with_durations(): - import time - +def test_gave_up_counter_and_attempt_spans_with_durations(fake_clock: Any) -> None: import pytest from python_wrap import retry @@ -140,7 +140,7 @@ def test_gave_up_counter_and_attempt_spans_with_durations(): @retry(max_attempts=3, delay=0) def flaky(): - time.sleep(0.002) + fake_clock.advance(0.002) raise ConnectionError handle = enable( diff --git a/uv.lock b/uv.lock index b74aeed..240e0f6 100644 --- a/uv.lock +++ b/uv.lock @@ -3294,6 +3294,17 @@ pydantic-ai = [ ] [package.dev-dependencies] +core-test = [ + { name = "hypothesis", version = "6.168.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "hypothesis", version = "6.170.12", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "mypy" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-sdk" }, + { name = "pytest" }, + { name = "pytest-asyncio" }, + { name = "pytest-cov" }, + { name = "ruff" }, +] dev = [ { name = "hypothesis", version = "6.168.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "hypothesis", version = "6.170.12", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, @@ -3330,6 +3341,16 @@ requires-dist = [ provides-extras = ["anthropic", "langchain", "openai", "openai-agents", "pydantic-ai"] [package.metadata.requires-dev] +core-test = [ + { name = "hypothesis", specifier = ">=6.100" }, + { name = "mypy", specifier = ">=2.4.1" }, + { name = "opentelemetry-api", specifier = ">=1.45.2" }, + { name = "opentelemetry-sdk", specifier = ">=1.45.1" }, + { name = "pytest", specifier = ">=9.2.0" }, + { name = "pytest-asyncio", specifier = ">=1.4.1.post1" }, + { name = "pytest-cov", specifier = ">=6.0" }, + { name = "ruff", specifier = ">=0.17.4" }, +] dev = [ { name = "hypothesis", specifier = ">=6.100" }, { name = "langchain-core", specifier = ">=0.3,<2" },