Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

perf(serve): cache canary policy and batch live outcome writes (#1712)

Aditya Pratap Singh943f16f32dee
diff --git a/changelog.d/0.75.1/1712.changed.md b/changelog.d/0.75.1/1712.changed.md
new file mode 100644
index 00000000..3763fd1a
--- /dev/null
+++ b/changelog.d/0.75.1/1712.changed.md
@@ -0,0 +1 @@
+- **Cache live canary policy and batch outcome writes**: keyed serving requests refresh the parsed policy when its file identity changes, and stats flush after 64 outcomes or two seconds, including an orderly-shutdown flush. Watch rollback takes effect on the next keyed request; superseded promotions cannot overwrite newer statistics. On-disk `canary-stats.json` and watch verdicts now lag traffic by the buffered window (normally up to 64 outcomes or two seconds); a crash can lose that window. Disk outages retain one pending batch but refuse additional outcomes, so outage losses can exceed one batch. Process-killing failures never reach recording. (#1320 by @akkupratap323 in #1712)
diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.md
index 88a0d056..e1bcce2d 100644
--- a/docs/adapters-and-governance.md
+++ b/docs/adapters-and-governance.md
@@ -155,6 +155,30 @@ directory containing `.soup/`, because the loop state and canary statistics path
resolved from the working directory. Clients choose their own stable key, so a client
can deliberately select a key that hashes into the canary bucket.
+The serving process caches the parsed policy using the state file's
+`(st_mtime_ns, st_size, st_ino)` identity. Atomic replacement invalidates it,
+so a rollback written by `soup loop watch` affects the next keyed request.
+State-path failures are warned about once per failure episode rather than on every request;
+a successful policy read allows a later failure to warn again.
+
+Outcome counters are buffered per serving app and persisted after 64 completed
+outcomes or two seconds from the first pending outcome, whichever comes first.
+Orderly shutdown flushes the remaining counters. With a healthy writable filesystem,
+an abrupt crash can lose the unflushed window (at most one 64-outcome batch, including
+a flush in progress, normally at most two seconds); scheduling delays or disk errors
+can delay persistence. A failed write retains the pending counters for retry.
+While that batch is full, additional outcomes are refused until persistence recovers;
+a disk outage can therefore lose more outcomes than the normal one-batch crash window.
+The on-disk `canary-stats.json` and watch verdicts lag traffic by the buffered window
+(normally up to 64 outcomes or two seconds). Rollout IDs prevent promotions from sharing
+samples. Pending samples and late completions from superseded promotions are discarded
+rather than replacing the new rollout's file. The existing stats lock protects threads
+in one process, not multiple server processes writing the same file.
+
+A canary that kills the serving process never reaches outcome recording: recording
+happens only after generation returns or raises. Such crashes remain invisible to
+the canary verdict unless external restart monitoring detects them.
+
## Knowledge Editing (`soup edit set`, ROME / MEMIT / AlphaEdit)
diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.py
index a2a1185d..31299433 100644
--- a/src/soup_cli/commands/serve.py
+++ b/src/soup_cli/commands/serve.py
@@ -1785,9 +1785,27 @@ def _create_app(
status_code=401, detail="Invalid or missing bearer token"
)
+ from collections.abc import AsyncIterator
+ from contextlib import asynccontextmanager
+
+ from soup_cli.utils.canary_router import BufferedCanaryOutcomes, CanaryStateCache
from soup_cli.utils.metrics import ServerMetrics
- app = FastAPI(title="Soup Inference Server", version="1.0.0")
+ canary_state = CanaryStateCache(canary_state_path)
+ canary_outcomes = BufferedCanaryOutcomes(canary_stats_path, state_cache=canary_state)
+
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
+ try:
+ yield
+ finally:
+ try:
+ canary_outcomes.close()
+ except (OSError, TypeError, ValueError):
+ logger.warning("canary shutdown flush failed", exc_info=True)
+
+ app = FastAPI(title="Soup Inference Server", version="1.0.0", lifespan=lifespan)
+ app.state.canary_outcomes = canary_outcomes
# Loopback-only CORS, and three layers behind it:
# * CORS limits which browser pages may READ a response. It does not stop
@@ -1862,16 +1880,27 @@ def _create_app(
with active_lock:
return active_state["active"]
+ _canary_warnings: set[str] = set()
+ _canary_warning_lock = threading.Lock()
+
+ def _warn_canary_once(message: str, *, exc_info: bool = False) -> None:
+ with _canary_warning_lock:
+ if message in _canary_warnings:
+ return
+ _canary_warnings.add(message)
+ logger.warning(message, exc_info=exc_info)
+
def _canary_adapter(conversation_id: Optional[str]):
"""Resolve one automatic canary route, or preserve normal activation."""
if not conversation_id or _mole_runtime is not None or not _peft_adapter_names:
return None, None
from soup_cli.utils.canary_router import CanaryPolicy, route
- from soup_cli.utils.loop_state import read_state
try:
- state = read_state(canary_state_path)
- if state.canary_active is None or not state.canary_traffic_pct:
+ state = canary_state.get()
+ with _canary_warning_lock:
+ _canary_warnings.discard("canary policy unavailable")
+ if state is None or state.canary_active is None or not state.canary_traffic_pct:
return None, None
policy = CanaryPolicy(
stable=state.served_model,
@@ -1880,11 +1909,11 @@ def _create_app(
)
decision = route(policy, conversation_id)
except (FileNotFoundError, OSError, TypeError, ValueError):
- logger.debug("canary policy unavailable", exc_info=True)
+ _warn_canary_once("canary policy unavailable", exc_info=True)
return None, None
if decision.bucket == "canary":
if decision.adapter not in _peft_adapter_names:
- logger.warning("canary adapter %r is not loaded", decision.adapter)
+ _warn_canary_once(f"canary adapter {decision.adapter!r} is not loaded")
return None, None
return decision.adapter, (policy, decision.bucket, state.canary_rollout_id)
if decision.adapter in _peft_adapter_names:
@@ -1897,19 +1926,17 @@ def _create_app(
def _record_canary_outcome(tracking, ok: bool) -> None:
if tracking is None:
return
- from soup_cli.utils.canary_router import record_bucket_outcome
policy, bucket, rollout_id = tracking
try:
- record_bucket_outcome(
+ canary_outcomes.record(
policy,
bucket,
ok,
rollout_id=rollout_id,
- path=canary_stats_path,
)
except (OSError, TypeError, ValueError):
- logger.warning("canary outcome write failed", exc_info=True)
+ _warn_canary_once("canary outcome write failed", exc_info=True)
@app.get("/health")
def health():
diff --git a/src/soup_cli/utils/canary_router.py b/src/soup_cli/utils/canary_router.py
index 1825ae82..99c57391 100644
--- a/src/soup_cli/utils/canary_router.py
+++ b/src/soup_cli/utils/canary_router.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import hashlib
import json
+import logging
import math
import os
import threading
@@ -23,6 +24,7 @@ from dataclasses import dataclass, field
from types import MappingProxyType
from typing import Mapping, Optional
+from soup_cli.utils.loop_state import LoopState
from soup_cli.utils.paths import atomic_write_text, enforce_under_cwd_and_no_symlink
@@ -73,6 +75,43 @@ _MAX_STATS_BYTES = 64 * 1024
_STATS_LOCK = threading.Lock()
+class CanaryStateCache:
+ """App-local state cache invalidated by atomic replacements, not just mtime."""
+
+ def __init__(self, path: Optional[str] = None) -> None:
+ from soup_cli.utils.loop_state import default_state_path
+
+ self.path = path if path is not None else default_state_path()
+ self._key: Optional[tuple[int, int, int]] = None
+ self._state: Optional[LoopState] = None
+ self._lock = threading.Lock()
+
+ def get(self) -> Optional[LoopState]:
+ from soup_cli.utils.loop_state import read_state
+
+ with self._lock:
+ enforce_under_cwd_and_no_symlink(self.path, "canary state path")
+ try:
+ info = os.stat(self.path)
+ except FileNotFoundError:
+ self._key = self._state = None
+ return None
+ key = (info.st_mtime_ns, info.st_size, info.st_ino)
+ if key != self._key:
+ # Cache only successful reads. A concurrent replacement causes
+ # another refresh on the next request instead of a stale policy.
+ state = read_state(self.path)
+ self._state, self._key = state, key
+ return self._state
+
+ def matches(self, policy: CanaryPolicy, rollout_id: Optional[str]) -> bool:
+ """Whether these observations still belong to the active promotion."""
+ state = self.get()
+ return state is not None and (
+ state.served_model, state.canary_active, state.canary_rollout_id
+ ) == (policy.stable, policy.canary, rollout_id)
+
+
def _bucket_for_key(key: str) -> int:
"""Deterministic 4-hex-digit bucket via SHA-256 (key fingerprint)."""
if not isinstance(key, str):
@@ -265,20 +304,33 @@ def record_bucket_outcome(
not isinstance(rollout_id, str) or not rollout_id or "\x00" in rollout_id
):
raise ValueError("rollout_id must be a non-empty NUL-free string or None")
+ delta = BucketStats()
+ delta.record(bucket, ok)
+ _record_bucket_counts(policy, delta.snapshot(), rollout_id=rollout_id, path=path)
+
+
+def _record_bucket_counts(
+ policy: CanaryPolicy, counts: Mapping[str, int], *,
+ rollout_id: Optional[str], path: Optional[str],
+ state_cache: Optional[CanaryStateCache] = None,
+) -> None:
+ """Merge one batch under the existing process-local persistence lock."""
target = path or default_stats_path()
with _STATS_LOCK:
+ if state_cache is not None and not state_cache.matches(policy, rollout_id):
+ return
stats = read_bucket_stats(
stable=policy.stable,
canary=policy.canary,
rollout_id=rollout_id,
path=target,
)
- stats.record(bucket, ok)
+ totals = {name: value + counts[name] for name, value in stats.snapshot().items()}
payload = {
"stable": policy.stable,
"canary": policy.canary,
"rollout_id": rollout_id,
- **dict(stats.snapshot()),
+ **totals,
}
atomic_write_text(
json.dumps(payload, allow_nan=False, indent=2, sort_keys=True),
@@ -286,3 +338,115 @@ def record_bucket_outcome(
prefix=".canary_stats_",
field="canary stats path",
)
+
+
+class BufferedCanaryOutcomes:
+ """Persist at 64 outcomes or two seconds, whichever comes first.
+
+ One buffer per serving app. Promotion changes retire the previous buffer
+ before accepting the next; shutdown cancels the timer and drains the tail.
+ """
+
+ def __init__(self, path: Optional[str] = None, *, batch_size: int = 64,
+ interval: float = 2.0, state_cache: Optional[CanaryStateCache] = None) -> None:
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1:
+ raise ValueError("batch_size must be a positive int")
+ if isinstance(interval, bool) or not math.isfinite(interval) or interval <= 0:
+ raise ValueError("interval must be positive and finite")
+ self.path = path if path is not None else default_stats_path()
+ self.batch_size = batch_size
+ self.interval = interval
+ self._state_cache = state_cache
+ self._lock = threading.Lock()
+ self._policy: Optional[CanaryPolicy] = None
+ self._rollout_id: Optional[str] = None
+ self._counts = BucketStats()
+ self._pending = 0
+ self._timer: Optional[threading.Timer] = None
+ self._closed = False
+ self._warned = False
+
+ def record(self, policy: CanaryPolicy, bucket: str, ok: bool, *,
+ rollout_id: Optional[str] = None) -> None:
+ if not isinstance(policy, CanaryPolicy):
+ raise TypeError("policy must be CanaryPolicy")
+ if policy.canary is None:
+ return
+ if rollout_id is not None and (
+ not isinstance(rollout_id, str) or not rollout_id or "\x00" in rollout_id
+ ):
+ raise ValueError("rollout_id must be a non-empty NUL-free string or None")
+ # Validate before changing the buffer or flushing another rollout.
+ delta = BucketStats()
+ delta.record(bucket, ok)
+ with self._lock:
+ if self._closed:
+ raise ValueError("canary outcome buffer is closed")
+ if not self._is_current(policy, rollout_id):
+ return
+ if self._policy is not None and (
+ (self._policy.stable, self._policy.canary, self._rollout_id)
+ != (policy.stable, policy.canary, rollout_id)
+ ):
+ self._flush_locked()
+ if self._pending >= self.batch_size:
+ self._flush_locked()
+ self._policy, self._rollout_id = policy, rollout_id
+ self._counts.record(bucket, ok)
+ self._pending += 1
+ if self._timer is None:
+ self._timer = threading.Timer(self.interval, self._timed_flush)
+ self._timer.daemon = True
+ self._timer.start()
+ if self._pending >= self.batch_size:
+ self._flush_locked()
+
+ def _is_current(self, policy: CanaryPolicy, rollout_id: Optional[str]) -> bool:
+ if self._state_cache is None:
+ return True
+ return self._state_cache.matches(policy, rollout_id)
+
+ def _flush_locked(self) -> None:
+ if self._pending:
+ assert self._policy is not None
+ # Check under the buffer lock, both when accepting and when flushing:
+ # an older in-flight request/timer cannot replace a new rollout's file.
+ _record_bucket_counts(self._policy, self._counts.snapshot(),
+ rollout_id=self._rollout_id, path=self.path,
+ state_cache=self._state_cache)
+ self._counts = BucketStats()
+ self._pending = 0
+ if self._timer is not None:
+ self._timer.cancel()
+ self._timer = None
+
+ def _timed_flush(self) -> None:
+ with self._lock:
+ if self._closed:
+ return
+ try:
+ self._flush_locked()
+ except (OSError, TypeError, ValueError):
+ if not self._warned:
+ logging.getLogger(__name__).warning("canary batch flush failed", exc_info=True)
+ self._warned = True
+ # Keep the batch for retry; a failed write never clears counters.
+ self._timer = threading.Timer(self.interval, self._timed_flush)
+ self._timer.daemon = True
+ self._timer.start()
+
+ def flush(self) -> None:
+ """Make the pending window durable (also useful before a local watch)."""
+ with self._lock:
+ self._flush_locked()
+
+ def close(self) -> None:
+ """Stop the timer and drain counters during orderly server shutdown."""
+ with self._lock:
+ self._closed = True
+ try:
+ self._flush_locked()
+ finally:
+ if self._timer is not None:
+ self._timer.cancel()
+ self._timer = None
diff --git a/tests/test_issue1320_canary_io.py b/tests/test_issue1320_canary_io.py
new file mode 100644
index 00000000..f3279411
--- /dev/null
+++ b/tests/test_issue1320_canary_io.py
@@ -0,0 +1,356 @@
+"""Canary hot-path IO frequency, durability, and rollout isolation."""
+
+import os
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import replace
+from pathlib import Path
+
+import pytest
+
+from soup_cli.utils import canary_router, loop_state
+from soup_cli.utils.canary_router import BufferedCanaryOutcomes, CanaryPolicy, CanaryStateCache
+from soup_cli.utils.loop_state import LoopState, write_state
+from tests.test_issue815_canary_runtime import (
+ _serve_with_canary,
+ _watch_once,
+ _write_canary_state,
+)
+
+
+def buffers(tmp_path: Path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ instances = []
+
+ def create(**kwargs):
+ instance = BufferedCanaryOutcomes(str(tmp_path / "stats.json"), **kwargs)
+ instances.append(instance)
+ return instance
+
+ yield create
+ for instance in instances:
+ instance.close()
+
+
+def test_unchanged_policy_is_parsed_once_and_missing_policy_is_not_read(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = tmp_path / "loop.yaml"
+ calls = []
+ original = loop_state.read_state
+
+ def read(path):
+ calls.append(path)
+ return original(path)
+
+ monkeypatch.setattr(loop_state, "read_state", read)
+ cache = CanaryStateCache(str(path))
+ for _ in range(100):
+ assert cache.get() is None
+ assert calls == []
+ state = LoopState(served_model="base", eval_suite="e", baseline="b")
+ write_state(state, str(path))
+ for _ in range(100):
+ assert cache.get().served_model == "base"
+ assert cache.get().canary_active is None
+ assert len(calls) == 1
+
+
+def test_atomic_replacement_with_same_mtime_and_size_invalidates_policy(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = tmp_path / "loop.yaml"
+ state = LoopState(served_model="base", eval_suite="e", baseline="b",
+ canary_active="candidate", canary_traffic_pct=50.0)
+ write_state(state, str(path))
+ cache = CanaryStateCache(str(path))
+ assert cache.get().canary_traffic_pct == 50.0
+ before = path.stat()
+ write_state(replace(state, canary_traffic_pct=10.0), str(path))
+ os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns))
+ assert path.stat().st_size == before.st_size
+ assert path.stat().st_ino != before.st_ino
+ assert cache.get().canary_traffic_pct == 10.0
+ path.unlink()
+ assert cache.get() is None
+
+
+def test_concurrent_outcomes_preserve_counts_with_batched_writes(buffers, monkeypatch):
+ writes = []
+ original = canary_router.atomic_write_text
+
+ def write(*args, **kwargs):
+ writes.append(1)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(canary_router, "atomic_write_text", write)
+ buffer = buffers(interval=60.0)
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ list(pool.map(lambda index: buffer.record(policy, "canary" if index % 2 else "stable",
+ index % 3 != 0, rollout_id="r"), range(257)))
+ assert len(writes) == 4 # Four complete 64-sample batches; one sample pending.
+ buffer.close()
+ assert len(writes) == 5
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=buffer.path).snapshot()
+ expected = {name: 0 for name in stats}
+ for index in range(257):
+ bucket = "canary" if index % 2 else "stable"
+ expected[f"{bucket}_{'ok' if index % 3 else 'major'}"] += 1
+ assert dict(stats) == expected
+
+
+def test_idle_partial_batch_flushes_without_another_request(buffers, monkeypatch):
+ written = threading.Event()
+ original = canary_router.atomic_write_text
+
+ def write(*args, **kwargs):
+ result = original(*args, **kwargs)
+ written.set()
+ return result
+
+ monkeypatch.setattr(canary_router, "atomic_write_text", write)
+ buffer = buffers(interval=0.02)
+ buffer.record(CanaryPolicy("base", "candidate", 50.0), "stable", True, rollout_id="r")
+ assert written.wait(2.0)
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=buffer.path)
+ assert stats.stable_ok == 1
+
+
+def test_promotion_change_keeps_rollout_counters_separate(buffers):
+ buffer = buffers(interval=60.0)
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ for _ in range(10):
+ buffer.record(policy, "canary", False, rollout_id="old")
+ buffer.record(policy, "stable", True, rollout_id="new")
+ buffer.close()
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="new",
+ path=buffer.path)
+ assert dict(stats.snapshot()) == {"stable_ok": 1, "stable_major": 0,
+ "canary_ok": 0, "canary_major": 0}
+
+
+def test_failed_flush_retains_the_batch_for_retry(buffers, monkeypatch):
+ buffer = buffers(batch_size=2, interval=60.0)
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ original = canary_router.atomic_write_text
+ buffer.record(policy, "canary", True, rollout_id="r")
+ with monkeypatch.context() as patch:
+ def fail(*args, **kwargs):
+ raise OSError("disk unavailable")
+ patch.setattr(canary_router, "atomic_write_text", fail)
+ with pytest.raises(OSError):
+ buffer.record(policy, "stable", False, rollout_id="r")
+ buffer.flush()
+ assert canary_router.atomic_write_text is original
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=buffer.path)
+ assert stats.canary_ok == 1 and stats.stable_major == 1
+
+
+def test_watch_rollback_is_visible_to_the_next_keyed_request(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ client, observed = _serve_with_canary(monkeypatch, state_path, stats_path,
+ adapters=("candidate",), fail_on="candidate")
+ with client:
+ for index in range(30):
+ response = client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": f"k{index}"})
+ assert response.status_code == 500
+ client.app.state.canary_outcomes.flush()
+ state, _ = _watch_once(tmp_path, state_path, stats_path)
+ assert state.canary_active is None
+ assert client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": "k0"}).status_code == 200
+ assert observed[-1] is None
+
+
+def test_orderly_app_shutdown_flushes_the_tail(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("candidate",))
+ with client:
+ response = client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": "k"})
+ assert response.status_code == 200
+ assert not stats_path.exists()
+ assert canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=str(stats_path)).canary_ok == 1
+
+
+def test_invalid_state_warning_is_emitted_once(tmp_path, monkeypatch, caplog):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ state_path.write_text("invalid json", encoding="utf-8")
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("candidate",))
+ with client:
+ for _ in range(5):
+ assert client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": "k"}).status_code == 200
+ assert sum(record.message == "canary policy unavailable" for record in caplog.records) == 1
+
+
+def test_late_old_rollout_completion_cannot_replace_new_statistics(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="old")
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("candidate",))
+ import soup_cli.commands.serve as serve
+
+ def generate(*args, **kwargs):
+ state = loop_state.read_state(str(state_path))
+ if state.canary_rollout_id == "old":
+ write_state(replace(state, canary_rollout_id="new"), str(state_path))
+ return "ok", 1, 1
+
+ monkeypatch.setattr(serve, "_generate_response", generate)
+ request = {"messages": [{"role": "user", "content": "hi"}], "conversation_id": "k"}
+ with client:
+ assert client.post("/v1/chat/completions", json=request).status_code == 200
+ client.app.state.canary_outcomes.flush()
+ assert not stats_path.exists()
+ assert client.post("/v1/chat/completions", json=request).status_code == 200
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="new",
+ path=str(stats_path))
+ assert stats.canary_ok == 1
+
+
[email protected]("active", [True, False])
+def test_live_keyed_requests_parse_an_unchanged_policy_only_once(tmp_path, monkeypatch, active):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ if not active:
+ state = loop_state.read_state(str(state_path))
+ write_state(replace(state, canary_active=None, canary_traffic_pct=None,
+ canary_rollout_id=None), str(state_path))
+ calls = []
+ original = loop_state.read_state
+
+ def read(path):
+ calls.append(path)
+ return original(path)
+
+ monkeypatch.setattr(loop_state, "read_state", read)
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("candidate",))
+ with client:
+ for _ in range(10):
+ response = client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": "k"})
+ assert response.status_code == 200
+ assert len(calls) == 1
+
+
+def test_pending_superseded_batch_does_not_replace_current_stats(buffers, tmp_path, monkeypatch):
+ state_path = tmp_path / "loop.yaml"
+ state = LoopState(served_model="base", eval_suite="e", baseline="b",
+ canary_active="candidate", canary_traffic_pct=50.0, canary_rollout_id="old")
+ write_state(state, str(state_path))
+ buffer = buffers(interval=60.0, state_cache=CanaryStateCache(str(state_path)))
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ buffer.record(policy, "canary", False, rollout_id="old")
+ write_state(replace(state, canary_rollout_id="new"), str(state_path))
+ canary_router.record_bucket_outcome(policy, "canary", True, rollout_id="new", path=buffer.path)
+ buffer.close()
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="new",
+ path=buffer.path)
+ assert stats.canary_ok == 1 and stats.canary_major == 0
+
+
+def test_in_place_edit_with_same_size_and_inode_invalidates_policy(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = tmp_path / "loop.yaml"
+ state = LoopState(served_model="base", eval_suite="e", baseline="b",
+ canary_active="candidate", canary_traffic_pct=50.0)
+ write_state(state, str(path))
+ cache = CanaryStateCache(str(path))
+ assert cache.get().canary_traffic_pct == 50.0
+ before = path.stat()
+ text = path.read_text(encoding="utf-8")
+ with open(path, "r+", encoding="utf-8", newline="") as handle:
+ handle.write(text.replace("50.0", "10.0"))
+ after = path.stat()
+ assert (after.st_ino, after.st_size) == (before.st_ino, before.st_size)
+ if after.st_mtime_ns == before.st_mtime_ns:
+ pytest.skip("filesystem timestamp too coarse for this check")
+ assert cache.get().canary_traffic_pct == 10.0
+
+
+def test_exactly_one_batch_is_persisted_without_waiting_for_the_next_outcome(buffers):
+ buffer = buffers(batch_size=64, interval=60.0)
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ for _ in range(63):
+ buffer.record(policy, "stable", True, rollout_id="r")
+ assert not os.path.exists(buffer.path)
+ buffer.record(policy, "stable", True, rollout_id="r")
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=buffer.path)
+ assert stats.stable_ok == 64
+
+
+def test_the_interval_runs_from_the_first_pending_outcome(buffers, monkeypatch):
+ created = []
+
+ class FakeTimer:
+ def __init__(self, interval, function):
+ created.append(interval)
+ self.daemon = False
+
+ def start(self):
+ pass
+
+ def cancel(self):
+ pass
+
+ monkeypatch.setattr(canary_router.threading, "Timer", FakeTimer)
+ buffer = buffers(interval=2.0)
+ policy = CanaryPolicy("base", "candidate", 50.0)
+ for _ in range(3):
+ buffer.record(policy, "stable", True, rollout_id="r")
+ assert created == [2.0]
+
+
+def test_timed_flush_retries_after_a_transient_write_error(buffers, monkeypatch):
+ original = canary_router.atomic_write_text
+ calls = []
+
+ def flaky(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ raise PermissionError("target locked")
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(canary_router, "atomic_write_text", flaky)
+ buffer = buffers(interval=0.05)
+ buffer.record(CanaryPolicy("base", "candidate", 50.0), "canary", False, rollout_id="r")
+ deadline = time.monotonic() + 3.0
+ while time.monotonic() < deadline and not os.path.exists(buffer.path):
+ time.sleep(0.02)
+ stats = canary_router.read_bucket_stats(stable="base", canary="candidate", rollout_id="r",
+ path=buffer.path)
+ assert len(calls) >= 2 and stats.canary_major == 1
+
+
+def test_policy_warning_returns_after_recovery(tmp_path, monkeypatch, caplog):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ valid = state_path.read_text(encoding="utf-8")
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("candidate",))
+ request = {"messages": [{"role": "user", "content": "hi"}], "conversation_id": "k"}
+ with client:
+ for text in ("invalid json", valid, "invalid again"):
+ state_path.write_text(text, encoding="utf-8")
+ assert client.post("/v1/chat/completions", json=request).status_code == 200
+ assert sum(record.message == "canary policy unavailable" for record in caplog.records) == 2
+
+
+def test_unloaded_adapter_warning_has_no_exception_traceback(tmp_path, monkeypatch, caplog):
+ monkeypatch.chdir(tmp_path)
+ state_path, stats_path = _write_canary_state(tmp_path, traffic_pct=100.0, rollout_id="r")
+ client, _ = _serve_with_canary(monkeypatch, state_path, stats_path, adapters=("other",))
+ with client:
+ assert client.post("/v1/chat/completions", json={"messages": [{"role": "user",
+ "content": "hi"}], "conversation_id": "k"}).status_code == 200
+ warning = next(record for record in caplog.records if "is not loaded" in record.message)
+ assert not warning.exc_info
diff --git a/tests/test_issue815_canary_runtime.py b/tests/test_issue815_canary_runtime.py
index 211cf64c..0446bfd6 100644
--- a/tests/test_issue815_canary_runtime.py
+++ b/tests/test_issue815_canary_runtime.py
@@ -84,6 +84,7 @@ def test_five_percent_policy_routes_live_serve_requests(tmp_path, monkeypatch):
canary_count = observed.count("candidate")
assert 10 <= canary_count <= 30
assert observed.count(None) == request_count - canary_count
+ client.app.state.canary_outcomes.close()
def test_failing_live_canary_requests_reach_the_rollout_stats(tmp_path, monkeypatch):
@@ -140,6 +141,7 @@ def test_failing_live_canary_requests_reach_the_rollout_stats(tmp_path, monkeypa
canary_count = observed.count("candidate")
stable_count = observed.count(None)
+ client.app.state.canary_outcomes.close()
stats = read_bucket_stats(
stable="base",
canary="candidate",
@@ -400,6 +402,7 @@ def test_keyed_stable_traffic_is_the_base_even_after_a_manual_cutover(
assert "other" not in observed
assert 0 < observed.count("candidate") < 100
+ client.app.state.canary_outcomes.close()
stats = read_bucket_stats(
stable="base", canary="candidate", rollout_id="rollout-cutover", path=str(stats_path)
)
@@ -430,6 +433,7 @@ def test_failing_live_canary_stream_requests_reach_the_rollout_stats(
assert response.status_code == 200
canary_count = observed.count("candidate")
+ client.app.state.canary_outcomes.close()
stats = read_bucket_stats(
stable="base", canary="candidate", rollout_id="rollout-stream", path=str(stats_path)
)