Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Finish completed streams without replay and preserve unknown usage

Rach Pradhan704e1149ee3b
diff --git a/docs/adr/0176-completed-streams-do-not-replay-on-trailer-timeout.md b/docs/adr/0176-completed-streams-do-not-replay-on-trailer-timeout.md
new file mode 100644
index 00000000..7faa6a87
--- /dev/null
+++ b/docs/adr/0176-completed-streams-do-not-replay-on-trailer-timeout.md
@@ -0,0 +1,29 @@
+# 0176. Completed streams do not replay on trailer timeout
+
+Status: accepted 2026-09-23
+
+## Context
+
+A streamed response can contain a terminal choice and usage while its connection
+remains open. The reader already accepted a subsequent connection close, but a
+silent trailer deadline retried the completed request and discarded its usage.
+
+## Decision
+
+Recognize a terminal choice structurally, with a cheap check that rejects ordinary
+null-marker chunks before parsing. Continue reading for a separate usage trailer.
+If the existing watchdog deadline then expires after valid completion, retire the
+connection and return the buffered response. Apply the same rule to both stream
+transports. Cancellation remains cancellation; an unterminated response still
+fails and follows the existing retry policy.
+
+A completed response without usage increments the observed call count and marks
+token and cost totals incomplete. Preserve reported subtotals without treating
+unknown usage as zero or mixing reported charges with list-price estimates.
+
+## Consequences
+
+The fix avoids replaying completed work without shortening the normal trailer
+wait. Offline unit and TLS/HTTP2 cases cover delayed usage, omitted usage, empty
+completed output, normal termination, and a genuinely unterminated response.
+This does not recover usage from other failed attempts or establish their charges.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index d5e7b217..2cf21688 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -199,6 +199,7 @@ record only when you need the evidence or the edge cases.
| [0174](0174-completion-requires-terminal-tool-results.md) | Deferred completion rejects pending work and preserves background verification exit status. |
| [0175](0175-rlm-preserves-dependent-tool-order.md) | RLM speculates only leading read-only calls, then preserves statement order and stopped tool results. |
+| [0176](0176-completed-streams-do-not-replay-on-trailer-timeout.md) | A trailer deadline after valid completion returns buffered output; missing usage stays explicitly unknown. |
## When to write one
diff --git a/graff-evals/list_price.py b/graff-evals/list_price.py
index e04b6d37..e8eebc32 100644
--- a/graff-evals/list_price.py
+++ b/graff-evals/list_price.py
@@ -171,6 +171,14 @@ def usd_tools(counts: dict | None) -> float:
def attach(rec: dict, inclusive: bool | None = None) -> dict:
"""Mutate `rec` with list-price fields. Returns rec."""
+ if rec.get("tok_missing_usage_calls") or rec.get("tok_usage_complete") is False:
+ # Known subtotals remain in tok_known_*; do not price unknown totals
+ # as zero or reinterpret a subtotal as complete subscription usage.
+ for key in ("ordinary", "cached", "out", "prompt", "tokens",
+ "token_usd", "tool_usd", "usd", "high_band"):
+ rec["list_" + key] = None
+ rec["list_price_kind"] = "unavailable-missing-usage"
+ return rec
if inclusive is None:
inclusive = convention_for(rec)
ordinary, cached = ordinary_and_cached(rec.get("tok_in"), rec.get("tok_cached"), inclusive)
diff --git a/graff-evals/measurement.py b/graff-evals/measurement.py
index 9c2802c2..6715ea5a 100644
--- a/graff-evals/measurement.py
+++ b/graff-evals/measurement.py
@@ -36,6 +36,17 @@ def graff_usage(stderr):
result['metered_cost_usd'] = result.get('cost_usd')
result['cost_usd'] = None
result['cost_kind'] = 'metered-only-subscription-excluded'
+ missing = re.search(r'totals incomplete: (\d+) call\(s\) missing usage \(tokens and cost unknown\)', tail)
+ if missing and int(missing.group(1)):
+ result['missing_usage_calls'] = int(missing.group(1))
+ result['usage_complete'] = False
+ for key in ('in', 'cached', 'writes', 'out'):
+ result['known_' + key] = result[key]
+ result[key] = None
+ # The footer dollar amount is a subtotal, including when it is zero.
+ result['known_cost_usd'] = float(m.group(6)) if m.group(6) is not None else None
+ result['cost_usd'] = None
+ result['cost_kind'] = 'incomplete-missing-usage'
return result
diff --git a/graff-evals/report.py b/graff-evals/report.py
index 4e1468eb..bc08c455 100644
--- a/graff-evals/report.py
+++ b/graff-evals/report.py
@@ -39,7 +39,7 @@ def bucket(records, suite=None):
"n": 0, "ok": 0, "wall": 0.0, "first": 0.0, "first_n": 0,
"tin": 0, "tcached": 0, "tout": 0, "calls": 0, "rss": 0, "cpu": 0.0,
"usd": 0.0, "usd_n": 0, "pass_n": 0,
- "tasks": {},
+ "tasks": {}, "missing_usage_calls": 0,
})
b["n"] += 1
passed = bool(r.get("outcome_ok"))
@@ -54,6 +54,11 @@ def bucket(records, suite=None):
b["first_n"] += 1
cost_ok = passed if live else True
if cost_ok:
+ if r.get("tok_missing_usage_calls") or r.get("tok_usage_complete") is False:
+ b["missing_usage_calls"] += r.get("tok_missing_usage_calls") or 1
+ b["tin"] += max((r.get("tok_known_in") or 0) - (r.get("tok_known_cached") or 0), 0)
+ b["tcached"] += r.get("tok_known_cached") or 0
+ b["tout"] += r.get("tok_known_out") or 0
b["tin"] += r.get("list_ordinary") if r.get("list_ordinary") is not None else (r.get("tok_in") or 0)
b["tcached"] += r.get("list_cached") if r.get("list_cached") is not None else (r.get("tok_cached") or 0)
b["tout"] += r.get("tok_out") or 0
@@ -68,6 +73,11 @@ def bucket(records, suite=None):
if not cpu:
cpu = (r.get("cpu_user_s") or 0) + (r.get("cpu_sys_s") or 0)
b["cpu"] += cpu
+ for b in by.values():
+ if b["missing_usage_calls"]:
+ for key in ("tin", "tcached", "tout", "usd"):
+ b["known_" + key] = b[key]
+ b[key] = None
if live:
for b in by.values():
b["task_n"] = len(b["tasks"])
@@ -83,15 +93,19 @@ def print_table(title, by, suite=None):
else:
print(f"{'harness':<16} {'pass':>7} {'wall':>8} {'first':>7} {'rss':>8} {'cpu':>7} {'in':>8} {'cached':>8} {'out':>8} {'calls':>6} {'list$':>8}")
for h, b in by.items():
- usd = f"${b['usd']:.4f}" if b["usd_n"] else "—"
+ usd = f"${b['usd']:.4f}" if b["usd_n"] and b['usd'] is not None else "—"
+ tin, tcached, tout = (b[k] if b[k] is not None else "unknown" for k in ("tin", "tcached", "tout"))
if live:
tasks = f"{b.get('task_ok', 0)}/{b.get('task_n', 0)}"
print(f"{h:<16} {b['ok']}/{b['n']:<5} {tasks:>8} {b['wall']:>7.1f}s "
- f"{fmt_mib(b['rss']):>8} {b['tin']:>8} {b['tout']:>8} {b['calls']:>6} {usd:>8}")
+ f"{fmt_mib(b['rss']):>8} {tin:>8} {tout:>8} {b['calls']:>6} {usd:>8}")
else:
first = (b["first"] / b["first_n"]) if b["first_n"] else 0.0
print(f"{h:<16} {b['ok']}/{b['n']:<5} {b['wall']:>7.1f}s {first:>6.1f}s "
- f"{fmt_mib(b['rss']):>8} {b['cpu']:>6.1f}s {b['tin']:>8} {b.get('tcached', 0):>8} {b['tout']:>8} {b['calls']:>6} {usd:>8}")
+ f"{fmt_mib(b['rss']):>8} {b['cpu']:>6.1f}s {tin:>8} {tcached:>8} {tout:>8} {b['calls']:>6} {usd:>8}")
+ if b.get("missing_usage_calls"):
+ print(f" totals incomplete: {b['missing_usage_calls']} call(s) missing usage; "
+ f"known token subtotals in={b['known_tin']} cached={b['known_tcached']} out={b['known_tout']}")
def summarize(records):
@@ -108,9 +122,13 @@ def summarize(records):
def line(rec):
cpu = rec.get("cpu_sample_s") or ((rec.get("cpu_user_s") or 0) + (rec.get("cpu_sys_s") or 0))
ok = "✓" if rec.get("outcome_ok") else "✗"
+ incomplete = rec.get("tok_missing_usage_calls") or rec.get("tok_usage_complete") is False
+ if incomplete:
+ rec = dict(rec, list_ordinary="unknown", list_cached="unknown", tok_out="unknown", list_usd="unknown")
return (f"{ok} {rec.get('harness', '?'):<16} {rec.get('task', '?'):<18} "
f"r{rec.get('rep', '?')} {rec.get('wall_s', '?')}s "
f"first={rec.get('first_out_s', '—')}s rss={fmt_mib(rec.get('rss_peak_kb'))} "
f"cpu={cpu:.1f}s in={rec.get('list_ordinary', rec.get('tok_in', '?'))} "
f"cached={rec.get('list_cached', rec.get('tok_cached', '—'))} "
- f"out={rec.get('tok_out', '?')} list=${rec.get('list_usd', '—')}")
+ f"out={rec.get('tok_out', '?')} list=${rec.get('list_usd', '—')}"
+ + (f" totals incomplete: {rec.get('tok_missing_usage_calls', '?')} call(s) missing usage" if incomplete else ""))
diff --git a/graff-evals/test_measurement.py b/graff-evals/test_measurement.py
index 90d155ff..00673530 100644
--- a/graff-evals/test_measurement.py
+++ b/graff-evals/test_measurement.py
@@ -1,5 +1,7 @@
"""Offline checks for trustworthy cross-model receipts and routing isolation."""
import json
+import contextlib
+import io
import os
from pathlib import Path
import tempfile
@@ -9,6 +11,7 @@ from unittest.mock import patch
import list_price
import measurement
import request_capture
+import report
class MeasurementTests(unittest.TestCase):
@@ -31,6 +34,82 @@ class MeasurementTests(unittest.TestCase):
self.assertIsNone(measurement.graff_usage(base + '2 subscription call(s), flat-rate (not in $)')['cost_usd'])
self.assertEqual(measurement.graff_usage(base + '2 subscription call(s), flat-rate (not in $)')['cost_kind'], 'metered-only-subscription-excluded')
+ def test_missing_usage_preserves_subtotals_without_claiming_complete_totals(self):
+ footer = ('[usage] 3 api call(s) · 80 in (40 cached, 5 cache writes) + 9 out tokens · $0.001234'
+ ' · totals incomplete: 1 call(s) missing usage (tokens and cost unknown)')
+ usage = measurement.graff_usage(footer)
+ self.assertEqual(usage['calls'], 3)
+ self.assertEqual(usage['missing_usage_calls'], 1)
+ self.assertFalse(usage['usage_complete'])
+ for key, subtotal in [('in', 80), ('cached', 40), ('writes', 5), ('out', 9), ('cost_usd', .001234)]:
+ self.assertIsNone(usage[key])
+ self.assertEqual(usage['known_' + key], subtotal)
+ self.assertEqual(usage['cost_kind'], 'incomplete-missing-usage')
+ # Exercise the runner's actual receipt prefix and downstream pricing.
+ row = dict(model='grok-4.6', requested_provider='xai', harness='graff-dev',
+ **{'tok_' + k: v for k, v in usage.items()})
+ list_price.attach(row)
+ for key in ('ordinary', 'cached', 'out', 'prompt', 'tokens', 'token_usd', 'tool_usd', 'usd', 'high_band'):
+ self.assertIsNone(row['list_' + key])
+ self.assertEqual(row['list_price_kind'], 'unavailable-missing-usage')
+ self.assertEqual(row['tok_known_in'], 80)
+
+ def test_all_missing_usage_zero_subtotals_and_subscription_are_unknown(self):
+ base = '[usage] 2 api call(s) · 0 in (0 cached) + 0 out tokens · $0.000000 · '
+ missing = 'totals incomplete: 2 call(s) missing usage (tokens and cost unknown)'
+ for classification in ('', '2 subscription call(s), flat-rate (not in $) · ',
+ '2 call(s) on unpriced models · '):
+ with self.subTest(classification=classification):
+ usage = measurement.graff_usage(base + classification + missing)
+ self.assertEqual(usage['known_in'], 0)
+ self.assertEqual(usage['known_cost_usd'], 0)
+ self.assertIsNone(usage['in'])
+ self.assertIsNone(usage['cost_usd'])
+ self.assertEqual(usage['missing_usage_calls'], 2)
+ if classification.startswith('2 subscription'):
+ self.assertEqual(usage['sub_calls'], 2)
+ elif classification:
+ self.assertEqual(usage['unpriced_calls'], 2)
+
+ def test_incomplete_receipt_reporting_never_turns_missing_tokens_into_zero(self):
+ usage = measurement.graff_usage(
+ '[usage] 2 api call(s) · 80 in (40 cached) + 9 out tokens · $0.001234'
+ ' · totals incomplete: 1 call(s) missing usage (tokens and cost unknown)')
+ row = dict(harness='graff-dev', model='grok-4.6', outcome_ok=True,
+ **{'tok_' + k: v for k, v in usage.items()})
+ list_price.attach(row)
+ complete = dict(harness='graff-dev', outcome_ok=True, tok_in=10, tok_cached=2,
+ tok_out=3, tok_calls=1, tok_cost_usd=.01, list_usd=.02)
+ for suite in (None, 'live'):
+ grouped = report.bucket([row, complete], suite=suite)
+ bucket = grouped['graff-dev']
+ self.assertIsNone(bucket['tin'])
+ self.assertIsNone(bucket['usd'])
+ self.assertEqual(bucket['missing_usage_calls'], 1)
+ self.assertEqual(bucket['known_tin'], 50)
+ self.assertEqual(bucket['known_tcached'], 42)
+ self.assertEqual(bucket['known_tout'], 12)
+ # Only the complete row contributes its selected list-price estimate.
+ # The incomplete actual-route subtotal stays in the receipt.
+ self.assertEqual(bucket['known_usd'], .02)
+ self.assertEqual(row['tok_known_cost_usd'], .001234)
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ report.print_table('fixture', grouped, suite=suite)
+ self.assertIn('unknown', output.getvalue())
+ self.assertIn('totals incomplete: 1 call(s)', output.getvalue())
+ self.assertIn('in=unknown', report.line(row))
+ self.assertIn('totals incomplete', report.line(row))
+
+ def test_complete_legacy_footer_receipt_stays_unchanged(self):
+ footer = '[usage] 1 api call(s) · 80 in (40 cached, 5 cache writes) + 9 out tokens · $0.001234'
+ self.assertEqual(measurement.graff_usage(footer),
+ {'calls': 1, 'in': 80, 'cached': 40, 'writes': 5, 'out': 9,
+ 'cost_usd': .001234, 'cost_kind': 'harness-reported'})
+ missing = footer + ' · totals incomplete: 1 call(s) missing usage (tokens and cost unknown)'
+ self.assertIsNone(measurement.graff_usage(footer + '\n' + missing)['in'])
+ self.assertEqual(measurement.graff_usage(missing + '\n' + footer), measurement.graff_usage(footer))
+
def test_multi_request_band_is_unavailable_not_mispriced(self):
row = {'model': 'grok-4.6', 'tok_in': 250000, 'tok_calls': 2, 'tok_out': 100}
list_price.attach(row)
diff --git a/scripts/eval/http2-acp-mock.cjs b/scripts/eval/http2-acp-mock.cjs
index f3de0322..0d2e81b0 100644
--- a/scripts/eval/http2-acp-mock.cjs
+++ b/scripts/eval/http2-acp-mock.cjs
@@ -2,7 +2,7 @@
const http2 = require('node:http2');
const fs = require('node:fs');
const crypto = require('node:crypto');
-const [key, cert, log] = process.argv.slice(2);
+const [key, cert, log, completionMode] = process.argv.slice(2);
const record = value => fs.appendFileSync(log, JSON.stringify(value) + '\n');
const server = http2.createSecureServer({
key: fs.readFileSync(key), cert: fs.readFileSync(cert), allowHTTP1: false,
@@ -28,6 +28,18 @@ server.on('stream', (stream, headers) => {
stream: stream.id, method: headers[':method'], path: headers[':path'], body: JSON.parse(body) });
stream.respond({ ':status': 200, 'content-type': 'text/event-stream' });
const delta = text => `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: text }, finish_reason: null }] })}\n\n`;
+ if (completionMode) {
+ if (completionMode !== 'quiet-empty') stream.write(delta('OK'));
+ if (completionMode !== 'quiet-unterminated')
+ stream.write('data: {"choices": [{"index":0,"delta":{}, "finish_reason": "stop"}]}\n\n');
+ const usage = 'data: {"choices":[],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}}\n\n';
+ if (completionMode === 'done') stream.end(usage + 'data: [DONE]\n\n');
+ if (completionMode === 'quiet-usage') setTimeout(() => {
+ if (!stream.destroyed) stream.write(usage);
+ }, 100);
+ // Quiet cases deliberately send neither [DONE] nor END_STREAM.
+ return;
+ }
if (request === 5) {
const tool = { index: 0, id: 'fixture-child', type: 'function', function: {
name: 'subagent', arguments: JSON.stringify({ description: 'Inspect fixture',
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 0789450a..244bdca7 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 2687,
+ "test_count_baseline": 2690,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/scripts/test-chat-http2-completion.py b/scripts/test-chat-http2-completion.py
new file mode 100644
index 00000000..ec6daa1e
--- /dev/null
+++ b/scripts/test-chat-http2-completion.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Offline Chat completion deadlines through real TLS/ALPN HTTP/2.
+
+Reuses the ACP fixture's isolated additive CA seam; no production trust or
+cached dependency changes. A server that forbids HTTP/1 proves this exercises
+agent_stream_h2, including a delayed usage trailer and a silent open stream.
+"""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+
+REPO = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location('acp_h2', REPO/'scripts/test-acp-http2.py')
+fixture = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(fixture)
+
+
+def exercise(root, binary, mode):
+ case = root/mode
+ case.mkdir(mode=0o700)
+ (case/'mcp.json').write_text('{"mcpServers":{}}')
+ shim = case/'bin'
+ shim.mkdir()
+ (shim/'security').write_text('#!/bin/sh\nexit 44\n')
+ (shim/'security').chmod(0o700)
+ log = case/'server.jsonl'
+ log.touch()
+ server = None
+ with (case/'server-stderr').open('w') as stderr:
+ try:
+ server = subprocess.Popen(['node', str(REPO/'scripts/eval/http2-acp-mock.cjs'),
+ str(root/'server.key'), str(root/'server.pem'), str(log), mode],
+ stdout=subprocess.PIPE, stderr=stderr, text=True, start_new_session=True)
+ port = int(server.stdout.readline())
+ env = dict(HOME=str(case), PATH=str(shim)+':/usr/bin:/bin', TERM='dumb',
+ AI_GATEWAY_API_KEY='fixture', GRAFF_VERCEL_URL=f'https://localhost:{port}/v1/chat/completions',
+ GRAFF_MCP_CONFIG=str(case/'mcp.json'), GRAFF_HTTP2='1', GRAFF_STREAM_STALL_SECS='1',
+ GRAFF_NO_TELEMETRY='1', GRAFF_FLEET='off', GRAFF_NO_ADOPT='1',
+ GRAFF_NO_SMOLIFY='1', GRAFF_BEHAVIOR_UPLOAD='off', NO_COLOR='1')
+ start = time.monotonic()
+ run = subprocess.run([str(binary), '-p', '--model', 'vercel', '--no-local-tools', 'Reply OK'],
+ cwd=case, env=env, capture_output=True, text=True, timeout=20)
+ elapsed = time.monotonic()-start
+ (case/'stdout').write_text(run.stdout)
+ (case/'stderr').write_text(run.stderr)
+ rows = [json.loads(line) for line in log.read_text().splitlines()]
+ sessions = [r for r in rows if r['event'] == 'session']
+ requests = [r for r in rows if r['event'] == 'request']
+ assert sessions and all(r['alpn'] == 'h2' for r in sessions), rows
+ expected = 3 if mode in ('quiet-unterminated', 'quiet-empty') else 1
+ assert len(requests) == expected, (mode, len(requests), run.stderr)
+ if mode == 'quiet-unterminated':
+ assert run.returncode != 0 and 'StreamStalled' in run.stderr, run.stderr
+ else:
+ assert run.returncode == 0, run.stderr
+ if mode != 'quiet-empty':
+ assert run.stdout.strip() == 'OK', run.stdout
+ if mode in ('done', 'quiet-usage'):
+ assert '20 in (0 cached, 0 cache writes) + 2 out tokens' in run.stderr, run.stderr
+ assert 'missing usage' not in run.stderr, run.stderr
+ else:
+ assert f'totals incomplete: {expected} call(s) missing usage' in run.stderr, run.stderr
+ traces = [json.loads(line) for path in case.glob('.graff/traces/*.jsonl')
+ for line in path.read_text().splitlines()]
+ assert not any(r.get('ev') == 'stream_retry' for r in traces), traces
+ if mode == 'quiet-empty':
+ # The model loop independently retries semantically empty answers.
+ assert 'empty completion' in run.stderr, run.stderr
+ return dict(mode=mode, requests=len(requests), exit=run.returncode,
+ elapsed_s=round(elapsed, 3), alpn='h2')
+ finally:
+ fixture.terminate(server)
+
+
+def main():
+ root = Path(tempfile.mkdtemp(prefix='graff-chat-h2-'))
+ os.chmod(root, 0o700)
+ print(f'Private evidence: {root}', flush=True)
+ fixture.certificates(root)
+ binary = fixture.build(root)
+ results = []
+ for mode in ('done', 'quiet-usage', 'quiet-no-usage', 'quiet-empty', 'quiet-unterminated'):
+ result = exercise(root, binary, mode)
+ results.append(result)
+ print(json.dumps(result), flush=True)
+ (root/'results.json').write_text(json.dumps(results, indent=2))
+ print('PASS Chat completion deadlines over TLS HTTP/2', flush=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 3a7d92ca..2b531cf1 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -464,6 +464,10 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
try sayTypedApiError(self, etype, ecode, emsg, errorRequestId(root));
return error.ApiError;
};
+ if (self.provider.kind == .openai) {
+ const usage = root.get("usage");
+ if (usage == null or usage.? != .object) @import("pricing.zig").g_cost.missingUsage(self.io);
+ }
self.recordUsage(root, body.len);
if (recoverBehavioralOverflow(self, root, &context_retried)) continue; // #414: silent overflow / upstream truncation → trim + retry
if (!self.compaction_request) self.compact_transport_failures = 0;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 92813fac..9f9cff88 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -289,6 +289,10 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
return e;
},
.stall => |w| {
+ if (w == .deadline and saw_done) {
+ if (req.connection) |conn| conn.closing = true;
+ break :stream;
+ }
// A user Esc is a deliberate cancel; a `.deadline` is a dead or
// idle stream (silent past this read's budget) — end the turn as
// error.StreamStalled so it is never recorded as "[response
@@ -351,15 +355,7 @@ fn readErrIsClose(e: anyerror) bool {
return e == error.ReadFailed or e == error.EndOfStream;
}
-/// #133: a non-null string finish_reason marks an OpenAI-compatible response
-/// semantically complete, even when the provider omits the [DONE] sentinel.
-/// Content deltas escape their quotes, so this raw substring can only match the
-/// real key, never text. Used to set saw_done WITHOUT stopping the read (so a
-/// trailing usage-only chunk and [DONE] are still consumed).
-fn openaiComplete(raw_line: []const u8) bool {
- const payload = ssePayload(raw_line) orelse return false;
- return std.mem.indexOf(u8, payload, "\"finish_reason\":\"") != null;
-}
+pub const openaiComplete = @import("chat_stream_terminal.zig").complete;
/// True if this SSE line is the provider's terminal event — after it no more
/// content comes, so postStream can stop instead of waiting for the socket to
diff --git a/src/agent_stream_h2.zig b/src/agent_stream_h2.zig
index 506da235..8977c71e 100644
--- a/src/agent_stream_h2.zig
+++ b/src/agent_stream_h2.zig
@@ -15,6 +15,7 @@ const watchdogError = http.watchdogError;
const deadlineStallTask = @import("http.zig").deadlineStallTask;
const ssePayload = Agent.ssePayload;
+const openaiComplete = @import("agent_stream.zig").openaiComplete;
const isStreamEnd = @import("agent_stream.zig").isStreamEnd;
pub fn postStream(self: *Agent, body: []const u8) !?[]u8 {
@@ -76,7 +77,7 @@ pub fn postStream(self: *Agent, body: []const u8) !?[]u8 {
var got_body = false;
var saw_done = false;
- while (true) {
+ stream: while (true) {
const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, self.partial_text.items.len != 0, self.stall.widen);
read: {
const ReadDone = union(enum) { line: anyerror!bool, stall: WatchdogFired };
@@ -129,6 +130,7 @@ pub fn postStream(self: *Agent, body: []const u8) !?[]u8 {
}
},
.stall => |w| {
+ if (w == .deadline and saw_done) break :stream;
if (w == .deadline) self.stall.tripped_ms = stall_budget;
if (w == .deadline) sink.emit(self.io, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } }) else sink.emit(self.io, .{ .stream_aborted = .interrupted });
return watchdogError(w, error.StreamStalled);
@@ -169,8 +171,3 @@ fn lineTask(ls: *http_zig.conn.LineStream, dest: *std.ArrayList(u8), gpa: std.me
_ = gpa;
return ls.readLine(dest);
}
-
-fn openaiComplete(raw_line: []const u8) bool {
- const payload = ssePayload(raw_line) orelse return false;
- return std.mem.indexOf(u8, payload, "\"finish_reason\":\"") != null;
-}
diff --git a/src/agent_stream_stall_test.zig b/src/agent_stream_stall_test.zig
index 5def4e0a..0e782cf6 100644
--- a/src/agent_stream_stall_test.zig
+++ b/src/agent_stream_stall_test.zig
@@ -210,3 +210,79 @@ test "#680: each stall reconnect widens the between-lines wait the SSE reader ar
try std.testing.expect(std.mem.indexOf(u8, msg, "for 1s") != null);
try std.testing.expect(std.mem.indexOf(u8, msg, "after 2 reconnect attempts") != null);
}
+
+const TrailerSrv = struct {
+ const Mode = enum { usage, missing, empty, unterminated };
+ const finish_line = "data: {\"choices\": [{\"index\":0, \"delta\": {}, \"finish_reason\": \"stop\"}]}\n\n";
+ const usage_line = "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":2,\"total_tokens\":22}}\n\n";
+ fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {
+ const c = server.accept(io) catch return;
+ defer c.close(io);
+ var rbuf: [8192]u8 = undefined;
+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);
+ while (true) {
+ const line = (sr.interface.takeDelimiter('\n') catch return) orelse return;
+ if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;
+ }
+ var wbuf: [1024]u8 = undefined;
+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);
+ sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n") catch return;
+ if (mode != .empty) sw.interface.writeAll(prose_line) catch return;
+ if (mode != .unterminated) sw.interface.writeAll(finish_line) catch return;
+ sw.interface.flush() catch return;
+ if (mode == .usage) {
+ io.sleep(.fromMilliseconds(100), .awake) catch return;
+ sw.interface.writeAll(usage_line) catch return;
+ sw.interface.flush() catch return;
+ }
+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(10), .awake) catch return;
+ }
+};
+
+test "Chat terminal marker keeps delayed usage and completes silent trailer; nonterminal still stalls" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const saved = http.stream_stall_ms;
+ http.stream_stall_ms = 250;
+ defer http.stream_stall_ms = saved;
+ for ([_]TrailerSrv.Mode{ .usage, .missing, .empty, .unterminated }) |mode| {
+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});
+ defer server.deinit(io);
+ var done: std.atomic.Value(bool) = .init(false);
+ var fut = io.async(TrailerSrv.run, .{ io, &server, mode, &done });
+ defer fut.await(io);
+ defer done.store(true, .release);
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const url = try std.fmt.allocPrint(arena, "http://127.0.0.1:{d}/v1/chat/completions", .{server.socket.address.getPort()});
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var child: Agent = .{
+ .gpa = gpa,
+ .arena = arena,
+ .io = io,
+ .client = &client,
+ .provider = testProvider(url),
+ .messages = std.json.Array.init(arena),
+ .sub = true,
+ .label = "child",
+ .out = null,
+ };
+ const start = nowMs(io);
+ const result = agent_stream.postStreamWithClient(&child, &client, "{}");
+ if (mode == .unterminated) {
+ try std.testing.expectError(error.StreamStalled, result);
+ continue;
+ }
+ const body = try result;
+ defer gpa.free(body);
+ const object = (try child.assembleOpenAI(body)).?;
+ try std.testing.expectEqual(mode == .usage, object.contains("usage"));
+ if (mode == .usage) try std.testing.expectEqual(@as(i64, 20), object.get("usage").?.object.get("prompt_tokens").?.integer);
+ try std.testing.expect(nowMs(io) - start >= 240);
+ try std.testing.expectEqual(@as(u64, 0), child.stall.tripped_ms);
+ }
+}
diff --git a/src/agent_stream_tests.zig b/src/agent_stream_tests.zig
index 3c44591b..961d07ec 100644
--- a/src/agent_stream_tests.zig
+++ b/src/agent_stream_tests.zig
@@ -145,3 +145,14 @@ pub fn openaiCompletion(openai_complete: anytype) !void {
// Escaped content must not false-match a finish_reason field.
try std.testing.expect(!openai_complete("data: {\"choices\":[{\"delta\":{\"content\":\"\\\"finish_reason\\\":\\\"x\"}}]}"));
}
+
+test "Chat finish marker is structurally parsed including whitespace and empty output" {
+ const complete = @import("agent_stream.zig").openaiComplete;
+ try std.testing.expect(complete("data: {\"choices\": [{\"delta\": {}, \"finish_reason\": \"stop\"}]}"));
+ try std.testing.expect(!complete("data: {\"finish_reason\":\"stop\",\"choices\":[]}"));
+ try std.testing.expect(!complete("data: {\"choices\":[{\"delta\":{\"finish_reason\":\"stop\"}}]}"));
+ try std.testing.expect(!complete("data: {\"choices\":[{\"finish_reason\":\"\"}]}"));
+ try std.testing.expect(!complete("data: {\"choices\":[{\"finish_reason\":42}]}"));
+ try std.testing.expect(complete("data: {\"choices\":[{\"delta\":{\"finish_reason\":null},\"finish_reason\":\"stop\"}]}"));
+ try std.testing.expect(!complete("data: {\"choices\":[{\"finish_reason\":\"stop\"}]"));
+}
diff --git a/src/chat_stream_terminal.zig b/src/chat_stream_terminal.zig
new file mode 100644
index 00000000..bec35a95
--- /dev/null
+++ b/src/chat_stream_terminal.zig
@@ -0,0 +1,31 @@
+//! Chat completion recognition shared by HTTP/1 and HTTP/2 SSE readers.
+const std = @import("std");
+
+/// Reject common null-marker delta chunks without allocating a JSON tree.
+fn stringCandidate(payload: []const u8) bool {
+ const key = "\"finish_reason\"";
+ var rest = payload;
+ while (std.mem.indexOf(u8, rest, key)) |at| {
+ rest = rest[at + key.len ..];
+ const suffix = std.mem.trimStart(u8, rest, " \t\r\n");
+ if (suffix.len == 0 or suffix[0] != ':') continue;
+ if (std.mem.startsWith(u8, std.mem.trimStart(u8, suffix[1..], " \t\r\n"), "\"")) return true;
+ }
+ return false;
+}
+
+/// Only a structurally valid first choice marks completion. This does not
+/// stop the reader: separate usage trailers must still have time to arrive.
+pub fn complete(raw_line: []const u8) bool {
+ const payload = @import("agent_interrupt.zig").ssePayload(raw_line) orelse return false;
+ if (!stringCandidate(payload)) return false;
+ const parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, payload, .{}) catch return false;
+ defer parsed.deinit();
+ if (parsed.value != .object) return false;
+ const choices = parsed.value.object.get("choices") orelse return false;
+ if (choices != .array or choices.array.items.len == 0) return false;
+ const choice = choices.array.items[0];
+ if (choice != .object) return false;
+ const reason = choice.object.get("finish_reason") orelse return false;
+ return reason == .string and reason.string.len != 0;
+}
diff --git a/src/pricing.zig b/src/pricing.zig
index b40afb73..d72f0c4d 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -61,6 +61,7 @@ pub const CostTally = struct {
out_tokens: u64 = 0,
api_calls: u64 = 0,
sub_calls: u64 = 0, // subscription-billed (flat-rate; contribute $0)
+ missing_usage_calls: u64 = 0, // completed responses whose usage was absent
unpriced_calls: u64 = 0, // no price_table row
/// `billing` is the caller's already-classified seat (billing.forSeat): a
@@ -87,6 +88,13 @@ pub const CostTally = struct {
}
}
+ pub fn missingUsage(self: *CostTally, io: Io) void {
+ self.mutex.lockUncancelable(io);
+ defer self.mutex.unlock(io);
+ self.api_calls +|= 1;
+ self.missing_usage_calls +|= 1;
+ }
+
/// Consistent copy for rendering (taken under the lock).
pub fn snap(self: *CostTally, io: Io) CostTally {
self.mutex.lockUncancelable(io);
@@ -101,6 +109,7 @@ pub const CostTally = struct {
try w.print("{d} api call(s) · {d} in ({d} cached, {d} cache writes) + {d} out tokens · ${d:.8}", .{
c.api_calls, c.in_tokens +| c.cache_tokens, c.cache_tokens, c.cache_write_tokens, c.out_tokens, c.usd,
});
+ if (c.missing_usage_calls > 0) try w.print(" · totals incomplete: {d} call(s) missing usage (tokens and cost unknown)", .{c.missing_usage_calls});
if (c.sub_calls > 0) try w.print(" · {d} subscription call(s), flat-rate (not in $)", .{c.sub_calls});
if (c.unpriced_calls > 0) try w.print(" · {d} call(s) on unpriced models", .{c.unpriced_calls});
}
@@ -561,3 +570,17 @@ pub fn providerModelInTable(provider_id: []const u8, model: []const u8) bool {
// Seat classification lives in billing.zig. Discovery / price-overlay / default
// catalog tests live in pricing_tests.zig (600-line cap).
+
+test "completed response without usage marks totals incomplete without inventing tokens or cost" {
+ var tally: CostTally = .{};
+ tally.missingUsage(std.testing.io);
+ const snapshot = tally.snap(std.testing.io);
+ try std.testing.expectEqual(@as(u64, 1), snapshot.api_calls);
+ try std.testing.expectEqual(@as(u64, 1), snapshot.missing_usage_calls);
+ try std.testing.expectEqual(@as(u64, 0), snapshot.in_tokens);
+ try std.testing.expectEqual(@as(f64, 0), snapshot.usd);
+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer out.deinit();
+ try snapshot.render(&out.writer);
+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "totals incomplete: 1 call(s) missing usage (tokens and cost unknown)") != null);
+}