Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcb0f0f988 | ||
|
|
9152c47a5d |
No files matched your search
@@ -234,6 +234,95 @@ unit tests (24) + box integration tests (2).
|
||||
stall with zero output usually means the ollama ROCm runner wedged;
|
||||
`sudo systemctl restart ollama` is the recovery.
|
||||
|
||||
## Codegen guardrails backlog (one session per item)
|
||||
|
||||
Context learned 2026-09-24 on the box: qwen38-iq3s looped ~40 min on one skill
|
||||
body (1.5 MB streamed) with no guard firing. Root causes: (1) `CodegenClient`
|
||||
sends `temperature 0.0` (greedy) and no penalties while the Modelfile has
|
||||
`repeat_penalty 1` (off) + `presence_penalty 0`; (2) the total `timeout` check
|
||||
only runs inside the `if not ready:` branch of `_read_stream`, so a
|
||||
continuously-streaming runaway never trips it. Known model facts: qwen38-iq3s
|
||||
runtime window `num_ctx=100000` (native `qwen35.context_length=262144`);
|
||||
ollama OpenAI-compat `/v1/chat/completions` supports `temperature`, `top_p`,
|
||||
`presence_penalty`, `frequency_penalty`, `max_tokens`, `reasoning_effort`, and
|
||||
`stream_options.include_usage` (returns exact token `usage`) — but NOT
|
||||
`repeat_penalty`/`min_p`/`top_k` (needs a Modelfile edit or native
|
||||
`/api/chat`). Degradation tracks ABSOLUTE tokens used (SMART<100K,
|
||||
WARN 100–200K, DUMB>200K), so limits are a total-context budget
|
||||
(prompt+output), not a fill %.
|
||||
|
||||
- [ ] **1. Fix the total-timeout stream bug** (`semif_agent/codegen.py`)
|
||||
- Move the `now - start >= self.timeout` check out of the `if not ready:`
|
||||
branch to the top of the `_read_stream` loop so it fires while streaming.
|
||||
- Test: fake SSE server that streams forever → `CodegenError` "total budget"
|
||||
must raise while tokens still flow.
|
||||
- Verify: `python3 -m pytest tests/ -q --ignore=tests/integration`.
|
||||
|
||||
- [ ] **2. Auto-detect context window + layered token budget** (`codegen.py`, `cli.py`, `config.example.json`)
|
||||
- `CodegenClient` lazily queries `GET /api/show {model}` → `parameters.num_ctx`
|
||||
(fallback `model_info.<arch>.context_length`, then `context_window` config,
|
||||
then default 100000).
|
||||
- Per request: `total_limit = min(smart_limit, window*max_fill_ratio)`;
|
||||
`output_limit = min(max_output, total_limit - prompt_est)`;
|
||||
`warn_point = min(warn_limit, window*warn_fill_ratio)`.
|
||||
- `max_output`: `>=1` = absolute tokens, `0<x<1` = fraction of window,
|
||||
default `0.25`. Enforce in `_read_stream` via chars→tokens estimate
|
||||
(`chars_per_token`). Abort → `CodegenError` → graceful stub.
|
||||
- Print a start line: context tokens, output cap tokens + %, peak total fill.
|
||||
- Config: `codegen.{context_window=0, smart_limit=100000, warn_limit=200000,
|
||||
max_fill_ratio=0.8, warn_fill_ratio=0.5, max_output=0.25, chars_per_token=4.0}`.
|
||||
- Tests: cap trips at fraction-of-window and absolute forms (fake server +
|
||||
explicit window); `/api/show` parse (mock the fetch).
|
||||
|
||||
- [ ] **3. Exact token accounting via include_usage** (`codegen.py`)
|
||||
- Send `stream_options: {"include_usage": true}`; capture the `usage` chunk
|
||||
in `_consume_frame`; after the stream log real `prompt/completion/total`
|
||||
tokens, % of window, and zone `SMART|WARN|DUMB` (absolute thresholds
|
||||
`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`)
|
||||
- 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);
|
||||
non-None → `CodegenError`.
|
||||
- Wire in `cli.build_scheduler`: 2-option SemIf decision (continue/stop);
|
||||
`P(stop) >= threshold` aborts. Record as a **trace-only** event
|
||||
(kind `codegen`, with probs) — never in the decision log.
|
||||
- Config: `codegen.degeneration.{enabled, threshold=0.9, interval=8000,
|
||||
window=2000, min_chars=4000}`. Disabled when no engine (keeps
|
||||
`CodegenClient` standalone pure for unit tests).
|
||||
- Tests: a callback returning a reason aborts the stream; not invoked when
|
||||
disabled.
|
||||
|
||||
- [ ] **5. Sampler params + 3-attempt escalation ladder** (`codegen.py`, `cli.py`)
|
||||
- Send `temperature`/`top_p`/`presence_penalty`/`frequency_penalty`
|
||||
(defaults `0.15`/`0.95`/`0.1`/`0.2`).
|
||||
- `generate_skill_body` escalates on degeneration or invalid parse:
|
||||
attempts 2–3 use `temp 0.3 / presence 0.3 / freq 0.5` + a corrective
|
||||
message ("You are looping; emit the final Python now."). Max 3 attempts
|
||||
(config `max_attempts`), then graceful stub. Retry = fresh short prompt,
|
||||
i.e. context resets to SMART.
|
||||
- Tests: payload carries the params; retry uses escalated params.
|
||||
|
||||
- [ ] **6. Box Modelfile anti-loop levers** (guppy; infra, not a code change)
|
||||
- `repeat_penalty`/`min_p` are not reachable via OpenAI-compat, so set them
|
||||
server-side: edit the qwen38-iq3s Modelfile to `PARAMETER repeat_penalty 1.2`
|
||||
and `PARAMETER min_p 0.05`, then `ollama create qwen38-iq3s -f ...`.
|
||||
- Verify: `ollama show --modelfile qwen38-iq3s` shows the params; re-run
|
||||
`test_generate_skill_body_codegen` and
|
||||
`test_create_category_chain_runs_new_skill`; confirm no long loop.
|
||||
|
||||
- [ ] **7. SKILL.md auditability** (`codegen.py`, `scheduler.py`, `static/app.js`)
|
||||
- `read_skill_contract` also yields sha256 of SKILL.md; record
|
||||
`contract_sha256` on the `skill_writing` trace event (+ dashboard display).
|
||||
- Test: the actually-sent HTTP payload's system message contains a SKILL.md
|
||||
phrase (harness already records request bodies).
|
||||
|
||||
- [ ] **8. Config + AGENTS.md docs**
|
||||
- Update `config.example.json` codegen block and the AGENTS.md codegen
|
||||
section with every new key from items 2, 4, 5.
|
||||
|
||||
### Code principles
|
||||
- **No mocking.** The decision engine is always real SemIf; the LLM is always a
|
||||
real endpoint. Pure unit tests touch data-structure math only (queue ordering,
|
||||
|
||||
+22
-9
@@ -114,10 +114,12 @@ class CodegenClient:
|
||||
Reads are gated by `select` so the socket never blocks-and-times-out:
|
||||
a socket that delivers no bytes for `idle_warn` seconds prints a
|
||||
warning, and `idle_timeout` seconds of silence raises CodegenError.
|
||||
The total wall-clock budget is `self.timeout`, so a slow-but-streaming
|
||||
generation is never cut short. Thresholds <= 0 disable that check. If
|
||||
the underlying socket can't be reached, falls back to a plain blocking
|
||||
read (relying on the outer TimeoutError handling).
|
||||
The total wall-clock budget `self.timeout` is enforced against the
|
||||
whole stream and checked on every loop iteration, so even a
|
||||
continuously-streaming generation that never sends `[DONE]` is cut
|
||||
short. 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 total budget).
|
||||
"""
|
||||
parts: list[str] = []
|
||||
sock = self._stream_socket(response)
|
||||
@@ -127,6 +129,10 @@ class CodegenClient:
|
||||
last_activity = start
|
||||
warned = False
|
||||
while True:
|
||||
if time.monotonic() - start >= self.timeout:
|
||||
raise CodegenError(
|
||||
f"codegen request exceeded {self.timeout:.0f}s total budget"
|
||||
)
|
||||
ready, _, _ = select.select([sock], [], [], 1.0)
|
||||
now = time.monotonic()
|
||||
if not ready:
|
||||
@@ -143,10 +149,6 @@ class CodegenClient:
|
||||
f"codegen stream stalled: no tokens for {idle:.0f}s "
|
||||
f"(idle_timeout={self.idle_timeout:.0f}s)"
|
||||
)
|
||||
if now - start >= self.timeout:
|
||||
raise CodegenError(
|
||||
f"codegen request exceeded {self.timeout:.0f}s total budget"
|
||||
)
|
||||
continue
|
||||
try:
|
||||
raw = response.readline()
|
||||
@@ -163,9 +165,20 @@ class CodegenClient:
|
||||
return "".join(parts)
|
||||
|
||||
def _read_stream_blocking(self, response) -> str:
|
||||
"""Fallback reader when the response socket can't be located."""
|
||||
"""Fallback reader when the response socket can't be located.
|
||||
|
||||
A plain blocking read relies on the per-read socket timeout for
|
||||
silence, but that bounds individual reads, not the whole stream — so
|
||||
enforce the same total wall-clock budget `self.timeout` in the loop,
|
||||
or a continuously-streaming runaway would never be cut short.
|
||||
"""
|
||||
parts: list[str] = []
|
||||
start = time.monotonic()
|
||||
for raw in response:
|
||||
if time.monotonic() - start >= self.timeout:
|
||||
raise CodegenError(
|
||||
f"codegen request exceeded {self.timeout:.0f}s total budget"
|
||||
)
|
||||
if not self._consume_frame(raw.decode("utf-8").strip(), parts):
|
||||
break
|
||||
if parts:
|
||||
|
||||
@@ -78,7 +78,7 @@ class CreateSkill:
|
||||
class CreateCategory:
|
||||
"""Suggestion that the request needs a brand-new top-level category.
|
||||
|
||||
Unlike CreateSkill this is handled live: the decision model is used in
|
||||
Like CreateSkill this is handled live: the decision model is used in
|
||||
normal generation mode to author the category stub.
|
||||
"""
|
||||
|
||||
|
||||
@@ -320,6 +320,89 @@ def _sse_frame(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload)}\n\n"
|
||||
|
||||
|
||||
class _RunawayStreamOpenAI(BaseHTTPRequestHandler):
|
||||
"""Streams content frames forever, never sending `[DONE]`.
|
||||
|
||||
Stands in for a degenerated generation that keeps producing tokens
|
||||
without finishing; the client must trip its total wall-clock budget
|
||||
even while bytes are still flowing. Drops out quietly when the client
|
||||
aborts the connection.
|
||||
"""
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(length)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
self.wfile.flush()
|
||||
try:
|
||||
while True:
|
||||
frame = _sse_frame(
|
||||
{"choices": [{"delta": {"content": "x"}}]}
|
||||
)
|
||||
self.wfile.write(frame.encode("utf-8"))
|
||||
self.wfile.flush()
|
||||
time.sleep(0.02)
|
||||
except (BrokenPipeError, ConnectionResetError, OSError):
|
||||
pass
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
|
||||
def test_chat_stream_total_budget_fires_while_streaming():
|
||||
"""A continuously-streaming runaway must be cut short by the total
|
||||
budget, not loop forever. idle_timeout (0.5s) < timeout (1.0s) makes the
|
||||
assertion meaningful: had the stream gone silent, "stalled" would have
|
||||
fired first — matching "total budget" proves the check ran while tokens
|
||||
were still flowing."""
|
||||
handler = type("Handler", (_RunawayStreamOpenAI,), {})
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
try:
|
||||
client = CodegenClient(
|
||||
base_url=f"http://127.0.0.1:{httpd.server_address[1]}/v1",
|
||||
model="test",
|
||||
timeout=1.0,
|
||||
stream=True,
|
||||
idle_warn=0.25,
|
||||
idle_timeout=0.5,
|
||||
)
|
||||
started = time.monotonic()
|
||||
with pytest.raises(CodegenError, match="total budget"):
|
||||
client.chat([{"role": "user", "content": "hi"}])
|
||||
elapsed = time.monotonic() - started
|
||||
assert 0.9 <= elapsed < 5.0, f"budget should fire ~1s in, took {elapsed:.1f}s"
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
class _ForeverFrames:
|
||||
"""Infinite iterable of valid content SSE lines (no `[DONE]`)."""
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
time.sleep(0.05)
|
||||
return _sse_frame({"choices": [{"delta": {"content": "x"}}]}).encode("utf-8")
|
||||
|
||||
|
||||
def test_read_stream_blocking_enforces_total_budget():
|
||||
"""The blocking fallback must enforce the total budget too — its
|
||||
per-read socket timeout bounds individual reads, not the whole stream."""
|
||||
client = CodegenClient(
|
||||
base_url="http://unused", model="test", timeout=0.5, stream=True
|
||||
)
|
||||
started = time.monotonic()
|
||||
with pytest.raises(CodegenError, match="total budget"):
|
||||
client._read_stream_blocking(_ForeverFrames())
|
||||
elapsed = time.monotonic() - started
|
||||
assert elapsed < 5.0, f"blocking fallback should fail fast, took {elapsed:.1f}s"
|
||||
|
||||
|
||||
class _StreamingOpenAI(BaseHTTPRequestHandler):
|
||||
"""Replies with an OpenAI-compatible SSE token stream (COT then content).
|
||||
|
||||
|
||||
Reference in new issue
Block a user