Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(loop): wire live canary routing and rollback (#1104)
Aditya Pratap Singheb652af4860e
diff --git a/changelog.d/0.75.1/1104.fixed.md b/changelog.d/0.75.1/1104.fixed.mdnew file mode 100644index 00000000..2309057a--- /dev/null+++ b/changelog.d/0.75.1/1104.fixed.md@@ -0,0 +1 @@+- **`soup loop canary` now routes keyed transformers requests at the configured traffic share and automatically clears a regressing canary (#815 by @akkupratap323 in #1104).** Serve records rollout-scoped generation outcomes for stable and canary buckets; `soup loop watch` evaluates those observations and persists a rollback after a `MAJOR` verdict, while explicit adapter selection keeps its existing behavior and the 100% activation endpoint still applies to requests without a conversation key.diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.mdindex 4f8d8167..5761a151 100644--- a/docs/adapters-and-governance.md+++ b/docs/adapters-and-governance.md@@ -121,8 +121,9 @@ soup loop replay iter-20260515T120000-abcdef01 --extract ./iter-dump# Background subprocess (writes PID, no shell)soup loop watch --detach-# Promote a canary at 5% traffic with auto-rollback on MAJOR verdict-soup loop canary registry://candidate --traffic 5% --autoroll-on-regress+# Start serve with the candidate loaded, then promote it at 5% traffic.+soup serve --model ./base --adapters candidate=./candidate+soup loop canary candidate --traffic 5% --autoroll-on-regress# Pause/resume the daemon between iterations (atomic state flip)soup loop pause@@ -132,7 +133,27 @@ soup loop resumesoup loop replay iter-20260515T120000-abcdef01```-State lives in `.soup/loop.yaml` (atomic write, cwd-contained, symlink-rejected). Per-iteration manifests under `.soup-loops/<iter-id>/iteration.json` are laid out so a v0.26 Soup Can can wrap them directly. The canary router is deterministic (SHA-256 hash of conversation id) and sticky-on-rollback — a flaky verdict can't ping-pong traffic between adapters.+State lives in `.soup/loop.yaml` (atomic write, cwd-contained, symlink-rejected). Per-iteration manifests under `.soup-loops/<iter-id>/iteration.json` are laid out so a v0.26 Soup Can can wrap them directly.++Canary routing is available on the transformers backend when the candidate name was+loaded with `soup serve --adapters`. Send a stable key as the+`conversation_id` field or `X-Conversation-Id` header on+`POST /v1/chat/completions`; requests without a key keep the normal active-adapter+behavior. The router hashes the key, so every request in one conversation stays in+the same stable or canary bucket. An explicit `adapter` field still takes precedence.++Completed generations and generation errors are accumulated separately for the two+buckets in `.soup/canary-stats.json`. `soup loop watch` evaluates those observations+after at least 30 canary samples. If the canary success rate trails the stable rate by+more than five percentage points, the verdict is `MAJOR`; with+`--autoroll-on-regress`, the watcher atomically clears the canary and its traffic share+from `loop.yaml`. `/v1/adapters/activate/<name>` remains an explicit 100% cutover for+requests without a conversation key and does not change the canary policy. Keyed+requests still follow the canary split; their stable bucket uses the served base+model, even when another adapter was activated manually. Start `soup serve` from the+directory containing `.soup/`, because the loop state and canary statistics paths are+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.## Knowledge Editing (`soup edit set`, ROME / MEMIT / AlphaEdit)diff --git a/docs/commands.md b/docs/commands.mdindex 3d1b698f..89c251f6 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -174,7 +174,7 @@ soup loop status Counters + status + pre_wired flagsoup loop watch [--detach] [--max-iter N] [--pre-wired] [--pack-cans] Harvest → train → gate → deploy daemon (pre-wired stages + Soup Can packing)soup loop pause Atomic status flip: pause watch daemon at next iteration boundarysoup loop resume Atomic status flip: resume a paused loop-soup loop canary <adapter> --traffic 5% Promote canary + auto-rollback on MAJOR+soup loop canary <adapter> --traffic 5% Route keyed serve traffic to a loaded adapter; watch auto-rolls back on MAJORsoup loop replay [<iter-id>] [--extract <dir>] Replay / unpack a recorded iteration manifestsoup serve --model m --adapters chat=./c code=./d Multi-adapter servingsoup migrate --from llamafactory config.yaml Import config from LLaMA-Factorydiff --git a/src/soup_cli/commands/loop.py b/src/soup_cli/commands/loop.pyindex ff605f71..9f11612f 100644--- a/src/soup_cli/commands/loop.py+++ b/src/soup_cli/commands/loop.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport osimport subprocessimport sys+import uuidfrom dataclasses import replacefrom typing import Optional@@ -295,7 +296,6 @@ def canary_cmd(stable=state.served_model,canary=new_adapter,traffic_pct=pct,- sticky_on_rollback=autoroll_on_regress,)except (TypeError, ValueError) as exc:console.print(f"[red]invalid canary policy:[/] {escape(str(exc))}")@@ -307,6 +307,7 @@ def canary_cmd(canary_active=policy.canary,canary_traffic_pct=policy.traffic_pct,canary_autoroll_on_regress=autoroll_on_regress,+ canary_rollout_id=uuid.uuid4().hex,)write_state(new_state)# Reload so the in-memory value reflects the persisted updated_at.diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.pyindex 3029cdea..bfecd647 100644--- a/src/soup_cli/commands/serve.py+++ b/src/soup_cli/commands/serve.py@@ -1460,7 +1460,9 @@ def _adapter_scope(model, lock, names, requested, active):if not names or lock is None:yieldreturn- name = requested or active+ # An explicit empty string is the internal sentinel for the unadapted base.+ # Test identity rather than truthiness so it overrides a manual full cutover.+ name = active if requested is None else requestedwith lock:if name and name in names and hasattr(model, "set_adapter"):model.set_adapter(name)@@ -1663,6 +1665,8 @@ def _create_app(loaded_bank: Any = None,mole_runtime: Any = None,kv_cache_generate_kwargs: Optional[Dict[str, Any]] = None,+ canary_state_path: Optional[str] = None,+ canary_stats_path: Optional[str] = None,):"""Create the FastAPI application with OpenAI-compatible endpoints.@@ -1780,6 +1784,12 @@ def _create_app(default=None,description="Adapter name to use (from --adapters flag).",)+ conversation_id: Optional[str] = Field(+ default=None,+ min_length=1,+ max_length=512,+ description="Stable key used by the soup loop canary router.",+ )# Resolved adapter map (name → path)_adapter_map = adapter_map or {}@@ -1801,6 +1811,55 @@ def _create_app(with active_lock:return active_state["active"]+ 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:+ return None, None+ policy = CanaryPolicy(+ stable=state.served_model,+ canary=state.canary_active,+ traffic_pct=float(state.canary_traffic_pct),+ )+ decision = route(policy, conversation_id)+ except (FileNotFoundError, OSError, TypeError, ValueError):+ logger.debug("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)+ return None, None+ return decision.adapter, (policy, decision.bucket, state.canary_rollout_id)+ if decision.adapter in _peft_adapter_names:+ return decision.adapter, (policy, decision.bucket, state.canary_rollout_id)+ # The stable model normally is the unadapted base. An empty explicit+ # selection makes _adapter_scope disable adapters even if a manual+ # full-cutover adapter is active.+ return "", (policy, decision.bucket, state.canary_rollout_id)++ 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(+ policy,+ bucket,+ ok,+ rollout_id=rollout_id,+ path=canary_stats_path,+ )+ except (OSError, TypeError, ValueError):+ logger.warning("canary outcome write failed", exc_info=True)+@app.get("/health")def health():return {@@ -1875,9 +1934,15 @@ def _create_app(def chat_completions(request: ChatCompletionRequest,x_user_id: Optional[str] = Header(default=None, alias="X-User-Id"),+ x_conversation_id: Optional[str] = Header(+ default=None, alias="X-Conversation-Id"+ ),):# Check adapter selection (from request body)- requested_adapter = request.adapter+ # Treat an empty public request value like an omitted adapter. The+ # empty string is reserved internally as the explicit base-model+ # sentinel used by keyed stable canary traffic.+ requested_adapter = request.adapter or Noneif requested_adapter and _adapter_map:if requested_adapter not in _adapter_map:raise HTTPException(@@ -1889,6 +1954,13 @@ def _create_app(status_code=404,detail="No adapters loaded.",)+ canary_tracking = None+ if requested_adapter is None:+ routed_adapter, canary_tracking = _canary_adapter(+ request.conversation_id or x_conversation_id+ )+ if canary_tracking is not None:+ requested_adapter = routed_adapter# v0.71.12 #221 — select the active VeRA / VB-LoRA user for this# request. set_active_user(None) (or an unknown id) self-clears, so@@ -1922,6 +1994,9 @@ def _create_app(adapter_names=_peft_adapter_names,requested_adapter=requested_adapter,active_adapter=_active_snapshot(),+ canary_outcome=(+ lambda ok: _record_canary_outcome(canary_tracking, ok)+ ),),media_type="text/event-stream",)@@ -1984,6 +2059,7 @@ def _create_app(kv_cache_generate_kwargs=kv_cache_generate_kwargs,)except Exception:+ _record_canary_outcome(canary_tracking, False)logger.exception("Generation error")raise HTTPException(status_code=500, detail="Internal server error")@@ -2018,7 +2094,7 @@ def _create_app(tokens=completion_tokens,)- return {+ result = {"id": f"chatcmpl-{uuid.uuid4().hex[:8]}","object": "chat.completion","created": int(time.time()),@@ -2039,6 +2115,8 @@ def _create_app("total_tokens": prompt_tokens + completion_tokens,},}+ _record_canary_outcome(canary_tracking, True)+ return resultfinally:# Always record latency so tail-latency percentiles include# error paths (prevents blind spots on the dashboard).@@ -2425,6 +2503,7 @@ def _stream_response(loaded_bank=None, x_user_id=None,adapter_lock=None, adapter_names=None,requested_adapter=None, active_adapter=None,+ canary_outcome=None,):"""Generator that yields SSE chunks for streaming responses."""chat_id = f"chatcmpl-{uuid.uuid4().hex[:8]}"@@ -2469,10 +2548,15 @@ def _stream_response(kv_cache_generate_kwargs=kv_cache_generate_kwargs,)except Exception:+ if canary_outcome is not None:+ canary_outcome(False)logger.exception("Stream generation error")yield 'data: {"error": "Internal server error"}\n\n'return+ if canary_outcome is not None:+ canary_outcome(True)+# Simulate streaming by sending word-by-wordwords = response_text.split(" ")for idx, word in enumerate(words):diff --git a/src/soup_cli/utils/canary_router.py b/src/soup_cli/utils/canary_router.pyindex bec90949..1825ae82 100644--- a/src/soup_cli/utils/canary_router.py+++ b/src/soup_cli/utils/canary_router.py@@ -15,12 +15,16 @@ plugs into `route()` directly.from __future__ import annotationsimport hashlib+import jsonimport math+import osimport threadingfrom dataclasses import dataclass, fieldfrom types import MappingProxyTypefrom typing import Mapping, Optional+from soup_cli.utils.paths import atomic_write_text, enforce_under_cwd_and_no_symlink+@dataclass(frozen=True)class CanaryPolicy:@@ -64,6 +68,9 @@ class RouteDecision:_HASH_MOD = 10_000 # buckets — gives ±0.01 % granularity on the split+_DEFAULT_STATS_PATH = os.path.join(".soup", "canary-stats.json")+_MAX_STATS_BYTES = 64 * 1024+_STATS_LOCK = threading.Lock()def _bucket_for_key(key: str) -> int:@@ -193,3 +200,89 @@ class BucketStats:"canary_major": self.canary_major,})+++def default_stats_path() -> str:+ """Return the canary outcome path next to the default loop state."""+ return _DEFAULT_STATS_PATH+++def read_bucket_stats(+ *,+ stable: str,+ canary: str,+ rollout_id: Optional[str] = None,+ path: Optional[str] = None,+) -> BucketStats:+ """Load counters for one rollout, returning empty stats for another rollout.++ The adapter identities prevent samples from an older promotion being reused+ after an operator selects a different canary.+ """+ policy = CanaryPolicy(stable=stable, canary=canary, traffic_pct=0.0)+ target = path or default_stats_path()+ enforce_under_cwd_and_no_symlink(target, "canary stats path")+ try:+ if os.path.getsize(target) > _MAX_STATS_BYTES:+ raise ValueError("canary stats file exceeds 64 KiB cap")+ with open(target, "r", encoding="utf-8") as fh:+ payload = json.load(fh)+ except FileNotFoundError:+ return BucketStats()+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ValueError("canary stats file is unreadable") from exc+ if not isinstance(payload, dict):+ raise ValueError("canary stats root must be an object")+ if (+ payload.get("stable") != policy.stable+ or payload.get("canary") != policy.canary+ or payload.get("rollout_id") != rollout_id+ ):+ return BucketStats()+ values = {}+ for name in ("stable_ok", "stable_major", "canary_ok", "canary_major"):+ value = payload.get(name, 0)+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise ValueError(f"{name} must be a non-negative int")+ values[name] = value+ return BucketStats(**values)+++def record_bucket_outcome(+ policy: CanaryPolicy,+ bucket: str,+ ok: bool,+ *,+ rollout_id: Optional[str] = None,+ path: Optional[str] = None,+) -> None:+ """Atomically add one served request outcome to the active rollout."""+ 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")+ target = path or default_stats_path()+ with _STATS_LOCK:+ stats = read_bucket_stats(+ stable=policy.stable,+ canary=policy.canary,+ rollout_id=rollout_id,+ path=target,+ )+ stats.record(bucket, ok)+ payload = {+ "stable": policy.stable,+ "canary": policy.canary,+ "rollout_id": rollout_id,+ **dict(stats.snapshot()),+ }+ atomic_write_text(+ json.dumps(payload, allow_nan=False, indent=2, sort_keys=True),+ target,+ prefix=".canary_stats_",+ field="canary stats path",+ )diff --git a/src/soup_cli/utils/loop_daemon.py b/src/soup_cli/utils/loop_daemon.pyindex f0dc2e49..9f3b03e6 100644--- a/src/soup_cli/utils/loop_daemon.py+++ b/src/soup_cli/utils/loop_daemon.py@@ -27,7 +27,12 @@ from dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom typing import Callable, Mapping, Optional-from soup_cli.utils.canary_router import BucketStats, CanaryPolicy, rollback+from soup_cli.utils.canary_router import (+ BucketStats,+ CanaryPolicy,+ read_bucket_stats,+ rollback,+)from soup_cli.utils.loop_budget import (BudgetDecision,check_budget,@@ -98,6 +103,7 @@ class WatchConfig:poll_interval_sec: float = 60.0max_iterations: Optional[int] = None # None = unbounded (real daemon)state_path: Optional[str] = None+ canary_stats_path: Optional[str] = Noneiteration_dir: Optional[str] = Noneharvest_fn: HarvestFn = default_harvesttrain_fn: TrainFn = default_train@@ -157,6 +163,15 @@ def run_once(state.runs_today, state.last_run_date)state = _state_with(state, runs_today=runs_today, last_run_date=today)+ canary_verdict, rollback_policy = _evaluate_active_canary(state, config)+ rolled_back = rollback_policy is not None+ if rollback_policy is not None:+ state = _state_with(+ state,+ canary_active=rollback_policy.canary,+ canary_traffic_pct=rollback_policy.traffic_pct,+ canary_rollout_id=None,+ )estimated = float(config.cost_fn(state))decision = check_budget(estimated_run_usd=estimated,@@ -175,9 +190,9 @@ def run_once(pairs_harvested=0,run_id=None,gate_verdict="SKIPPED",- canary_verdict=None,+ canary_verdict=canary_verdict,shipped=False,- rolled_back=False,+ rolled_back=rolled_back,estimated_cost_usd=estimated,notes=f"budget-skip: {decision.reason}",)@@ -187,11 +202,11 @@ def run_once(gate_out = dict(config.gate_fn(state, train_out))deploy_out = dict(config.deploy_fn(state, {**train_out, **gate_out}))gate_verdict = str(gate_out.get("gate_verdict", "SKIPPED"))- canary_verdict = deploy_out.get("canary_verdict")- if canary_verdict is not None:- canary_verdict = str(canary_verdict)+ deploy_verdict = deploy_out.get("canary_verdict")+ if canary_verdict is None and deploy_verdict is not None:+ canary_verdict = str(deploy_verdict)shipped = bool(deploy_out.get("deployed", False))- rolled_back = bool(deploy_out.get("rolled_back", False))+ rolled_back = rolled_back or bool(deploy_out.get("rolled_back", False))pairs = int(harvest_out.get("pairs_harvested", 0) or 0)if pairs < 0:pairs = 0@@ -229,6 +244,34 @@ def run_once(return new_state, record, decision+def _evaluate_active_canary(+ state: LoopState, config: WatchConfig+) -> "tuple[Optional[str], Optional[CanaryPolicy]]":+ """Read live bucket outcomes and return a sticky rollback policy if needed."""+ active_canary = state.canary_active+ if active_canary is None:+ return None, None+ try:+ policy = CanaryPolicy(+ stable=state.served_model,+ canary=active_canary,+ traffic_pct=float(state.canary_traffic_pct or 0.0),+ )+ stats = read_bucket_stats(+ stable=policy.stable,+ canary=active_canary,+ rollout_id=state.canary_rollout_id,+ path=config.canary_stats_path,+ )+ verdict = evaluate_canary_verdict(stats)+ except (OSError, TypeError, ValueError):+ _LOG.warning("canary stats read failed", exc_info=True)+ return None, None+ if verdict == "MAJOR" and state.canary_autoroll_on_regress:+ return verdict, maybe_rollback(policy, verdict)+ return verdict, None++def watch(config: WatchConfig) -> "tuple[LoopState, int]":"""Run the daemon loop. Returns ``(final_state, iterations_run)``.diff --git a/src/soup_cli/utils/loop_state.py b/src/soup_cli/utils/loop_state.pyindex 7064024c..ab4e6f56 100644--- a/src/soup_cli/utils/loop_state.py+++ b/src/soup_cli/utils/loop_state.py@@ -61,6 +61,7 @@ class LoopState:canary_active: Optional[str] = Nonecanary_traffic_pct: Optional[float] = Nonecanary_autoroll_on_regress: bool = True+ canary_rollout_id: Optional[str] = Nonemonthly_budget_usd: Optional[float] = Nonespent_this_month_usd: float = 0.0max_runs_per_day: Optional[int] = None@@ -117,6 +118,8 @@ class LoopState:raise ValueError("pre_wired must be bool")if self.canary_active is not None:_require_str("canary_active", self.canary_active, allow_empty=False)+ if self.canary_rollout_id is not None:+ _require_str("canary_rollout_id", self.canary_rollout_id, allow_empty=False)if self.last_iteration_id is not None:_require_str("last_iteration_id", self.last_iteration_id, allow_empty=False)if self.last_run_date is not None:diff --git a/tests/test_issue815_canary_runtime.py b/tests/test_issue815_canary_runtime.pynew file mode 100644index 00000000..211cf64c--- /dev/null+++ b/tests/test_issue815_canary_runtime.py@@ -0,0 +1,465 @@+"""Regression tests for the live canary path from issue #815."""++from contextlib import contextmanager++import pytest+from fastapi.testclient import TestClient++from soup_cli.utils.canary_router import (+ CanaryPolicy,+ read_bucket_stats,+ record_bucket_outcome,+)+from soup_cli.utils.loop_daemon import WatchConfig, watch+from soup_cli.utils.loop_state import LoopState, read_state, write_state+++class _AdapterModel:+ def __init__(self) -> None:+ self.current = None++ def set_adapter(self, name: str) -> None:+ self.current = name++ @contextmanager+ def disable_adapter(self):+ previous = self.current+ self.current = None+ try:+ yield+ finally:+ self.current = previous+++def test_five_percent_policy_routes_live_serve_requests(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ state_path = tmp_path / ".soup" / "loop.yaml"+ stats_path = tmp_path / ".soup" / "canary-stats.json"+ write_state(+ LoopState(+ served_model="base",+ eval_suite="evals.yaml",+ baseline="prod",+ canary_active="candidate",+ canary_traffic_pct=5.0,+ canary_rollout_id="rollout-1",+ ),+ str(state_path),+ )++ import soup_cli.commands.serve as serve++ model = _AdapterModel()+ observed = []++ def generate(current_model, *args, **kwargs):+ observed.append(current_model.current)+ return "ok", 1, 1++ monkeypatch.setattr(serve, "_generate_response", generate)+ app = serve._create_app(+ model_obj=model,+ tokenizer=object(),+ device="cpu",+ model_name="base",+ max_tokens_default=8,+ adapter_map={"candidate": "unused"},+ peft_adapter_names={"candidate"},+ canary_state_path=str(state_path),+ canary_stats_path=str(stats_path),+ )+ client = TestClient(app)++ request_count = 400+ for index in range(request_count):+ response = client.post(+ "/v1/chat/completions",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "conversation_id": f"conversation-{index}",+ },+ )+ assert response.status_code == 200++ canary_count = observed.count("candidate")+ assert 10 <= canary_count <= 30+ assert observed.count(None) == request_count - canary_count+++def test_failing_live_canary_requests_reach_the_rollout_stats(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ state_path = tmp_path / ".soup" / "loop.yaml"+ stats_path = tmp_path / ".soup" / "canary-stats.json"+ write_state(+ LoopState(+ served_model="base",+ eval_suite="evals.yaml",+ baseline="prod",+ canary_active="candidate",+ canary_traffic_pct=50.0,+ canary_rollout_id="rollout-bridge",+ ),+ str(state_path),+ )++ import soup_cli.commands.serve as serve++ model = _AdapterModel()+ observed = []++ def generate(current_model, *args, **kwargs):+ observed.append(current_model.current)+ if current_model.current == "candidate":+ raise RuntimeError("bad canary")+ return "ok", 1, 1++ monkeypatch.setattr(serve, "_generate_response", generate)+ app = serve._create_app(+ model_obj=model,+ tokenizer=object(),+ device="cpu",+ model_name="base",+ max_tokens_default=8,+ adapter_map={"candidate": "unused"},+ peft_adapter_names={"candidate"},+ canary_state_path=str(state_path),+ canary_stats_path=str(stats_path),+ )+ client = TestClient(app)++ statuses = []+ for index in range(200):+ response = client.post(+ "/v1/chat/completions",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "conversation_id": f"bridge-{index}",+ },+ )+ statuses.append(response.status_code)++ canary_count = observed.count("candidate")+ stable_count = observed.count(None)+ stats = read_bucket_stats(+ stable="base",+ canary="candidate",+ rollout_id="rollout-bridge",+ path=str(stats_path),+ )+ assert statuses.count(500) == canary_count+ assert statuses.count(200) == stable_count+ assert stats.canary_major == canary_count+ assert stats.canary_ok == 0+ assert stats.stable_ok == stable_count+ assert stats.stable_major == 0+++def test_watch_persists_rollback_for_major_live_stats(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ state_path = tmp_path / ".soup" / "loop.yaml"+ stats_path = tmp_path / ".soup" / "canary-stats.json"+ write_state(+ LoopState(+ served_model="base",+ eval_suite="evals.yaml",+ baseline="prod",+ status="running",+ canary_active="candidate",+ canary_traffic_pct=5.0,+ canary_autoroll_on_regress=True,+ canary_rollout_id="rollout-1",+ ),+ str(state_path),+ )+ persisted = read_state(str(state_path))+ policy = CanaryPolicy(stable="base", canary="candidate", traffic_pct=5.0)+ for _ in range(30):+ record_bucket_outcome(+ policy,+ "stable",+ True,+ rollout_id=persisted.canary_rollout_id,+ path=str(stats_path),+ )+ record_bucket_outcome(+ policy,+ "canary",+ False,+ rollout_id=persisted.canary_rollout_id,+ path=str(stats_path),+ )++ final_state, iterations = watch(+ WatchConfig(+ poll_interval_sec=1.0,+ max_iterations=1,+ state_path=str(state_path),+ canary_stats_path=str(stats_path),+ iteration_dir=str(tmp_path / ".soup-loops"),+ )+ )++ persisted = read_state(str(state_path))+ assert iterations == 1+ assert final_state.canary_active is None+ assert persisted.canary_active is None+ assert persisted.canary_traffic_pct == 0.0++[email protected]("sample_count", [5, 30])+def test_watch_keeps_a_non_regressing_canary_active(tmp_path, monkeypatch, sample_count):+ monkeypatch.chdir(tmp_path)+ state_path = tmp_path / ".soup" / "loop.yaml"+ stats_path = tmp_path / ".soup" / "canary-stats.json"+ write_state(+ LoopState(+ served_model="base",+ eval_suite="evals.yaml",+ baseline="prod",+ status="running",+ canary_active="candidate",+ canary_traffic_pct=5.0,+ canary_autoroll_on_regress=True,+ canary_rollout_id="rollout-healthy",+ ),+ str(state_path),+ )+ policy = CanaryPolicy(stable="base", canary="candidate", traffic_pct=5.0)+ for _ in range(sample_count):+ record_bucket_outcome(+ policy,+ "stable",+ True,+ rollout_id="rollout-healthy",+ path=str(stats_path),+ )+ record_bucket_outcome(+ policy,+ "canary",+ True,+ rollout_id="rollout-healthy",+ path=str(stats_path),+ )++ final_state, iterations = watch(+ WatchConfig(+ poll_interval_sec=1.0,+ max_iterations=1,+ state_path=str(state_path),+ canary_stats_path=str(stats_path),+ iteration_dir=str(tmp_path / ".soup-loops"),+ )+ )++ persisted = read_state(str(state_path))+ assert iterations == 1+ assert final_state.canary_active == "candidate"+ assert final_state.canary_traffic_pct == 5.0+ assert persisted.canary_active == "candidate"+ assert persisted.canary_traffic_pct == 5.0+ assert persisted.canary_rollout_id == "rollout-healthy"+++def _write_canary_state(tmp_path, *, traffic_pct, rollout_id):+ state_path = tmp_path / ".soup" / "loop.yaml"+ write_state(+ LoopState(+ served_model="base",+ eval_suite="evals.yaml",+ baseline="prod",+ status="running",+ canary_active="candidate",+ canary_traffic_pct=traffic_pct,+ canary_autoroll_on_regress=True,+ canary_rollout_id=rollout_id,+ ),+ str(state_path),+ )+ return state_path, tmp_path / ".soup" / "canary-stats.json"+++def _record(stats_path, rollout_id, *, stable_ok, canary_ok, count):+ policy = CanaryPolicy(stable="base", canary="candidate", traffic_pct=5.0)+ for _ in range(count):+ record_bucket_outcome(+ policy, "stable", stable_ok, rollout_id=rollout_id, path=str(stats_path)+ )+ record_bucket_outcome(+ policy, "canary", canary_ok, rollout_id=rollout_id, path=str(stats_path)+ )+++def _watch_once(tmp_path, state_path, stats_path):+ return watch(+ WatchConfig(+ poll_interval_sec=1.0,+ max_iterations=1,+ state_path=str(state_path),+ canary_stats_path=str(stats_path),+ iteration_dir=str(tmp_path / ".soup-loops"),+ )+ )+++def _serve_with_canary(monkeypatch, state_path, stats_path, adapters, fail_on=None):+ import soup_cli.commands.serve as serve++ observed = []++ def generate(current_model, *args, **kwargs):+ observed.append(current_model.current)+ if fail_on is not None and current_model.current == fail_on:+ raise RuntimeError("bad canary")+ return "ok", 1, 1++ monkeypatch.setattr(serve, "_generate_response", generate)+ app = serve._create_app(+ model_obj=_AdapterModel(),+ tokenizer=object(),+ device="cpu",+ model_name="base",+ max_tokens_default=8,+ adapter_map={name: "unused" for name in adapters},+ peft_adapter_names=set(adapters),+ canary_state_path=str(state_path),+ canary_stats_path=str(stats_path),+ )+ return TestClient(app, base_url="http://127.0.0.1"), observed+++def test_samples_from_an_earlier_rollout_never_count(tmp_path, monkeypatch):+ """Re-promoting the same adapter names must start from zero evidence."""+ monkeypatch.chdir(tmp_path)+ state_path, stats_path = _write_canary_state(+ tmp_path, traffic_pct=5.0, rollout_id="rollout-new"+ )+ _record(stats_path, "rollout-old", stable_ok=True, canary_ok=False, count=30)++ final_state, _ = _watch_once(tmp_path, state_path, stats_path)++ assert final_state.canary_active == "candidate"+ assert read_state(str(state_path)).canary_active == "candidate"+++def test_an_undersampled_failing_canary_is_not_rolled_back(tmp_path, monkeypatch):+ """Five failed canary samples are UNKNOWN (fewer than 30), not MAJOR."""+ monkeypatch.chdir(tmp_path)+ state_path, stats_path = _write_canary_state(+ tmp_path, traffic_pct=5.0, rollout_id="rollout-few"+ )+ _record(stats_path, "rollout-few", stable_ok=True, canary_ok=False, count=5)++ final_state, _ = _watch_once(tmp_path, state_path, stats_path)++ persisted = read_state(str(state_path))+ assert final_state.canary_active == "candidate"+ assert persisted.canary_active == "candidate"+ assert persisted.canary_rollout_id == "rollout-few"+++def test_each_canary_promotion_gets_a_fresh_rollout_id(tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ runner = CliRunner()+ init = runner.invoke(app, ["loop", "init", "base", "--eval", "e", "--baseline", "b"])+ assert init.exit_code == 0, (init.output, repr(init.exception))+ rollout_ids = []+ for _ in range(2):+ result = runner.invoke(app, ["loop", "canary", "candidate", "--traffic", "5%"])+ assert result.exit_code == 0, (result.output, repr(result.exception))+ rollout_ids.append(read_state().canary_rollout_id)+ assert all(rollout_ids)+ assert rollout_ids[0] != rollout_ids[1]+++def test_keyed_stable_traffic_is_the_base_even_after_a_manual_cutover(+ tmp_path, monkeypatch+):+ """The stable bucket is what the stats call stable, not an activated adapter."""+ monkeypatch.chdir(tmp_path)+ state_path, stats_path = _write_canary_state(+ tmp_path, traffic_pct=50.0, rollout_id="rollout-cutover"+ )+ client, observed = _serve_with_canary(+ monkeypatch, state_path, stats_path, adapters=("candidate", "other")+ )+ assert client.post("/v1/adapters/activate/other").status_code == 200++ for index in range(100):+ response = client.post(+ "/v1/chat/completions",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "conversation_id": f"cutover-{index}",+ },+ )+ assert response.status_code == 200++ assert "other" not in observed+ assert 0 < observed.count("candidate") < 100+ stats = read_bucket_stats(+ stable="base", canary="candidate", rollout_id="rollout-cutover", path=str(stats_path)+ )+ assert stats.stable_ok == observed.count(None)+++def test_failing_live_canary_stream_requests_reach_the_rollout_stats(+ tmp_path, monkeypatch+):+ """A streamed generation error still answers 200; the stats file is its only record."""+ monkeypatch.chdir(tmp_path)+ state_path, stats_path = _write_canary_state(+ tmp_path, traffic_pct=50.0, rollout_id="rollout-stream"+ )+ client, observed = _serve_with_canary(+ monkeypatch, state_path, stats_path, adapters=("candidate",), fail_on="candidate"+ )++ for index in range(100):+ response = client.post(+ "/v1/chat/completions",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "conversation_id": f"stream-{index}",+ "stream": True,+ },+ )+ assert response.status_code == 200++ canary_count = observed.count("candidate")+ stats = read_bucket_stats(+ stable="base", canary="candidate", rollout_id="rollout-stream", path=str(stats_path)+ )+ assert canary_count > 0+ assert stats.canary_major == canary_count+ assert stats.canary_ok == 0+ assert stats.stable_ok == observed.count(None)+ assert stats.stable_major == 0+++def test_an_empty_public_adapter_field_keeps_the_manual_activation(tmp_path, monkeypatch):+ """An empty public adapter field must preserve the manual activation."""+ monkeypatch.chdir(tmp_path)+ client, observed = _serve_with_canary(+ monkeypatch,+ tmp_path / ".soup" / "loop.yaml",+ tmp_path / ".soup" / "canary-stats.json",+ adapters=("chat",),+ )+ assert client.post("/v1/adapters/activate/chat").status_code == 200++ for stream in (False, True):+ response = client.post(+ "/v1/chat/completions",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "adapter": "",+ "stream": stream,+ },+ )+ assert response.status_code == 200++ assert observed == ["chat", "chat"]diff --git a/tests/test_review_fixes_v07133.py b/tests/test_review_fixes_v07133.pyindex e22e4491..535388df 100644--- a/tests/test_review_fixes_v07133.py+++ b/tests/test_review_fixes_v07133.py@@ -177,6 +177,11 @@ class TestAdapterScope:model = self._run(None, None, {"chat"})assert model.disable_calls == 1+ def test_empty_selection_overrides_active_with_base(self):+ model = self._run("", "chat", {"chat"})+ assert model.set_calls == []+ assert model.disable_calls == 1+def test_no_adapters_is_noop(self):model = self._run("chat", "chat", set())assert model.set_calls == []