Skip to content

Pin the generate.text receipt gap in CI (#395) - #401

Merged
abogartz merged 2 commits into
mainfrom
395-receipt-characterization
Nov 12, 2026
Merged

abogartz merged 2 commits into
mainfrom
395-receipt-characterization

Conversation

@abogartz

@abogartz abogartz commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Part of #386. Addresses #395 — does not close: AC 1 needs upstream (route 1) or a deliberate route-2 decision.

What this is

#395's premise (generate.text returns no usage) was probed by hand on 2026-11-11. Hand probes rot; this makes the limitation machine-checked in CI.

The fake model attaches usage: { prompt_tokens: 111, completion_tokens: 22, total_tokens: 133 } to every final chunk — the shape a real openai-compatible provider sends. A standalone probe plugin records, inside a real host process on the same session.context seam the plugin injects through, what ctx.generate.text actually resolves to.

Result, pinned by e2e/generate-receipt.test.ts:

observed in the plugin process value
Object.keys(ctx.generate) ["text"]
result keys ["text"]
result.usage null — with the provider's numbers on the wire

The gap is the host's contract, not the provider's silence.

The premise is checked from both ends

A test that reads only the plugin's own file cannot tell "the host dropped the receipt" from "the provider stopped sending one": deleting the fake model's usage block left the first version green. The fake model now records the final chunk it actually wrote (served.jsonl, exposed at GET /__served), and the test requires all of:

  1. the probe's own ctx.generate.text call appears in the fake model's request log;
  2. the final chunk served back to that call carries prompt_tokens: 111 / completion_tokens: 22 / total_tokens: 133 and finish_reason: "stop";
  3. the plugin still sees { text } with usage: null.

Delete the usage block and the test goes red with a message naming finalChunk().

When this test flips

Three assertions, three expectation messages, checked flip-first so a red always names the right contract:

red on what it means
usage #395 flip trigger — upstream surfaced usage. Flip this test and name the source capture_cost reads, once #394 lands
resultKeys the result gained a member: if it is usage, that is the flip above; anything else is a new member to add to the list
generateKeys ctx.generate gained a member — that alone is not the usage flip

The instruction rides on the expectation, not on a comment, so it survives someone editing the prose.

AC status, stated before review

# criterion status
1 provider-reported counts inside the plugin process not met — route 1 (upstream ask) is outside this repo; route 2 not implemented, see below
2 capture_cost switches to a named source, both kinds distinguishable blocked on 1; the distinguishability half ships with PR #394 (open)
3 transport re-verified after the change not applicable yet — nothing capture writes has changed
4 estimate path kept, never a zero met by PR #394 (open), not by anything on main — capture_cost does not exist on this branch. This PR touches no production path
5 bench billedFrom agrees within 2% blocked on 1

Route 2: declined for cost, not blocked

An earlier version of this body said the original hand probe found session.prompt blocked within the probe window. That no longer reproduces. Re-probed 2026-11-12 in an isolated guest against both hosts, with a 20 s hard timeout on every await:

host session.create → session.prompt → session.wait
opencode v2.2.5 (local) 37–80 ms over 4 runs
opencode v2.0.26 (the CI pin) 39–62 ms over 4 runs

The route-2 session's assistant message carries the provider's numbers in the guest db — {"input":111,"output":22,"reasoning":0,"cache":{"read":0,"write":0}} — so those numbers are reachable that way today, on both hosts.

Route 2 is still declined, for the reason that survives the measurement: capture stops being a fire-and-forget text call and becomes a session — an agent, a system prompt, the full tool list on the wire (26 tools offered, against the bare generate call's none), and a lifecycle. That changes what capture writes, and AC 3 is the benchmark of exactly that output. Taking route 2 is a decision for a quiet seat with the transport arm ready, not a drive-by on a degraded one (F19).

Verification

  • Host matrix: the new test passes on the local host (opencode v2.2.5) and on the CI pin, installed hermetically as @opencode/[email protected] and selected with OPENCODE_BIN.
  • Mutation checks: remove the fake model's usage block → FAIL; inject a usage into the probe's result → FAIL with the flip-trigger message; add an unrelated ctx.generate member → FAIL with the "not the flip" message; restore → PASS.
  • Full e2e: 31 pass / 0 fail, run twice.
  • Gate: typecheck exit 0; lint 542 warnings, the same as main (the three noExplicitAny the first version added are gone — the probe now types its context structurally in its own file); unit 1190 pass / 19 skip / 0 fail; e2e 31 pass / 0 fail.
  • Temp dirs: a full e2e pass leaves no psi-e2e-* guest and no psi-e2e-fake-* behind — this test removes its guests in afterAll, and startFake().stop() now reaps its own directory. The psi-e2e-pack-* directory installPacked() creates is a separate pre-existing leak, left alone here.

…reports usage

Part of #386, addresses #395 (does not close: AC 1 needs upstream or route 2).

#395's premise was probed by hand on 2026-11-11 and hand probes rot. This makes
the limitation machine-checked: the fake model now attaches
`usage: {prompt_tokens: 111, completion_tokens: 22, total_tokens: 133}` to every
final chunk -- the shape a real openai-compatible provider sends -- and a
standalone probe plugin records, inside a real host process on the
session.context seam, what `ctx.generate.text` actually resolves to.

Result, pinned by e2e/generate-receipt.test.ts: `ctx.generate` exposes exactly
["text"], the result carries exactly ["text"], and `usage` is null -- with the
provider's numbers on the wire. The gap is the host's contract, not the
provider's silence. When upstream surfaces usage (route 1), resultKeys grows,
this test fails, and the failure is the trigger to flip it and switch
capture_cost from receipt=none to a named source.

Route 2 (session.create + prompt + wait) is NOT implemented, deliberately: it
turns capture from a fire-and-forget text call into a session with an agent and
a lifecycle -- a behaviour change to the one component the transport benchmark
measures -- and the original probe found session.prompt blocked within the
probe window. AC 3 exists precisely because that route could change what capture
writes; taking it is a decision for a quiet seat with the transport arm ready,
not a drive-by.

AC 4 (keep the estimate path) is already met by PR #394: no receipt degrades to
the labelled chars/4 estimate, never a zero, and this change touches no
production path.

- e2e/support/fake-model.ts: usage on the final chunk
- e2e/support/probe-plugin/: standalone { id, setup } plugin, session.context
  hook, model shape { providerID, id } (the host rejects modelID -- the error
  named the key, so the probe doubles as the shape documentation)
- e2e/support/harness.ts: makeGuest takes extraPlugins
- e2e/generate-receipt.test.ts: the characterization

Co-authored-by: OpenCode <[email protected]>
@abogartz

Copy link
Copy Markdown
Owner Author

Adversarial review — APPROVE_WITH_NITS

Reviewed head 952cbcc3a66db8559e99c38933860d81ad7f1f90 against merge-base f8f42fd. Findings come from running code, not from reading the diff.

The core characterization is true and proven end-to-end: the host parses provider usage into message tokens, then the generate.text endpoint schema ({data:{text}}) drops it before any plugin sees it. The test is mutation-reactive, green on both host versions I could exercise, and breaks nothing. Three P2s are body/premise defects rather than runtime defects.

Seam proof

The probe and the real plugin run in one host process (both logged the same pid). ctx.generate objects are per-plugin wrapper instances, not the same object — cross-markers set by each side were invisible to the other (realMarker: null, realGenSame: false). That is the host's per-plugin adapter (generate: { text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text) }).

Decisive step: the real plugin's own ctx.generate.text({model:{providerID:"fake",id:"scripted"},prompt:"probe receipt"}) from a temporary hook on the same seam returned {"resultKeys":["text"],"usage":null,"text":"SMOKE-AUX"} — identical to the probe. Both wrappers delegate to the same endpoint, and the plugin's capture path (src/capture/runtime.ts:258,484) uses the same ctx.generate from setup with the same input shape. Claim 2 holds; do not let anyone phrase it as object identity.

Wire proof

Raw SSE from the fake model:

data: {"id":"chatcmpl-fake",...,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":111,"completion_tokens":22,"total_tokens":133}}

The host itself sends "stream_options":{"include_usage":true} on every request, so a strict OpenAI-compatible provider answers exactly this shape. The probe's own call reached the fake model (request log: {"msgs":1,"last":"probe receipt","stream":true}). The host parses the usage — the guest db session_message shows {"input":111,"output":22,"reasoning":0,"cache":{"read":0,"write":0}}. It disappears at the host's endpoint contract: the v2.2.5 binary embeds success:i({data:i({text:t})}).annotate({identifier:"GenerateTextResponse"}), with no usage slot. Claim 4 is proven: host contract, not provider silence.


P2 — The test cannot detect loss of its own premise

e2e/generate-receipt.test.ts:53-66. Delete the usage block from e2e/support/fake-model.ts:122-126 and the test still passes:

$ # usage block removed
$ bun test ./e2e/generate-receipt.test.ts
 1 pass  0 fail

Nothing asserts that the provider actually reported usage. The distinction this PR exists to pin — "the host's contract, not the provider's silence" — becomes unprotected the moment the fake model drifts.

Fix: after the turn, assert the probe's generate call reached the fake model, for example

expect((await fake.requests()).some((r) => String(r.messages?.at(-1)?.content) === "probe receipt")).toBe(true);

Response bytes are deterministic from that request, as shown above.

P2 — "AC 4 already met by #394" is false against any merged tree

e2e/generate-receipt.test.ts:4 and the body's AC table. #394 is open, and c046297 (which adds capture_cost / receipt=none) is not an ancestor of this branch or of origin/main:

$ git merge-base --is-ancestor c046297 HEAD && echo yes || echo no
no
$ grep -rn "capture_cost" src/
(empty)

The flip instruction "switch capture_cost from receipt=none to a named source" points at code a future author will not find on main. Fix: say "PR #394 (open)" and make the flip step conditional on #394 merging.

P2 — The "route 2 deliberately not taken" premise is stale on both hosts

The body says the original hand probe found session.prompt blocked within the probe window. A bounded probe (scratch, session.context hook, hard internal timeouts) resolves the full route on both hosts: session.create → session.prompt → session.wait in 28 ms (v2.2.5) and 43 ms (v2.0.26). The route-2 session's assistant message carries the provider's numbers in the guest db: {"input":111,"output":22,"reasoning":0,"cache":{"read":0,"write":0}}.

Declining route 2 for behaviour-change and AC 3 reasons remains sound judgment. Citing a block that no longer reproduces is not. Fix: correct the body and #395's findings.

NITs

  1. Guest temp dir leaks (e2e/generate-receipt.test.ts:33,42-43). guests.push(g) with no cleanup; the repo pattern is rmSync(g.root, ...) (e2e/characterization.test.ts:46, load.test.ts:39). ${TMPDIR} already holds 211 psi-e2e-* guest dirs and 1332 psi-e2e-fake-* — the fake-dir leak pre-exists in harness.ts:73. Fix: afterAll(() => { for (const g of guests) rmSync(g.root, { recursive: true, force: true }); });
  2. Lint warnings +3 (head 545 vs base 542, both exit 0). All three are lint/suspicious/noExplicitAny at e2e/support/probe-plugin/index.ts:13,29,30. The new test file itself is clean.
  3. The flip trigger leans on comments. The resultKeys failure prints a bare toEqual diff (+ "usage"); bun echoes the five preceding source lines, which include the Give capture a provider receipt: generate.text returns no usage #395 comment, so the guidance is visible today. A custom message (expect(probe.resultKeys, "#395: upstream surfaced usage — flip this test and name the source")) would survive comment edits.
  4. generateKeys conflates two contracts. If upstream adds image or decisions to plugin ctx.generate, this test goes RED on generateKeys — a false trigger for the usage flip. The failing-assertion diff disambiguates, so it is acceptable.

Residual

CI e2e runs @opencode/[email protected] (.github/workflows/ci.yml, smoke job OPENCODE_VERSION: 2.0.26). Verification here used darwin-arm64 binaries of 2.0.26 and 2.2.5. The same-version linux binary was not run locally; the suite is CI-proven on main.


Efficacy table

Mutation Test failed? Message actionable?
Probe result gains usage (simulated upstream fix) RED at generate-receipt.test.ts:63, diff + "usage" yes, via the printed comments; no custom message (NIT 3)
usage removed from the fake model PASS n/a — premise unprotected (P2 above)
Hook never fires / probe file missing fails existsSync (structural, path verified) —
generate.text throws fails on probe.error (structural, error path written) —

Version matrix

Host New test Full e2e
v2.2.5 (local, darwin-arm64) pass 31/31, twice
v2.0.26 (CI pin, darwin-arm64 via OPENCODE_BIN) pass 31/31
v2.0.26 linux-x64 (CI's actual binary) not exercised —

The characterization is version-stable across both testable hosts: no red CI, no silent mis-pin.

Measured numbers

Check head 952cbcc base f8f42fd
e2e (bun test ./e2e/ --parallel=4) 31 pass / 0 fail, 15.13 s; repeat 13.80 s, no flake 30 pass / 0 fail, 15.93 s
unit (bun test ./test/ --parallel=4) 1209 ran (1190 pass, 19 skip) identical
typecheck exit 0 —
lint exit 0, 545 warnings exit 0, 542 warnings
on origin/main ce36c65 git apply --check OK; e2e 31/31; typecheck 0; lint exit 0 (548 warnings) —

Hygiene: guests are fully hermetic (HOME, all XDG_*, OPENCODE_MEMORY_DIR redirected); no e2e leakage into the real store; no orphan processes; the packed tarball contains 0 e2e or probe entries; the probe package has no dependencies and no workspaces key, so a frozen-lockfile install is unaffected.

The characterization test read only the probe plugin's own file, so deleting
the fake model's `usage` block left it green: it could not tell the host's
contract apart from a provider that had stopped reporting. The fake now
records the final chunk it actually wrote (served.jsonl, exposed at
/__served), and the test requires both that the probe's generate call reached
the model and that the chunk served back to it carried prompt_tokens 111 /
completion_tokens 22.

Also from the review:

- #394 is OPEN and `capture_cost` is not on any merged tree. The header and
  the flip instruction now say "PR #394 (open)" instead of sending a future
  author to a symbol that is not on main.
- Route 2 is not blocked. Re-probed with a 20 s timeout on every await, it
  resolves in 37-80 ms on v2.2.5 and 39-62 ms on the CI pin v2.0.26, and the
  route-2 session's assistant message carries the provider's numbers in the
  guest db. The comment now gives the real reason to decline it: it changes
  what capture writes, which is exactly what AC 3 measures.
- Guests this test creates are removed in afterAll, and startFake() reaps its
  own temp dir in stop(), so a full e2e pass leaves no psi-e2e-fake-* behind.
- Each contract gets its own expectation message, so an unrelated new
  ctx.generate member cannot be read as the usage flip.
- The probe plugin types its context structurally in its own file, which
  returns the branch to main's 542 lint warnings.
@abogartz

Copy link
Copy Markdown
Owner Author

Review fixes — 240e887

All six findings addressed. No production path touched; this stays a characterization PR.

What changed

F1 — the test can now detect loss of its own premise. e2e/support/fake-model.ts factors the closing SSE chunk into finalChunk() and appends the object it actually wrote to served.jsonl, exposed as GET /__served (truncated by /__reset, surfaced through fake.served() in the harness). The test asserts that the probe's own prompt ("probe receipt", a constant shared with the probe plugin) appears in the request log, and that the final chunk served back to that request carries prompt_tokens: 111 / completion_tokens: 22 / total_tokens: 133 with finish_reason: "stop".

F2 — the #394 references. The test header and the AC table now say "PR #394 (open)" and state plainly that capture_cost exists on neither this branch nor main. The flip instruction is conditional on #394 landing.

F3 — route 2. Re-probed in scratch with a 20 s hard timeout on every await. The route is not blocked; measurements below. The test comment and the body now give the reason that survives the measurement — route 2 changes what capture writes, which is what AC 3 measures — and they state the latency and that the numbers are reachable that way. The probe itself is not committed.

F4 — temp dirs. The test removes its guests in afterAll. startFake().stop() now also rmSyncs its own directory: that is the one-line fix at the old harness.ts:73, and it is safe because no e2e file reads fake.dir after stop() (none references it at all).

F5 — the three noExplicitAny. The probe plugin declares a local structural ProbeContext / GenerateResult instead of any. Local on purpose: importing the SDK's or src/core/host.ts's context type would let a declared shape hide the runtime shape the probe exists to observe.

F6 — the flip trigger no longer leans on printed comments. Each contract carries its own expectation message, and the usage check runs first, so a usage flip always reports as the flip even when ctx.generate gained a member at the same time.

Mutation table (each row observed, not inferred)

mutation observed result
pre-fix tree (HEAD~1) with usage removed 1 pass 0 fail, 7 expect() calls — the finding, reproduced on this machine
none (restored) 1 pass 0 fail, 11 expect() calls
remove usage from finalChunk() FAIL — the fake model no longer attaches usage to the final chunk (see finalChunk() in ./support/fake-model.ts) — restore it, or this test is pinning provider silence rather than the host's contract; diff - prompt_tokens 111 / completion_tokens 22 / total_tokens 133, + undefined
probe returns a usage on the result FAIL — #395 FLIP TRIGGER: upstream surfaced usage on the generate result — flip this test and name the source capture_cost reads (once #394 lands); Received: { prompt_tokens: 111, completion_tokens: 22, total_tokens: 133 }
ctx.generate gains an unrelated member (json) FAIL on generateKeys only — ctx.generate gained a member; that alone is NOT the #395 usage flip — read the usage assertion before changing this test; usage and resultKeys stayed green

The first row is the finding itself: before this commit the test could not see the provider stop reporting.

Host matrix

host how selected result
opencode v2.2.5 opencode on PATH 1 pass / 0 fail
opencode v2.0.26 (CI pin) @opencode/[email protected] from npm into scratch, OPENCODE_BIN=... 1 pass / 0 fail

Route-2 measurements (scratch probe, not committed)

host create → prompt → wait total, 4 runs
v2.2.5 37, 39, 43, 80 ms
v2.0.26 39, 40, 44, 62 ms

The route-2 session's assistant message in the guest db carried {"input":111,"output":22,"reasoning":0,"cache":{"read":0,"write":0}}. One note for whoever does take route 2: the session's own totals read 222/44, because the host also charges the session's title request — the per-message tokens are the number to read, not session_v2.

Gate

  • typecheck: exit 0.
  • lint + format: 542 warnings / 147 infos, format clean. Measured on this machine: origin/main = 542, pr-401 before this commit = 545, after = 542. (The review brief quoted main at 545; the measured count on main's tree is 542.)
  • unit: 1190 pass / 19 skip / 0 fail (1209 tests, 111 files).
  • e2e: 31 pass / 0 fail, run twice at head (26.5 s and 25.2 s), and again green under the gate at 31 pass / 0 fail.
  • bun run gate: all green. The pre-push hook ran the same gate before the push and it was green.
  • temp dirs: with a marker file to date the survivors, a full e2e pass now leaves zero psi-e2e-fake-* and zero psi-e2e-* guests newer than the marker.

Not fixed, and why

  • installPacked() leaks one psi-e2e-pack-* directory per packed-load scenario (e2e/support/harness.ts). Pre-existing, unrelated to this test, and a fix means deciding whether the packed install should be cached across scenarios. Left as a follow-up; it is the only directory a full e2e pass now leaves behind.
  • The psi-e2e-fake-* and psi-e2e-* directories already sitting in $TMPDIR are not deleted by this PR. It stops new ones; sweeping history is a separate call.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving.

The characterization now proves its own premise: the test asserts the probe's call reached the fake model and that the chunk the fake served carried the provider's usage, so removing that field turns the test red instead of silently passing. The host-contract conclusion holds on both the local host and the CI-pinned version, and the route-2 rationale is corrected to the real one.

Full gate green, CI green. Not merged — the merge is left to a human.

@abogartz
abogartz merged commit 58945fc into main Nov 12, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.24.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@abogartz
abogartz deleted the 395-receipt-characterization branch November 19, 2026 05:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant