Commit Graph
5 Commits
Author SHA1 Message Date
yetone ef75a9a2b5 plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.

Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)

Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
  stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".

Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
2026-10-19 09:40:45 +08:00
yetone e3c09f4f36 plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.

infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.

Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
  wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
  87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
  fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.

Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).

Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
2026-10-19 09:40:45 +08:00
forever c162a98a11 plugin tests: TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy stop node at the run's deadline, catch ready-wait and held-window leaks by name, and fail a case that never finishes (#1120)
* plugin tests: TestHostJSCancellation's ready-wait counts every listener on its fake stdin and stdout, so a cancelled bootstrap wait that leaves one there fails by name

ready-wait counted stdout's drain listeners only. A listener that a
cancelled wait left for any other event, on stdout or on stdin's
readline, went through every cycle. A fetch that adds a stdout 'close'
listener and removes it only once it starts (a request cancelled while
it waits for init never starts) passed with nothing but a
MaxListenersExceededWarning, which the Go test only logs. A stdin 'line'
listener per fetch was caught at 30,000 cycles only by the 10s
deadline, since every line walks every listener; at 1,000 (d9b2cdc5) it
passes in 0.6s.

The case now records every event's listener count on both once stdout
is blocked, and checks the counts are the same after the cancelled
waits. Today they are { stdin: { line: 1, close: 1 }, stdout: { drain:
1, error: 1, close: 1 } }. host.js is unchanged.

Verified by putting such a listener into host.js and running ready-wait
on Node 22.22.2 and 24.21.0 (CI's) and 26.8.1. Each passed before and
now fails 'cancelled bootstrap waits leave no listener on stdin or
stdout', with the count that grew (line: 1001, expected 1):
- a stdin 'line' listener per fetch, which 30,000 cycles caught only by
  the deadline
- a stdout 'close' listener per fetch: holding the request, holding 16
  KiB to 256 KiB more (160 KiB ran 30,000 cycles out of heap), holding
  nothing, or one shared function added again each time
- a stdin 'error' listener per fetch, or a listener on a symbol event
Unchanged host.js passes, and every leak main's case fails still fails
on the same assertion.

* plugin tests: TestHostJSCancellation's ready-wait forces a garbage collection after its cancelled waits and fails when anything still holds one of their requests

ready-wait counts what the cancelled waits share by name: waiters,
reactions on ready, queued lines, listeners on stdin and stdout. A wait
that left its request held by anything else passed every count. A
listener left on an AbortSignal every fetch shares was caught at 30,000
cycles only by the 10s deadline, since Node's EventTarget walks its
listeners on every add; at 1,000 (d9b2cdc5) it passes in 0.2s. A
reaction on a promise derived from ready rather than on ready itself, a
chain of closures in place of readyWaiters, or a list of the waiting
fetches, their controllers or their credit gates that the cancel path
never prunes passed at 30,000 too.

host.js says a cancelled wait lets "its controller, gate and body go".
The case now takes a WeakRef to each request, its controller, its
signal and its credit gate as its fetch is read. After the cycles it
forces a full collection (node runs with --expose-gc) and checks that
none of them is still alive. Waiters are counted before the collection,
so a FinalizationRegistry that tidies them up afterwards can't hide
them. A fetch that has no record in flight while it waits fails by name
rather than throwing from WeakRef. host.js is unchanged.

node also runs with --no-concurrent-recompilation, so V8 optimizes on
the main thread. On Node 23 and later it optimizes host.js's
per-request closures on a worker thread from about the 500th cycle,
and a compile job holds its function, and through it the request it
was made for, until a worker has freed the job. A job still held at
the collection makes unchanged host.js fail with retainedRequests 1.
V8 flags that delay Turbofan's queue hold one there and fail it that
way on all six local versions, 22.14.0 to 26.8.1; one worker with a
delay per compile does on 23.9.0 and later. With
--no-concurrent-recompilation each of those runs passes, and the case
takes about the same CPU time (0.2 to 0.3s).

Verified by putting such a leak into host.js and running ready-wait on
Node 22.22.2 and 24.21.0 (CI's) and 26.8.1. Each passed before and now
fails 'cancelled requests are garbage collected' with retainedRequests
1000:
- a listener on a shared AbortSignal: one aborted when stdin closes,
  linked directly or through an abortOn helper, or one per init (4
  variants)
- a reaction on a ready.then(...) every fetch shares, or a chain of
  closures in place of readyWaiters (7 variants)
- an unpruned list of the waiting fetches (2 variants), of their
  controllers or of their credit gates
Keeping each wait's abort by fetch id fails with retainedRequests 1,
since the case reuses id 1.

Unchanged host.js passes 100 of 100 runs on each of Node 22.14.0,
22.22.2, 23.9.0, 24.19.0, 24.21.0 and 26.8.1, and 25 of 25 under each of
13 V8 flag sets (--stress-compaction, --always-sparkplug, --jitless,
--single-threaded-gc, --stress-incremental-marking, --gc-interval=1000,
--minor-ms, --stress-scavenge=100, --predictable, --max-lazy,
--max-semi-space-size=1 and --conservative-stack-scanning on 26.8.1;
--always-turbofan on 23.9.0). Under each of those, each of 11 retaining
variants fails 3 of 3 runs.

* plugin tests: TestHostJSCancellation's ready-wait looks for late errors a turn after its forced collection, so an error sent when a cancelled request is collected fails on CI's Node too

ready-wait checks after every cycle that a cancelled request gets no
late error. One sent from a FinalizationRegistry callback once the
request is collected reaches that check only if node collects garbage
during the cycles. At 30,000 cycles it always did. At 1,000 (d9b2cdc5)
Node 26.8.1 still does, and Node 22 to 24 don't: such an error passes
on 22.14.0, 22.22.2, 23.9.0, 24.19.0 and 24.21.0, and CI's
ubuntu-latest runs 22 and macos-latest 24.

The case now waits a turn after the collection it forces, when such
callbacks have run, and checks again that nothing was queued. host.js
is unchanged.

Verified with a host.js whose FinalizationRegistry sends an error for
each collected request that never answered. It passed on those five
versions and now fails 'collected requests emit no late error' on each.
On 26.8.1 it still fails the check after each cycle, as on main. With
--max-semi-space-size=128 --min-semi-space-size=128, under which the
forced collection is the only one in the run, it fails 'collected
requests emit no late error' on 22.22.2, 24.21.0 and 26.8.1. Unchanged
host.js passes.

* plugin tests: TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy stop node at 90% of the run's deadline, not at a fixed 10s a starved machine can spend starting it

Each case runs in its own `node -e` under a fixed 10s context. d9b2cdc5
took ready-wait from 30,000 rounds to 1,000, and that fixed the reported
failure: beside 16 `yes > /dev/null` loops (load 50-113), 30,000 rounds
were killed at 10.01s in 4 of 4 runs, and 1,000 rounds passed 4 of 4
(ready-wait 0.76-2.74s). Per round the work is ~100µs and flat with the
round count.

What is left is the fixed 10s itself, and it is the same for every case.
Under `taskpolicy -c background` beside 16 busy loops (load ~114), main
had 10 of the 11 TestHostJSCancellation cases killed, the one-step
stopped-gate among them. Under background QoS alone, main passed, but
stopped-gate, split-chunk and blocked-head took 5.7-7.6s, most of it
starting node. ready-wait took 2.6s there.

So both tests now run node through runHostJSCase, which stops it at 90%
of t.Deadline()'s remaining time, as e13f1513 did for
TestConcurrentRedactedCountTokens' children. A case that really hangs
still fails before the run's own deadline with "signal: killed". With
no deadline (-timeout 0), node is not stopped, the same as the test
itself.

Verified with a node stand-in on PATH that sleeps 12s before starting
node: on main, stopped-gate, ready-wait and mid-setup are killed at
10s and fail; with this change all three pass. With a stand-in that
never returns and -test.timeout 30s, the case fails at 27.00s with
"signal: killed", and no process is left behind.
go vet ./...; go build (darwin), GOOS=linux go build -tags nogui,
GOOS=windows go build; gofmt -l; -race -count=20 of both tests (ok,
43s); go test -tags nogui ./... all ok (load 34-96).
No production code changed.

* plugin tests: a host.js case that hangs is stopped after two minutes at most, not at 90% of what's left of a 10m -timeout or never under -timeout 0

runHostJSCase took 9/10 of the time left before t.Deadline(), so under
the default -timeout 10m a case that really hangs held the run for about
nine minutes before it failed, and under -timeout 0 (no deadline) it was
never stopped. The limit is now two minutes, or 9/10 of what's left if
that is sooner: still far above the node start-up a loaded machine needs.

Tested: TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy
pass with the default -timeout and -count=3 -timeout 0; go vet, gofmt.
With the limit set to 1ms in a scratch edit, TestHostJSCancellation's
cases fail with "signal: killed", so the limit applies without a
deadline too.

* plugin tests: TestHostJSCancellation checks that a cancel ends a fetch holding at its credit window

A fetch whose reader has credited nothing back spends its window and waits
in makeGate's take for credit. A cancel ends that wait through
transitionFetch → gate.stop(), which wakes the waiting take with -1, so the
body loop leaves and the fetch's finally frees its record. No case reached
that wait. stopped-gate stops a gate with no take waiting, and split-chunk's
and normal-reply's bodies fit inside the 512 KiB window. So a stop() that
dropped the waiting take without waking it passed every case, while each
cancelled fetch held at its window stayed in inflight for good.

The new held-window case streams a 1 MiB body with no credit returned. It
waits until the chunks sent, plus FRAME_OVERHEAD for each, add up to the
whole window (8 frames). It checks that no further frame goes and that the
fetch is still in flight, then aborts it and needs the host idle with no
result or error owed for it.

Fails without the fix it guards: in a copy of host.js, makeGate's stop() is
changed to `if (wake) { wake = null }` (the waiting take is dropped, never
woken). held-window then fails with "cancel wakes a fetch waiting for
credit". Every other case, and TestHostJSCancellation on main without the
new case, passes on that mutation. A take that ignores the window
(fit = want) fails it too, with "fetch spends its whole window". The case
waits through until(), so it doesn't rely on node noticing a promise that
never settles.

Every case passes on host.js unchanged. -race -count=20 of
TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy passes. go
test -tags nogui ./..., go vet ./..., gofmt -l, and the darwin, linux (nogui)
and windows builds pass. No production code changed.

* plugin tests: a hostJSCancellationTest case that never reaches the end of main() fails, rather than passing when node runs out of work and exits 0

TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy run
`node -e hostJSCancellationTest <case>` with host.js on stdin and pass
when node exits 0. The fixture ended with main().catch(...), and node
exits 0 once nothing is left to run, even while main() still awaits a
promise that never settles, so a case could pass without reaching its
assertions. Waits through until() are bounded by 30 setImmediate ticks
and fail; a raw await of host code is not. stopped-gate has two,
`await run('gate.take(64)')` on an open gate and then on a stopped one.
With makeGate's `if (stopped) return Promise.resolve(-1)` changed to
`if (stopped) return new Promise(() => {})`, a stopped gate's take never
answers, and stopped-gate passed.

The fixture now marks main() finished when it resolves. An exit listener
sets exitCode 1 when node would otherwise exit 0 before that, and names
the case. A case that throws still prints only its error and exits 1.

With that broken gate, the old fixture passes every case, and the new
one fails stopped-gate:

    --- FAIL: TestHostJSCancellation/stopped-gate (0.21s)
        host_flow_test.go:35: JavaScript cancellation regression: exit status 1
            stopped-gate never finished: main() was still awaiting a promise that never settled when node ran out of work

and passes the other ten cases and mid-setup. With an open gate's take
broken the same way (`if (n > 0) return new Promise(() => {})`), the old
fixture passes stopped-gate too, and the new one fails it with the same
line (split-chunk and normal-reply fail under both, through until()).
On the real host.js every case passes. node v23.9.0, v24.19.0, v24.21.0,
v26.8.1 and v26.10.0 give the same results. CI's ubuntu runner has Node
22.23.3, not run here; its src/api/hooks.cc reads the exit code again
after emitting 'exit', which the listener relies on.

go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows
go build and go test -tags nogui ./... pass under a temp HOME with Go's
caches pinned, and go test -race -count=20 of both tests passes. No
production code changed.
2026-10-13 09:06:42 +08:00
yetone d9b2cdc593 plugin tests: TestHostJSCancellation's ready-wait cancels 1,000 bootstrap waits rather than 30,000, so it finishes inside its 10 s under a full suite's load
ready-wait failed twice on 10-07 in full `go test -tags nogui ./...` runs on
main ("signal: killed" at 10.00s) and passed alone. The cause is the test's
size, not the host's cancellation. The case runs 30,000 fetch+abort rounds,
each waiting at least one setImmediate turn. That takes ~4s alone, 4.4-8.5s
beside a full go test ./... plus CPU and fresh-script load loops, and more
than 10s when starved (taskpolicy -c background with every core busy: killed
3 of 3). The cost per round stays flat from 5,000 to 120,000 rounds (no growth,
so no leak), and the counts at the end are exact: retainedWaiters 0, one
reaction on the shared ready promise, one drain listener.

Those counts are what catches a leak, and they catch it at any size. With
1,000 rounds, leaving the waiter in readyWaiters fails with retainedWaiters
1000, and a reaction per request on the shared ready promise fails with
retainedReadyReactions 1000.

Before: starved, 3 of 3 runs killed at 10.04-10.26s; -race -count=20 79.9s.
After: starved, 5 of 5 pass (ready-wait 0.6-5.6s, mostly node startup);
-race -count=20 9.9s.
No production code changed.
2026-10-07 04:37:31 +08:00
Snowyy c38728145b plugin: a slow reader pauses its stream instead of racing a watchdog (#812)
* plugin: a slow reader pauses its stream instead of racing a watchdog

#664 gave a plugin reply a soft watermark (softQueuedBytes 4 MiB, softQueuedEvents 4096) and a 10-second idle watchdog: past the watermark, a reader that made no progress for stallIdle had its call failed with errStalledReader, and hardQueuedBytes/hardQueuedEvents (64 MiB / 65536) cut the reply outright. Both are guesses at how long a reader may take, and both end a reply that reader was still consuming.

The host now hands each fetch a credit window instead. Go grants streamWindow (512 KiB) up front and returns credit as the reader takes bytes, so the child stops producing at the window instead of being timed out; the window is charged per delivered byte plus frameOverhead (2048), so a run of tiny frames cannot fill it with metadata. streamBudget (64 MiB) and maxFrame (64 KiB) bound a whole reply and a single frame, and a child that sends past its window is a protocol violation (errProtocolOverrun) rather than a slow reader.

The plugin side grew the matching gate (makeGate, gate.take/spend/add, waitDrain): a fetch holds at the window until Go credits it, and its pending writes are cancellable. Cancellation and shutdown now have one owner per call - a five-state lifecycle (sending, active, draining, aborting, released) whose single transition helper disposes the queue, detaches the watcher, commits the terminal answer, creates the abort and returns capacity exactly once - so a host failure, a Close, a cancelled context and an already-delivered reply can no longer race each other over who cleans up. A reply the host already delivered keeps its bytes and its vendor outcome when the host dies.

Tests: the JS cancellation cases run the production sections with controlled stdout backpressure (stopped gate, split chunk, terminal suppression, acquired-body cancel, 30,000 cancelled bootstrap waits with no retained waiter or ready reaction); the Go cases drive lifecycle orderings directly (terminal-before-failure, failure-before-terminal, abort acknowledged before capacity returns, blocked enqueue), and the shutdown, body-close and mid-setup-cancel cases block on explicit channels instead of sleeping. TestFlowBigReplyProd reads 100 MiB non-SSE and SSE through the real host and checks lengths and SHA-256, including a 12 s reader pause. CI installs Bun 1.4.2 on Linux and runs that case in its own step, since the plugin sandbox skips when bun is not on PATH.

* plugin: the stream-head credit test waits for the credits before the reply ends (CI, macos-latest: TestHostStreamHeadChunksFinal failed on the macOS runner with "the credits were given back didn't happen", while the same package passed on ubuntu-latest and locally) — the test sent the child's final answer together with its 50 chunks, so the call could be marked stopped and its pending credits dropped before waitFor saw them; a completed fetch needs no credit, so waiting longer could not recover them and the expectation was a race, not a real accounting bug. The final answer is now withheld until io.ReadFull has taken the 140 payload bytes in order and exactly 140 + 49*frameOverhead credits have been observed with frameOverhead still owed, and only then does the child answer and the test assert a zero-byte EOF read. No production code changed.

Tests: go test -run '^TestHostStreamHeadChunksFinal$' -count=500 ./internal/plugin/ and -count=200 -race pass; go test -count=1 and -race -count=1 ./internal/plugin/... pass; gofmt -l and git diff --check clean.
2026-10-05 01:36:20 +08:00