ship exact token accounting via include_usage (codegen guardrail item 3)

This commit is contained in:
Denton Social committed 2026-09-24 23:12:12 -05:00
1 parent 340520d630
commit db7d431976
3 files changed
+166 -11

No files matched your search

+9 -1
View File
@@ -316,12 +316,20 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
both confirmed live on the box (`context window 100000 tokens` start both confirmed live on the box (`context window 100000 tokens` start
line; abort at the configured cap). line; abort at the configured cap).
- [ ] **3. Exact token accounting via include_usage** (`codegen.py`) - [x] **3. Exact token accounting via include_usage** (`codegen.py`)
- Send `stream_options: {"include_usage": true}`; capture the `usage` chunk - Send `stream_options: {"include_usage": true}`; capture the `usage` chunk
in `_consume_frame`; after the stream log real `prompt/completion/total` in `_consume_frame`; after the stream log real `prompt/completion/total`
tokens, % of window, and zone `SMART|WARN|DUMB` (absolute thresholds tokens, % of window, and zone `SMART|WARN|DUMB` (absolute thresholds
`smart_limit`/`warn_limit`). `smart_limit`/`warn_limit`).
- Test: fake server emits a usage chunk; assert it's captured and logged. - Test: fake server emits a usage chunk; assert it's captured and logged.
- Implemented on the dev machine (2026-09-24): `_consume_frame` now also
tolerates a usage chunk with an empty `choices` list (OpenAI's shape —
previously an `IndexError`) and returns the `usage` dict; both stream
readers capture it and `_log_usage` prints real `prompt/completion/total`
tokens, % of the detected window, and the zone once the stream ends.
`chat` always sends `stream_options: {"include_usage": true}`. Unit-tested
(payload carries include_usage; usage captured + zone parametrized
SMART/WARN/DUMB; a stream without a usage chunk logs nothing extra).
- [x] **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 - Add optional `degeneration_check: Callable[[str], str|None]` to
+56 -10
View File
@@ -174,6 +174,7 @@ class CodegenClient:
self.frequency_penalty if frequency_penalty is None else frequency_penalty self.frequency_penalty if frequency_penalty is None else frequency_penalty
), ),
"stream": True, "stream": True,
"stream_options": {"include_usage": True},
} }
if max_tokens is not None: if max_tokens is not None:
payload["max_tokens"] = max_tokens payload["max_tokens"] = max_tokens
@@ -295,6 +296,35 @@ class CodegenClient:
) )
sys.stdout.flush() sys.stdout.flush()
def _log_usage(self, budget: TokenBudget, usage: dict) -> None:
"""Report exact token usage once `include_usage` yields a usage chunk.
Logs real prompt/completion/total tokens, % of the detected window, and
the zone (SMART < smart_limit, WARN < warn_limit, else DUMB) measured
against absolute total-token thresholds.
"""
prompt = usage.get("prompt_tokens")
completion = usage.get("completion_tokens")
total = usage.get("total_tokens")
if not isinstance(total, int):
return
if not isinstance(prompt, int):
prompt = total - (completion if isinstance(completion, int) else 0)
if not isinstance(completion, int):
completion = total - prompt
pct = total / budget.window * 100 if budget.window else 0.0
if self.smart_limit > 0 and total < self.smart_limit:
zone = "SMART"
elif self.warn_limit > 0 and total < self.warn_limit:
zone = "WARN"
else:
zone = "DUMB"
print(
f"[codegen] usage: prompt {prompt} · completion {completion} · "
f"total {total} tokens · {pct:.0f}% of window · {zone}"
)
sys.stdout.flush()
def _enforce_budget(self, budget: TokenBudget, out_chars: int, warned: bool) -> bool: def _enforce_budget(self, budget: TokenBudget, out_chars: int, warned: bool) -> bool:
"""Abort when the output cap is exceeded; one-shot warn near the fill """Abort when the output cap is exceeded; one-shot warn near the fill
threshold. Returns the updated warned state.""" threshold. Returns the updated warned state."""
@@ -353,6 +383,7 @@ class CodegenClient:
warned = False warned = False
warned_fill = False warned_fill = False
out_chars = 0 out_chars = 0
usage: dict | None = None
recent: list[str] = [] recent: list[str] = []
recent_len = 0 recent_len = 0
last_check: int | None = None last_check: int | None = None
@@ -385,9 +416,11 @@ class CodegenClient:
if not raw: if not raw:
break break
last_activity = time.monotonic() last_activity = time.monotonic()
continues, text, reasoning = self._consume_frame( continues, text, reasoning, frame_usage = self._consume_frame(
raw.decode("utf-8").strip() raw.decode("utf-8").strip()
) )
if frame_usage is not None:
usage = frame_usage
if self.stream and (text or reasoning): if self.stream and (text or reasoning):
sys.stdout.write(text + reasoning) sys.stdout.write(text + reasoning)
sys.stdout.flush() sys.stdout.flush()
@@ -405,6 +438,8 @@ class CodegenClient:
raise DegenerationError(f"codegen degeneration detected: {reason}") raise DegenerationError(f"codegen degeneration detected: {reason}")
if not continues: if not continues:
break break
if usage is not None:
self._log_usage(budget, usage)
if parts and self.stream: if parts and self.stream:
sys.stdout.write("\n") sys.stdout.write("\n")
sys.stdout.flush() sys.stdout.flush()
@@ -428,6 +463,7 @@ class CodegenClient:
start = time.monotonic() start = time.monotonic()
warned_fill = False warned_fill = False
out_chars = 0 out_chars = 0
usage: dict | None = None
recent: list[str] = [] recent: list[str] = []
recent_len = 0 recent_len = 0
last_check: int | None = None last_check: int | None = None
@@ -436,9 +472,11 @@ class CodegenClient:
raise CodegenError( raise CodegenError(
f"codegen request exceeded {self.timeout:.0f}s total budget" f"codegen request exceeded {self.timeout:.0f}s total budget"
) )
continues, text, reasoning = self._consume_frame( continues, text, reasoning, frame_usage = self._consume_frame(
raw.decode("utf-8").strip() raw.decode("utf-8").strip()
) )
if frame_usage is not None:
usage = frame_usage
if self.stream and (text or reasoning): if self.stream and (text or reasoning):
sys.stdout.write(text + reasoning) sys.stdout.write(text + reasoning)
sys.stdout.flush() sys.stdout.flush()
@@ -456,6 +494,8 @@ class CodegenClient:
raise DegenerationError(f"codegen degeneration detected: {reason}") raise DegenerationError(f"codegen degeneration detected: {reason}")
if not continues: if not continues:
break break
if usage is not None:
self._log_usage(budget, usage)
if parts and self.stream: if parts and self.stream:
sys.stdout.write("\n") sys.stdout.write("\n")
sys.stdout.flush() sys.stdout.flush()
@@ -493,26 +533,32 @@ class CodegenClient:
return None, last_check return None, last_check
@staticmethod @staticmethod
def _consume_frame(line: str) -> tuple[bool, str, str]: def _consume_frame(line: str) -> tuple[bool, str, str, dict | None]:
"""Process one SSE line. """Process one SSE line.
Returns (continue, content, reasoning). `content` feeds the returned Returns (continue, content, reasoning, usage). `content` feeds the
body; `reasoning` is only ever echoed. (False, "", "") on [DONE]. returned body; `reasoning` is only ever echoed; `usage` is the exact
token usage carried on the final chunk when `include_usage` was
requested (None otherwise). (False, "", "", None) on [DONE].
""" """
if not line.startswith("data:"): if not line.startswith("data:"):
return True, "", "" return True, "", "", None
data = line[len("data:") :].strip() data = line[len("data:") :].strip()
if data == "[DONE]": if data == "[DONE]":
return False, "", "" return False, "", "", None
try: try:
chunk = json.loads(data) chunk = json.loads(data)
except ValueError: except ValueError:
return True, "", "" return True, "", "", None
choice = chunk.get("choices", [{}])[0] usage = chunk.get("usage")
if not isinstance(usage, dict):
usage = None
choices = chunk.get("choices") or []
choice = choices[0] if choices else {}
delta = choice.get("delta", {}) or {} delta = choice.get("delta", {}) or {}
text = delta.get("content") or "" text = delta.get("content") or ""
reasoning = delta.get("reasoning_content") or delta.get("reasoning") or "" reasoning = delta.get("reasoning_content") or delta.get("reasoning") or ""
return True, text, reasoning return True, text, reasoning, usage
@staticmethod @staticmethod
def _stream_socket(response): def _stream_socket(response):
+101
View File
@@ -613,6 +613,7 @@ def test_chat_stream_accumulates_full_content():
assert out == GOOD_BODY, "streamed deltas must reassemble the full body" assert out == GOOD_BODY, "streamed deltas must reassemble the full body"
body = httpd.RequestHandlerClass.received[0] body = httpd.RequestHandlerClass.received[0]
assert body["stream"] is True assert body["stream"] is True
assert body["stream_options"] == {"include_usage": True}
finally: finally:
httpd.shutdown() httpd.shutdown()
httpd.server_close() httpd.server_close()
@@ -647,6 +648,106 @@ def test_chat_stream_false_returns_content_without_echo(capsys):
httpd.server_close() httpd.server_close()
class _UsageOpenAI(BaseHTTPRequestHandler):
"""Streams a small content delta, then the exact-token usage chunk
(`choices: []` — OpenAI's shape when include_usage is set) before
[DONE]. The `/api/show` window query is answered (default num_ctx 4242)
and never recorded."""
usage: dict = {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15}
content: str = "ok\n"
received: list = []
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length).decode("utf-8")
if _respond_show(self):
return
type(self).received.append(json.loads(raw))
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
self.wfile.write(
_sse_frame({"choices": [{"delta": {"content": self.content}}]}).encode("utf-8")
)
self.wfile.write(
_sse_frame({"choices": [], "usage": self.usage}).encode("utf-8")
)
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
self.close_connection = True
def log_message(self, format, *args):
pass
def _usage_server() -> tuple[ThreadingHTTPServer, str]:
handler = type("Handler", (_UsageOpenAI,), {"received": []})
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def test_chat_captures_usage_chunk():
"""A usage chunk (empty choices) must be consumed without crashing and
the real token counts logged after the stream — the include_usage path."""
httpd, base = _usage_server()
try:
client = CodegenClient(base_url=base, model="test", timeout=10)
out = client.chat([{"role": "user", "content": "hi"}])
assert out == "ok\n"
assert httpd.RequestHandlerClass.received[0]["stream_options"] == {
"include_usage": True
}
finally:
httpd.shutdown()
httpd.server_close()
@pytest.mark.parametrize(
("smart_limit", "warn_limit", "zone"),
[
(250000, 500000, "SMART"),
(10, 500, "WARN"),
(10, 14, "DUMB"),
],
)
def test_chat_logs_real_usage_with_zone(smart_limit, warn_limit, zone, capsys):
"""Real usage is logged with prompt/completion/total tokens, % of window,
and the zone by absolute total-token thresholds."""
httpd, base = _usage_server()
try:
client = CodegenClient(
base_url=base,
model="test",
timeout=10,
smart_limit=smart_limit,
warn_limit=warn_limit,
)
client.chat([{"role": "user", "content": "hi"}])
captured = capsys.readouterr().out
assert "prompt 5 · completion 10 · total 15 tokens" in captured
assert "0% of window" in captured
assert zone in captured
finally:
httpd.shutdown()
httpd.server_close()
def test_chat_no_usage_chunk_logs_nothing(capsys):
"""Without an include_usage chunk nothing extra is logged — old servers
keep working and the budget line is the only output."""
httpd, base = _streaming_server()
try:
client = CodegenClient(base_url=base, model="test", timeout=10, stream=True)
client.chat([{"role": "user", "content": "hi"}])
captured = capsys.readouterr().out
assert "usage: prompt" not in captured
finally:
httpd.shutdown()
httpd.server_close()
def test_chat_omits_max_tokens_by_default(): def test_chat_omits_max_tokens_by_default():
httpd, base = _fake_server(GOOD_BODY) httpd, base = _fake_server(GOOD_BODY)
try: try: