diff --git a/AGENTS.md b/AGENTS.md index 7d8ab71..3056a18 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -301,7 +301,7 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget `smart_limit`/`warn_limit`). - Test: fake server emits a usage chunk; assert it's captured and logged. -- [ ] **4. SemIf degeneration watchdog** (`codegen.py`, `cli.py`, `scheduler.py`) +- [x] **4. SemIf degeneration watchdog** (`codegen.py`, `cli.py`, `scheduler.py`) - Add optional `degeneration_check: Callable[[str], str|None]` to `CodegenClient.chat`/`generate_skill_body`; `_read_stream` calls it every `interval` chars with the last `window` chars (content+reasoning); @@ -314,6 +314,25 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget `CodegenClient` standalone pure for unit tests). - Tests: a callback returning a reason aborts the stream; not invoked when disabled. + - Implemented on the dev machine (2026-09-24): `CodegenClient` gained + `degeneration_interval`/`degeneration_window`/`degeneration_min_chars` + constructor params and a per-`chat` `degeneration_check`; both stream + readers (`_read_stream` and the blocking fallback) poll it against a + bounded rolling buffer (content+reasoning), trimming to + `window + interval` chars so a long degenerating stream never grows + unbounded memory. `cli.build_scheduler` wires a `degeneration_check_factory` + (per-run SemIf continue/stop decision; `EngineUnavailable` at call time + degrades to "keep going", so a machine without the engine never aborts via + this path) into the `Scheduler`, which builds the per-request check with + `request.id` and passes it through `generate_skill_body`. Trace event: + `kind: "codegen"` carrying state/question/options/probs/stop_prob — not in + the decision log. Config block added to `config.example.json` (`enabled` + defaults true; the runtime engine check is what disables it off the box). + Unit-tested: callback reason aborts the stream (deviation from the "not + invoked when disabled" spec: the min_chars gate is covered too), callback + returning None continues, no callback completes normally. **Box + verification pending**: run the codegen integration tests and watch the + `codegen` trace events + an abort fire on a real degenerating stream. - [ ] **5. Sampler params + 3-attempt escalation ladder** (`codegen.py`, `cli.py`) - Send `temperature`/`top_p`/`presence_penalty`/`frequency_penalty` diff --git a/config.example.json b/config.example.json index a21e7e5..1ad6a18 100644 --- a/config.example.json +++ b/config.example.json @@ -26,7 +26,15 @@ "max_fill_ratio": 0.9, "warn_fill_ratio": 0.7, "max_output": 0.85, - "chars_per_token": 4.0 + "chars_per_token": 4.0, + "degeneration": { + "_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.", + "enabled": true, + "threshold": 0.9, + "interval": 8000, + "window": 2000, + "min_chars": 4000 + } }, "skill_bodies": "data/skills", "skills": { diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 3e41699..4148b2f 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -19,6 +19,7 @@ from pathlib import Path from .dream import dream as run_dream from .codegen import CodegenClient +from .decisions import DecisionRequest, Option from .engine import EngineConfig, EngineUnavailable, SemIfEngine from .llm import LLMClient from .log import DecisionLog @@ -46,7 +47,10 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: base_url=config.get("llm", {}).get("base_url", "http://localhost:11434/v1"), model=config.get("llm", {}).get("model", "qwen2.5:3b"), ) + log = DecisionLog(config.get("log", "data/decisions.jsonl")) + trace = TraceLog(config.get("trace", "data/runs.jsonl")) codegen_cfg = config.get("codegen", {}) + deg_cfg = codegen_cfg.get("degeneration", {}) or {} codegen = CodegenClient( base_url=codegen_cfg.get( "base_url", config.get("llm", {}).get("base_url", "http://localhost:11434/v1") @@ -63,9 +67,52 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: warn_fill_ratio=float(codegen_cfg.get("warn_fill_ratio", 0.7)), max_output=float(codegen_cfg.get("max_output", 0.85)), chars_per_token=float(codegen_cfg.get("chars_per_token", 4.0)), + degeneration_interval=int(deg_cfg.get("interval", 8000)), + degeneration_window=int(deg_cfg.get("window", 2000)), + degeneration_min_chars=int(deg_cfg.get("min_chars", 4000)), ) - log = DecisionLog(config.get("log", "data/decisions.jsonl")) - trace = TraceLog(config.get("trace", "data/runs.jsonl")) + + def make_degeneration_check(run_id: str): + """2-option SemIf decision (continue/stop) that aborts a degenerating + codegen stream: P(stop) >= threshold returns an abort reason. Recorded + as a trace-only event (kind `codegen`, with probs) — never in the + decision log. Disabled when no engine (EngineUnavailable at call time + degrades to "keep going"), which keeps CodegenClient standalone pure.""" + if not bool(deg_cfg.get("enabled", True)): + return None + threshold = float(deg_cfg.get("threshold", 0.9)) + + def check(recent: str) -> str | None: + decision = DecisionRequest( + state=f"[codegen {codegen.model}] {recent[-2000:]}", + question="Is this skill-body generation degenerating (looping or repeating instead of converging)?", + options=[ + Option("continue", "Continue; it is still making progress."), + Option("stop", "Stop; it is degenerating."), + ], + ) + try: + result = engine.call(decision) + except EngineUnavailable: + return None + trace.append( + "codegen", + run_id, + state=decision.state, + question=decision.question, + options=[o.id for o in decision.options], + selected=result.selected, + probs=result.probs, + stop_prob=result.prob("stop"), + ) + if result.prob("stop") >= threshold: + return ( + f"P(stop)={result.prob('stop'):.2f} >= threshold {threshold}" + ) + return None + + return check + scheduler = Scheduler( engine=engine, llm=llm, @@ -75,6 +122,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: max_reentries=int(config.get("max_reentries", 3)), trace=trace, codegen=codegen, + degeneration_check_factory=make_degeneration_check, ) return scheduler, config diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index becae85..72feb22 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -18,7 +18,7 @@ import time import urllib.error import urllib.request from pathlib import Path -from typing import NamedTuple +from typing import Callable, NamedTuple from .decisions import Request from .skills import SkillDraft, tree_summary @@ -75,6 +75,13 @@ class CodegenClient: then the `context_window` config, then 100000); the per-request budget caps output at `max_output` (absolute tokens if >= 1, else a fraction of the window) and total fill at `smart_limit`/`warn_limit`. + + An optional `degeneration_check` callback (passed per `chat` call) is fed + the last `degeneration_window` chars of content+reasoning every + `degeneration_interval` chars once `degeneration_min_chars` have + accumulated; a non-None return aborts the stream. It lets a SemIf + continue/stop decision cut off a generation that is looping instead of + converging, before it fills the context window. """ def __init__( @@ -92,6 +99,9 @@ class CodegenClient: warn_fill_ratio: float = 0.7, max_output: float = 0.85, chars_per_token: float = 4.0, + degeneration_interval: int = 8000, + degeneration_window: int = 2000, + degeneration_min_chars: int = 4000, ): self.base_url = base_url.rstrip("/") self.model = model @@ -106,6 +116,9 @@ class CodegenClient: self.warn_fill_ratio = warn_fill_ratio self.max_output = max_output self.chars_per_token = chars_per_token + self.degeneration_interval = degeneration_interval + self.degeneration_window = degeneration_window + self.degeneration_min_chars = degeneration_min_chars self._window: int | None = None def chat( @@ -113,6 +126,7 @@ class CodegenClient: messages: list[dict], max_tokens: int | None = None, temperature: float = 0.0, + degeneration_check: Callable[[str], str | None] | None = None, ) -> str: budget = self._compute_budget(messages) if self.stream: @@ -132,7 +146,7 @@ class CodegenClient: ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: - return self._read_stream(response, budget) + return self._read_stream(response, budget, degeneration_check) except urllib.error.URLError as exc: raise CodegenError( f"codegen endpoint unreachable at {url}: {exc}. Is your local server running?" @@ -264,7 +278,12 @@ class CodegenClient: return True return warned - def _read_stream(self, response, budget: TokenBudget) -> str: + def _read_stream( + self, + response, + budget: TokenBudget, + degeneration_check: Callable[[str], str | None] | None = None, + ) -> str: """Read an OpenAI-compatible SSE stream; echo tokens if `stream`. Only `content` deltas are accumulated into the returned body; @@ -282,16 +301,24 @@ class CodegenClient: Thresholds <= 0 disable the idle checks. If the underlying socket can't be reached, falls back to a plain blocking read (`_read_stream_blocking`, which enforces the same budgets). + + An optional `degeneration_check` (last `window` chars of content + + reasoning, every `interval` chars past `min_chars`) can abort a + generation that is looping instead of converging — a non-None return + is the abort reason. """ parts: list[str] = [] sock = self._stream_socket(response) if sock is None: - return self._read_stream_blocking(response, budget) + return self._read_stream_blocking(response, budget, degeneration_check) start = time.monotonic() last_activity = start warned = False warned_fill = False out_chars = 0 + recent: list[str] = [] + recent_len = 0 + last_check: int | None = None while True: if time.monotonic() - start >= self.timeout: raise CodegenError( @@ -330,7 +357,15 @@ class CodegenClient: if text: parts.append(text) out_chars += len(text) + len(reasoning) + if text or reasoning: + recent.append(text + reasoning) + recent_len = self._trim_recent(recent, recent_len) warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + reason, last_check = self._check_degeneration( + degeneration_check, recent, out_chars, last_check + ) + if reason: + raise CodegenError(f"codegen degeneration detected: {reason}") if not continues: break if parts and self.stream: @@ -338,7 +373,12 @@ class CodegenClient: sys.stdout.flush() return "".join(parts) - def _read_stream_blocking(self, response, budget: TokenBudget) -> str: + def _read_stream_blocking( + self, + response, + budget: TokenBudget, + degeneration_check: Callable[[str], str | None] | None = None, + ) -> str: """Fallback reader when the response socket can't be located. A plain blocking read relies on the per-read socket timeout for @@ -351,6 +391,9 @@ class CodegenClient: start = time.monotonic() warned_fill = False out_chars = 0 + recent: list[str] = [] + recent_len = 0 + last_check: int | None = None for raw in response: if time.monotonic() - start >= self.timeout: raise CodegenError( @@ -365,7 +408,15 @@ class CodegenClient: if text: parts.append(text) out_chars += len(text) + len(reasoning) + if text or reasoning: + recent.append(text + reasoning) + recent_len = self._trim_recent(recent, recent_len) warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + reason, last_check = self._check_degeneration( + degeneration_check, recent, out_chars, last_check + ) + if reason: + raise CodegenError(f"codegen degeneration detected: {reason}") if not continues: break if parts and self.stream: @@ -373,6 +424,37 @@ class CodegenClient: sys.stdout.flush() return "".join(parts) + def _trim_recent(self, recent: list[str], recent_len: int) -> int: + """Keep the rolling (content+reasoning) buffer bounded. + + Only the last `degeneration_window + degeneration_interval` chars are + ever needed: the check runs every `interval` chars against the last + `window` chars, so older text can be dropped. Returns the new length. + """ + budget = self.degeneration_window + self.degeneration_interval + while recent and recent_len > budget: + recent_len -= len(recent.pop(0)) + return recent_len + + def _check_degeneration( + self, + check: Callable[[str], str | None] | None, + recent: list[str], + out_chars: int, + last_check: int | None, + ) -> tuple[str | None, int | None]: + """Run the degeneration callback on the last `window` chars of + content+reasoning, every `interval` chars once `min_chars` have + accumulated. Returns (reason, new_last_check); a non-None reason means + the caller should abort.""" + if check is None or out_chars < self.degeneration_min_chars: + return None, last_check + if last_check is None or out_chars - last_check >= self.degeneration_interval: + window = self.degeneration_window or len(recent) + reason = check("".join(recent)[-window:]) + return reason, out_chars + return None, last_check + @staticmethod def _consume_frame(line: str) -> tuple[bool, str, str]: """Process one SSE line. @@ -490,6 +572,7 @@ def generate_skill_body( tree: dict, contract: str | None = None, max_tokens: int | None = None, + degeneration_check: Callable[[str], str | None] | None = None, ) -> str: """Author a skill body with the big model; retries once on invalid output.""" contract_text = contract if contract is not None else read_skill_contract() @@ -499,7 +582,11 @@ def generate_skill_body( last_error: Exception | None = None for attempt in range(2): try: - raw = client.chat(messages, max_tokens=max_tokens) + raw = client.chat( + messages, + max_tokens=max_tokens, + degeneration_check=degeneration_check, + ) return parse_skill_body(raw) except ValueError as exc: last_error = exc diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index f6af751..879dc4f 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -8,6 +8,7 @@ state preserved; a deferred input is scored and queued by urgency. from __future__ import annotations from dataclasses import dataclass, field +from typing import Callable from .codegen import CodegenClient, CodegenError, generate_skill_body from .decisions import DecisionRequest, Option, Request @@ -90,6 +91,8 @@ class Scheduler: max_reentries: int = 3, trace: TraceLog | None = None, codegen: CodegenClient | None = None, + degeneration_check_factory: Callable[[str], Callable[[str], str | None] | None] + | None = None, ): self.engine = engine self.llm = llm @@ -99,6 +102,7 @@ class Scheduler: self.tau = tau self.max_reentries = max_reentries self.codegen = codegen + self.degeneration_check_factory = degeneration_check_factory self.queue = UrgencyQueue( max_size=int(config.get("queue", {}).get("max_size", 100)), age_rate=float(config.get("queue", {}).get("age_rate", 0.0)), @@ -443,7 +447,16 @@ class Scheduler: try: draft.code = generate_skill_body( - self.codegen, request, category, draft, self.tree + self.codegen, + request, + category, + draft, + self.tree, + degeneration_check=( + self.degeneration_check_factory(request.id) + if self.degeneration_check_factory is not None + else None + ), ) skill = materialize_skill(draft, category, self.body_store) except (CodegenError, ValueError) as exc: diff --git a/tests/test_codegen.py b/tests/test_codegen.py index b22f6d3..b0ca28c 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -775,6 +775,122 @@ def test_context_window_is_cached(): assert client._context_window() == 4242 assert client._context_window() == 4242 assert httpd.RequestHandlerClass.show_calls == 1 + finally: + httpd.shutdown() + httpd.server_close() + + +def test_degeneration_check_aborts_stream(): + """A degeneration callback that returns a reason must abort a still- + streaming generation with CodegenError, before the token budget trips.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=0.5, + idle_timeout=30, + degeneration_interval=5, + degeneration_window=20, + degeneration_min_chars=1, + ) + calls = [] + + def check(recent): + calls.append(recent) + return "looping forever" + + started = time.monotonic() + with pytest.raises(CodegenError, match="degeneration detected"): + client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) + assert time.monotonic() - started < 8.0 + assert calls, "degeneration callback must be invoked" + assert calls[0] == "x", "callback must receive the recent window chars" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_degeneration_check_not_invoked_before_min_chars(): + """The callback must not fire before `min_chars` accumulate — the token + budget aborts first and the callback stays silent.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=0.5, + idle_timeout=30, + degeneration_interval=5, + degeneration_window=20, + degeneration_min_chars=10**9, + ) + calls = [] + + def check(recent): + calls.append(recent) + return "should never fire" + + with pytest.raises(CodegenError, match="token budget"): + client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) + assert calls == [], "callback must not run before min_chars is reached" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_degeneration_check_returning_none_continues(): + """A callback that never flags degeneration must not abort — the token + budget is still the terminator.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=0.5, + idle_timeout=30, + degeneration_interval=5, + degeneration_window=20, + degeneration_min_chars=1, + ) + calls = [] + + def check(recent): + calls.append(recent) + return None + + with pytest.raises(CodegenError, match="token budget"): + client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) + assert calls, "callback should have been polled across the stream" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_degeneration_disabled_no_callback_no_abort(): + """With no callback (disabled), a stream exceeding min_chars completes + normally — nothing in the read path assumes a check is present.""" + httpd, base = _streaming_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + degeneration_interval=1, + degeneration_window=10, + degeneration_min_chars=1, + ) + out = client.chat([{"role": "user", "content": "hi"}]) + assert out == GOOD_BODY finally: httpd.shutdown() httpd.server_close() \ No newline at end of file