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.
This commit is contained in:
Snowyy
2026-10-05 01:36:20 +08:00
committed by GitHub
parent eb0e5e1d00
commit c38728145b
6 changed files with 2906 additions and 857 deletions
+14
View File
@@ -43,10 +43,24 @@ jobs:
- name: Vet
run: go vet -tags "${{ steps.tags.outputs.tags }}" ./...
- uses: oven-sh/setup-bun@v2
if: runner.os == 'Linux'
with:
bun-version: 1.4.2
- name: Test
if: runner.os != 'Windows'
run: go test -tags "${{ steps.tags.outputs.tags }}" ./...
- name: Production plugin flow
if: runner.os == 'Linux'
timeout-minutes: 10
env:
MAGPIE_FLOW_BIG: '1'
run: |
bun --version
go test -timeout 10m -tags "${{ steps.tags.outputs.tags }}" ./internal/plugin/... -run '^TestFlowBigReplyProd$' -count=1
# The redaction tests reuse this binary in fresh processes to check
# first-use races, so it must include the race detector.
- name: Race
+728 -256
View File
File diff suppressed because it is too large Load Diff
+298 -18
View File
@@ -4,7 +4,12 @@
// magpie → host: {id, method, params}; the host answers {id, result} or
// {id, error}. A fetch streams its reply first: {id, event: "head", status,
// headers}, then {id, event: "chunk", data} (base64) as the body comes, then
// {id, result: null}. {method: "abort", params: {id}} cancels one.
// {id, result: null}. {method: "abort", params: {id}} cancels one, and
// {method: "credit", params: {id, n}} gives a fetch back the n charged bytes
// its reader took (the payload it read, and a frame's overhead once the frame
// is done), so it may send that much more. A fetch starts with the window
// magpie gave it and sends no more than that ahead of its reader, so a slow
// reader pauses its upstream instead of the host buffering without bound.
// host → magpie, unasked: {event: "log", level, message} and {event:
// "toast", ...} (what a plugin logs or shows), {event: "auth", provider}
// (a sign-in the host saved or refreshed).
@@ -29,7 +34,177 @@ import tls from "node:tls"
import { pathToFileURL } from "node:url"
const rpcWrite = process.stdout.write.bind(process.stdout)
const send = (msg) => rpcWrite(JSON.stringify(msg) + "\n")
// Everything the child writes goes through one ordered queue: a line goes out
// only when the stream can take it, so a parent that stops reading bounds what
// Bun buffers instead of it growing without bound. A caller may cancel its own
// wait, which drops its line if it has not been written yet, so an aborted
// request leaves no listener or closure behind. A write failure or a closed
// stream fails every line still waiting rather than leaving them pending.
const outq = [] // {line, settle}
let pumping = false
let outFail = null
function waitDrain() {
return new Promise((resolve, reject) => {
const done = () => { clear(); resolve() }
const bad = (e) => { clear(); reject(e ?? new Error("the host's stdout closed")) }
const clear = () => {
process.stdout.removeListener("drain", done)
process.stdout.removeListener("error", bad)
process.stdout.removeListener("close", bad)
}
process.stdout.once("drain", done)
process.stdout.once("error", bad)
process.stdout.once("close", bad)
})
}
function pump() {
if (pumping) return
pumping = true
while (outq.length) {
const item = outq[0]
if (outFail) {
outq.shift()
item.settle(outFail)
continue
}
// write returns false when the stream is full, but the line was still
// taken: wait for it to drain before the next one, never write it twice
const ok = rpcWrite(item.line)
outq.shift()
item.settle(null)
if (!ok) {
waitDrain().then(
() => { pumping = false; pump() },
(e) => { outFail = e; pumping = false; pump() },
)
return
}
}
pumping = false
}
// queueLine queues one line, giving a promise that settles with null once it is
// written or with the error that stopped it, and a way to give the wait up.
function queueLine(line) {
const item = { line, settle: () => {} }
const promise = new Promise((resolve) => { item.settle = (err) => resolve(err ?? null) })
outq.push(item)
pump()
return {
promise,
cancel: () => {
const i = outq.indexOf(item)
if (i >= 0) {
outq.splice(i, 1)
item.settle(null)
}
},
}
}
// send queues one message, ignoring whether it was written.
const send = (msg) => queueLine(JSON.stringify(msg) + "\n").promise
// sendCancelable is send, with a way to give the wait up.
const sendCancelable = (msg) => queueLine(JSON.stringify(msg) + "\n")
// A host cancellation suppresses the answer; a local abort still owes Go
// its error. The record, rather than the signal, owns pending wire output.
function transitionFetch(record, state) {
if (record.state === "finished") return
if (record.state !== "cancelled") record.state = state
if (state === "streaming") return
record.gate.stop()
const body = record.unconsumedBody
record.unconsumedBody = undefined
try { Promise.resolve(body?.cancel?.()).catch(() => {}) } catch {}
if (state === "finishing") return
record.pendingSend?.cancel()
record.readyCleanup?.()
record.readyCleanup = null
if (state === "cancelled") record.controller.abort()
else record.state = "finished"
}
function checkFetch(record) {
if (record.state === "cancelled" || record.state === "finished") throw new DOMException("Aborted", "AbortError")
record.controller.signal.throwIfAborted()
}
async function sendForFetch(record, msg) {
if (record.state === "cancelled" || record.state === "finished") return
const ctl = record.controller
const pendingSend = sendCancelable(msg)
record.pendingSend = pendingSend
const onAbort = () => pendingSend.cancel()
ctl.signal.addEventListener("abort", onAbort, { once: true })
try {
const err = await pendingSend.promise
if (err) throw err
} finally {
record.pendingSend = null
ctl.signal.removeEventListener("abort", onAbort)
}
}
// The largest decoded bytes one frame carries: the reader credits in larger
// steps than this, so frames stay small enough that a credit round trip is
// cheap without one frame dwarfing the window.
const MAX_FRAME = 64 << 10
// FRAME_OVERHEAD is what one queued frame costs the window besides its bytes,
// as Go counts it too: the message struct and the decoded slice behind it. It
// keeps a producer of tiny frames from filling a window with structs.
const FRAME_OVERHEAD = 2048
// HEAD_MAX and HEAD_ENTRIES are magpie's own head-envelope policy, not HTTP's:
// a fetch's head carries at most HEAD_MAX header bytes (the UTF-8 bytes of
// every name and value, plus HEAD_ENTRY_COST an entry) and HEAD_ENTRIES
// entries, counted the same by Go before it is queued, so a vendor's unbounded
// header set is not a free 0-charge line.
const HEAD_MAX = 64 << 10
const HEAD_ENTRIES = 256
const HEAD_ENTRY_COST = 4
// headCost is a head's header cost, as Go counts it too: the UTF-8 bytes of
// every name and value, plus HEAD_ENTRY_COST an entry.
function headCost(h) {
let n = 0
for (const [k, v] of Object.entries(h)) n += Buffer.byteLength(k) + Buffer.byteLength(v) + HEAD_ENTRY_COST
const entries = Object.keys(h).length
return { n, entries }
}
// makeGate is one fetch's credit: the child may have `window` decoded bytes
// outstanding, each frame costing its bytes plus FRAME_OVERHEAD. take returns
// how many bytes of a frame may go now (-1 when the fetch was stopped), spend
// takes the frame's cost, add is the reader giving credit back.
function makeGate(window) {
let free = window
let stopped = false
let wake = null
const fit = (want) => Math.min(want, free - FRAME_OVERHEAD)
return {
take(want) {
if (stopped) return Promise.resolve(-1)
const n = fit(want)
if (n > 0) return Promise.resolve(n)
return new Promise((resolve) => { wake = (ok) => resolve(ok ? fit(want) : -1) })
},
spend(cost) { free -= cost },
add(n) {
free += n
if (wake && free > FRAME_OVERHEAD) { const w = wake; wake = null; w(true) }
},
stop() {
stopped = true
if (wake) { const w = wake; wake = null; w(false) }
},
}
}
// A plugin writing to stdout would break the protocol: everything it
// prints goes to stderr, which magpie logs.
@@ -72,7 +247,7 @@ const hooks = [] // {spec, hooks}
const loaded = [] // {spec, id, error}
const loaders = new Map() // account → options the auth loader returned
const sessions = new Map() // oauth sign-in in progress → its authorize result
const inflight = new Map() // fetch id → AbortController
const inflight = new Map() // fetch id → its lifecycle and owned resources
const renewing = new Map() // account → its sign-in's renewal under way
const unrenewed = new Map() // account → its last renewal that failed: {at, secret, gone}
let config = { provider: {} } // what the plugins' config hooks made of it
@@ -1205,22 +1380,24 @@ function bodyOf(b64) {
}
}
async function doFetch(id, params) {
async function doFetch(id, record, params) {
const key = accountKey(params.provider, params.account)
return via.run(params.proxy ?? "", () => inScope(params.provider, key, () => fetchAs(id, key, params)))
return via.run(params.proxy ?? "", () => inScope(params.provider, key, () => fetchAs(id, record, key, params)))
}
async function fetchAs(id, key, { provider, model, npm, url, method, headers, body, session }) {
const ctl = new AbortController()
inflight.set(id, ctl)
async function fetchAs(id, record, key, params) {
const { controller: ctl, gate } = record
const { provider, model, npm, url, method, headers, body, session } = params
try {
const o = await options(provider, key)
checkFetch(record)
const h = new Headers()
for (const [k, v] of Object.entries(sdkHeaders(npm, o.apiKey))) h.set(k, v)
for (const [k, v] of Object.entries(o.headers ?? {})) h.set(k, String(v))
for (const [k, v] of Object.entries(headers ?? {})) h.set(k, v)
// chat.headers: what the plugins add to the request, theirs winning
const p = await info(provider, key)
checkFetch(record)
const m = p.models[model] ?? { id: model, providerID: provider, api: { id: model, npm } }
for (const x of hooks) {
const fn = x.hooks["chat.headers"]
@@ -1240,31 +1417,64 @@ async function fetchAs(id, key, { provider, model, npm, url, method, headers, bo
} catch (e) {
send({ event: "log", level: "error", message: `${x.spec}: chat.headers: ${e?.message ?? e}` })
}
checkFetch(record)
for (const [k, v] of Object.entries(out.headers)) h.set(k, String(v))
}
const f = typeof o.fetch === "function" ? o.fetch : fetch
// the fetch is owned since its message was read: an abort that came while
// this setup was awaiting must not let the upstream start
checkFetch(record)
const res = await f(url, {
method: method ?? "POST",
headers: h,
body: bodyOf(body),
signal: ctl.signal,
})
record.unconsumedBody = res.body
checkFetch(record)
transitionFetch(record, "streaming")
const rh = {}
res.headers.forEach((v, k) => (rh[k] = v))
send({ id, event: "head", status: res.status, headers: rh })
const head = headCost(rh)
if (head.entries > HEAD_ENTRIES || head.n > HEAD_MAX) {
// the reply's head is past magpie's envelope: give the fetch up rather
// than write a line the host would refuse, and let the body go
throw new Error(`the reply's headers are past the host's head envelope (${HEAD_MAX} bytes or ${HEAD_ENTRIES} entries)`)
}
await sendForFetch(record, { id, event: "head", status: res.status, headers: rh })
checkFetch(record)
if (res.body) {
record.unconsumedBody = undefined
// an abort gives up this fetch's own pending write, so its wait ends and
// the loop leaves rather than parking on a stream that never drains
for await (const chunk of res.body) {
send({ id, event: "chunk", data: Buffer.from(chunk).toString("base64") })
checkFetch(record)
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
for (let off = 0; off < bytes.length; ) {
// one frame at a time, no more than the reader has credited: a
// reader that stopped leaves the upstream paused here
const n = await gate.take(Math.min(MAX_FRAME, bytes.length - off))
checkFetch(record)
if (n <= 0) break
const data = bytes.subarray(off, off + n).toString("base64")
gate.spend(n + FRAME_OVERHEAD)
await sendForFetch(record, { id, event: "chunk", data })
checkFetch(record)
off += n
}
}
}
send({ id, result: null })
checkFetch(record)
transitionFetch(record, "finishing")
await sendForFetch(record, { id, result: null })
} catch (e) {
transitionFetch(record, "finishing")
// a fetch hook that threw on its sign-in (a refresh the vendor turned
// away) marks the account, as a built-in's refused refresh marked it
if (["expired", "kept", "renewed"].includes(e?.signIn) && key) send({ event: "signIn", provider, account: key, said: e.signIn })
send({ id, error: { message: String(e?.message ?? e) } })
} finally {
inflight.delete(id)
// a fetch the host already gave up on needs no late error: its slot is
// gone, and queueing an uncancellable line for it would only be noise
await sendForFetch(record, { id, error: { message: String(e?.message ?? e) } })
}
}
@@ -1351,6 +1561,42 @@ const handlers = {
// Everything waits for init; a request is answered even when magpie has
// closed stdin behind it, the host leaving once nothing is pending.
let ready
let readyState
const readyWaiters = new Set()
function setReady(promise) {
readyState = undefined
ready = promise
const settle = (state) => {
readyState = state
for (const waiter of readyWaiters) waiter(state)
readyWaiters.clear()
}
ready.then(
() => settle({}),
(error) => settle({ error }),
)
}
function waitForReady(record) {
const signal = record.controller.signal
if (!ready) return Promise.reject(new Error("the host has not been initialised"))
return new Promise((resolve, reject) => {
const finish = (state) => {
readyWaiters.delete(finish)
signal.removeEventListener("abort", abort)
record.readyCleanup = null
if ("error" in state) reject(state.error)
else resolve()
}
const abort = () => finish({ error: new DOMException("Aborted", "AbortError") })
record.readyCleanup = abort
if (signal.aborted) abort()
else if (readyState) finish(readyState)
else {
readyWaiters.add(finish)
signal.addEventListener("abort", abort, { once: true })
}
})
}
let pending = 0
let closed = false
const done = () => {
@@ -1367,23 +1613,57 @@ rl.on("line", (line) => {
return
}
if (msg.method === "abort") {
inflight.get(msg.params?.id)?.abort()
const id = msg.params?.id
const record = inflight.get(id)
if (record) transitionFetch(record, "cancelled")
return
}
if (msg.method === "credit") {
const record = inflight.get(msg.params?.id)
if (record?.state === "streaming") record.gate.add(msg.params?.n ?? 0)
return
}
pending++
if (msg.method === "init") {
ready = handlers.init(msg.params ?? {})
setReady(handlers.init(msg.params ?? {}))
ready.then(
(result) => send({ id: msg.id, result }),
(e) => send({ id: msg.id, error: { message: String(e?.message ?? e) } }),
).finally(done)
return
}
const wait = ready ?? Promise.reject(new Error("the host has not been initialised"))
if (msg.method === "fetch") {
wait.then(() => doFetch(msg.id, msg.params ?? {}), (e) => send({ id: msg.id, error: { message: String(e?.message ?? e) } })).finally(done)
const id = msg.id
// the fetch is owned the moment its message is read, before the async
// setup below: an abort that comes before the upstream is reached still
// stops it, and one that comes during the await is not missed
const record = {
state: "setup", controller: new AbortController(),
gate: makeGate(msg.params?.window > 0 ? msg.params.window : 512 << 10),
pendingSend: null, readyCleanup: null, unconsumedBody: undefined,
}
inflight.set(id, record)
// waiting for the host to be ready is the host's own await: an abort must
// end it too, so a request whose setup never finishes still runs its
// finally and lets its controller, gate and body go. The shared setup
// promise itself is not cancelled — only this request's wait on it.
const start = () => {
checkFetch(record)
return doFetch(id, record, msg.params ?? {})
}
waitForReady(record).then(start)
.catch((e) => {
transitionFetch(record, "finishing")
return sendForFetch(record, { id, error: { message: String(e?.message ?? e) } })
})
.finally(() => {
transitionFetch(record, "finished")
inflight.delete(id)
done()
})
return
}
const wait = ready ?? Promise.reject(new Error("the host has not been initialised"))
const fn = handlers[msg.method]
if (!fn) {
send({ id: msg.id, error: { message: `no method ${msg.method}` } })
+671
View File
@@ -0,0 +1,671 @@
package plugin
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestHostJSCancellation(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("no node on PATH")
}
for _, name := range []string{"stopped-gate", "split-chunk", "terminal", "blocked-head", "blocked-head-cancel-error", "ready-wait", "ready-success", "ready-error", "local-error", "local-error-cancel", "normal-reply"} {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, node, "-e", hostJSCancellationTest, name)
cmd.Stdin = bytes.NewReader(hostJS)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("JavaScript cancellation regression: %v\n%s", err, out)
}
if len(out) > 0 {
t.Logf("%s", out)
}
})
}
}
const hostJSCancellationTest = `
const assert = require('node:assert/strict')
const fs = require('node:fs')
const vm = require('node:vm')
const { EventEmitter } = require('node:events')
const source = fs.readFileSync(0, 'utf8')
const section = (from, to) => {
const start = source.indexOf(from)
const end = to ? source.indexOf(to, start) : source.length
assert.ok(start >= 0 && end > start, 'production section exists')
return source.slice(start, end)
}
const stdout = new EventEmitter()
const lines = []
let blockOn = ''
stdout.write = line => {
const msg = JSON.parse(line)
lines.push(msg)
return blockOn !== 'all' && !(blockOn === 'chunk' && msg.event === 'chunk')
}
const rl = new EventEmitter()
const context = vm.createContext({
Buffer, Headers, AbortController, DOMException, ReadableStream,
process: { stdout, stdin: {}, exit: () => { throw Error('unexpected exit') } },
readline: { createInterface: () => rl },
options: async () => ({ fetch: async () => context.reply }),
info: async () => ({ models: {} }),
sdkHeaders: () => ({}), bodyOf: () => undefined,
accountKey: () => '',
via: { run: (_, fn) => fn() }, inScope: (_, key, fn) => fn(),
})
const run = code => vm.runInContext(code, context)
run(section('const rpcWrite =', '// A plugin writing to stdout'))
run('const hooks = []; const inflight = new Map(); const handlers = {}')
run(section('async function doFetch(', '// ---- the loop'))
run(section('// Everything waits for init;'))
const message = value => rl.emit('line', JSON.stringify(value))
const tick = () => new Promise(resolve => setImmediate(resolve))
const until = async (check, label) => {
for (let iteration = 0; iteration < 30; iteration++) {
if (check()) return
await tick()
}
assert.ok(check(), label)
}
const idle = () => run('pending === 0 && inflight.size === 0')
const queued = () => run('outq.length')
const fetchOne = () => message({ id: 1, method: 'fetch', params: { window: 512 << 10, provider: 'test', model: 'test', url: 'http://localhost/' } })
const abortOne = () => message({ method: 'abort', params: { id: 1 } })
const initialize = promise => {
context.initialization = promise
run('typeof setReady === "function" ? setReady(initialization) : ready = initialization')
}
async function main() {
const name = process.argv[1]
initialize(Promise.resolve())
await tick()
context.reply = { status: 200, headers: new Headers(), body: null }
if (name === 'stopped-gate') {
run('globalThis.gate = makeGate(512 << 10)')
assert.equal(await run('gate.take(64)'), 64)
run('gate.stop(); gate.add(1)')
assert.equal(await run('gate.take(64)'), -1, 'stopped gate refuses remaining credit')
} else if (name === 'split-chunk') {
blockOn = 'chunk'
context.reply.body = (async function* () { yield Buffer.alloc(3 * (64 << 10)) })()
fetchOne()
await until(() => queued() === 1 && run('outq[0].line.includes("chunk")'), 'second slice queued while credit remains')
abortOne()
await until(idle, 'cancelled split-chunk fetch cleans registries and pending count')
assert.equal(queued(), 0, 'no late chunk or terminal queued')
assert.equal(lines.filter(msg => msg.event === 'chunk').length, 1)
assert.equal(lines.filter(msg => msg.id === 1 && ('result' in msg || 'error' in msg)).length, 0)
} else if (name === 'terminal') {
blockOn = 'all'
fetchOne()
await until(() => queued() === 1, 'terminal queued behind head awaiting drain')
abortOne()
await until(idle, 'cancelled terminal wait cleans registries')
assert.equal(queued(), 0, 'cancelled terminal removed')
} else if (name === 'blocked-head' || name === 'blocked-head-cancel-error') {
blockOn = 'all'
run('send({ id: 99, result: null })')
let bodyCancelCalls = 0
context.reply.body = new ReadableStream({ cancel() {
bodyCancelCalls++
if (name === 'blocked-head-cancel-error') throw Error('body cancellation failed')
} })
fetchOne()
await until(() => queued() === 1 && run('outq[0].line.includes("head")'), 'head queued behind blocked stdout')
abortOne()
await until(idle, 'cancelled blocked head cleans registries')
console.log(JSON.stringify({ idle: idle(), queued: queued(), bodyCancelCalls, bodyLocked: context.reply.body.locked }))
assert.equal(bodyCancelCalls, 1, 'acquired body cancelled before iteration')
assert.equal(queued(), 0, 'cancelled head removed')
assert.equal(context.reply.body.locked, false)
assert.equal(lines.length, 1, 'body cancellation emits no duplicate error')
} else if (name === 'ready-wait') {
blockOn = 'all'
let readyReactions = 0
const unresolved = new Promise(() => {})
const originalThen = unresolved.then.bind(unresolved)
unresolved.then = (...args) => { readyReactions++; return originalThen(...args) }
initialize(unresolved)
run('send({id: 99, result: null})')
for (let iteration = 0; iteration < 30000; iteration++) {
fetchOne()
abortOne()
await until(idle, 'cancelled bootstrap wait cleans registries')
assert.equal(queued(), 0, 'cancelled bootstrap emits no late error')
}
assert.equal(lines.length, 1, 'stdout stayed blocked at original line')
assert.equal(stdout.listenerCount('drain'), 1, 'only shared drain listener remains')
const retainedWaiters = run('typeof readyWaiters === "undefined" ? -1 : readyWaiters.size')
const retainedReadyReactions = readyReactions - (run('typeof setReady') === 'function' ? 1 : 0)
console.log(JSON.stringify({ cancellations: 30000, idle: idle(), queued: queued(), readyReactions, retainedReadyReactions, retainedWaiters }))
assert.equal(retainedWaiters, 0, 'cancelled bootstrap leaves no retained waiters')
assert.equal(retainedReadyReactions, 0, 'cancelled requests leave no reactions on shared ready')
assert.equal(readyReactions, 1, 'only shared initialization reaction remains')
} else if (name === 'ready-success' || name === 'ready-error') {
let settle
initialize(new Promise((resolve, reject) => { settle = name === 'ready-success' ? resolve : reject }))
fetchOne()
assert.equal(run('readyWaiters.size'), 1, 'bootstrap waiter registered')
settle(name === 'ready-error' ? Error('init failed') : undefined)
await until(idle, 'settled initialization cleans fetch')
assert.equal(run('readyWaiters.size'), 0, 'settled initialization releases waiters')
if (name === 'ready-error') {
assert.equal(lines.length, 1)
assert.equal(lines[0].error.message, 'init failed')
} else {
assert.deepEqual(lines.map(msg => msg.event || 'result'), ['head', 'result'])
}
} else if (name === 'mid-setup') {
for (const stage of ['options', 'info']) {
let release
let entered = false
let vendorCalls = 0
const barrier = new Promise(resolve => { release = resolve })
context.options = async () => {
if (stage === 'options') { entered = true; await barrier }
return { fetch: async () => { vendorCalls++; return context.reply } }
}
context.info = async () => {
if (stage === 'info') { entered = true; await barrier }
return { models: {} }
}
fetchOne()
await until(() => entered, 'plugin setup entered its deferred await')
assert.equal(run('inflight.get(1).state'), 'setup')
abortOne()
assert.equal(run('inflight.get(1).state'), 'cancelled', 'JS processed abort before setup resumes')
assert.equal(run('inflight.get(1).controller.signal.aborted'), true)
release()
await until(idle, 'cancelled setup finishes')
assert.equal(vendorCalls, 0, 'cancelled setup never starts vendor')
context.options = async () => ({ fetch: async () => { vendorCalls++; return context.reply } })
context.info = async () => ({ models: {} })
fetchOne()
await until(idle, 'healthy fetch after cancelled setup')
assert.equal(vendorCalls, 1)
}
assert.deepEqual(lines.map(msg => msg.event || 'result'), ['head', 'result', 'head', 'result'])
} else if (name === 'local-error') {
context.options = async () => {
run('inflight.get(1).controller.abort()')
throw Error('local protocol failure')
}
fetchOne()
await until(idle, 'local error settles')
assert.equal(lines.length, 1)
assert.equal(lines[0].error.message, 'local protocol failure', 'local abort does not suppress error owed to Go')
} else if (name === 'local-error-cancel') {
blockOn = 'all'
run('send({ id: 99, result: null })')
context.options = async () => {
run('inflight.get(1).controller.abort()')
throw Error('local protocol failure')
}
fetchOne()
await until(() => queued() === 1, 'local error queued after local abort')
abortOne()
await until(idle, 'host cancel ends error wait even after local signal aborted')
assert.equal(queued(), 0, 'late error removed after host cancel')
} else if (name === 'normal-reply') {
context.reply.body = (async function* () { yield Buffer.from('complete reply') })()
fetchOne()
await until(idle, 'normal reply settles')
assert.deepEqual(lines.map(msg => msg.event || 'result'), ['head', 'chunk', 'result'])
assert.equal(Buffer.from(lines[1].data, 'base64').toString(), 'complete reply')
assert.equal(lines[2].result, null)
} else {
throw Error('unknown test case')
}
}
main().catch(err => { console.error(err); process.exitCode = 1 })
`
// fakeSignedIn starts a real Bun host with the fake plugin signed in to, its
// requests going to base, and gives the plugin's base URL.
func fakeSignedIn(t *testing.T, base string) string {
t.Helper()
sandbox(t)
t.Setenv("FAKE_BASE", base)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
t.Cleanup(cancel)
abs, _ := filepath.Abs("testdata/fake/index.js")
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := Providers(ctx); err != nil {
t.Fatal(err)
}
if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil {
t.Fatal(err)
}
o, err := LoaderOptions(ctx, "fakeco", "")
if err != nil {
t.Fatal(err)
}
return o.BaseURL
}
// TestFlowSlowReaderGetsTheWholeReply is the flow control's point: a reader
// slower than the vendor still gets every byte — credit pauses the upstream
// rather than the host cutting the reply at a fixed size.
func TestFlowSlowReaderGetsTheWholeReply(t *testing.T) {
const size = 4 << 20
payload := bytes.Repeat([]byte("0123456789abcdef"), size/16)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
for off := 0; off < len(payload); off += 64 << 10 {
end := min(off+(64<<10), len(payload))
_, _ = w.Write(payload[off:end])
w.(http.Flusher).Flush()
}
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
res, err := Fetch(ctx, FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/big", Method: "POST", Body: []byte(`{}`),
})
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
// read slower than the vendor writes, so the credit window must pause it
// and let it go again rather than the reply being cut
buf := make([]byte, 64<<10)
var got []byte
for {
n, err := res.Body.Read(buf)
if n > 0 {
got = append(got, buf[:n]...)
time.Sleep(time.Millisecond)
}
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("read at %d bytes: %v", len(got), err)
}
}
if !bytes.Equal(got, payload) {
t.Fatalf("read %d bytes, want %d", len(got), len(payload))
}
}
// TestFlowCancelAfterHeadStopsTheVendor: a request cancelled after its head,
// with nothing reading or closing the body, still stops the upstream fetch —
// the vendor's own request is cancelled.
func TestFlowCancelAfterHeadStopsTheVendor(t *testing.T) {
hit := make(chan struct{})
gone := make(chan struct{})
var once sync.Once
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
w.(http.Flusher).Flush()
once.Do(func() { close(hit) })
<-r.Context().Done()
close(gone)
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
rctx, rcancel := context.WithCancel(ctx)
res, err := Fetch(rctx, FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/hang", Method: "POST", Body: []byte(`{}`),
})
if err != nil {
t.Fatal(err)
}
<-hit // the vendor is in the request, its head has reached magpie
rcancel() // nothing reads or closes the body
select {
case <-gone:
case <-time.After(10 * time.Second):
t.Fatal("cancelling the request did not stop the vendor")
}
_ = res
}
// TestFlowTinyFramesStillArrive: a vendor that yields tiny pieces, read slowly,
// still gets every byte. The frame overhead pauses such a producer — it can
// keep at most window/(payload+overhead) frames queued — rather than the host
// cutting it, and the reader gets the whole reply.
func TestFlowTinyFramesStillArrive(t *testing.T) {
const size = 4096
payload := bytes.Repeat([]byte("abcdefgh"), size/8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fl := w.(http.Flusher)
for i := range payload {
_, _ = w.Write(payload[i : i+1])
if i%16 == 0 {
fl.Flush()
}
}
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
res, err := Fetch(ctx, FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/tiny", Method: "POST", Body: []byte(`{}`),
})
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
buf := make([]byte, 512)
var got []byte
for {
n, err := res.Body.Read(buf)
if n > 0 {
got = append(got, buf[:n]...)
time.Sleep(time.Millisecond)
}
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("read at %d bytes: %v", len(got), err)
}
}
if !bytes.Equal(got, payload) {
t.Fatalf("read %d bytes, want %d", len(got), len(payload))
}
}
// bigPiece is one piece of the production-scale stream: the 64 KiB block, or
// the same block as an SSE data event.
func bigPiece(block []byte, sse bool) []byte {
if !sse {
return block
}
return []byte("data: " + base64.StdEncoding.EncodeToString(block) + "\n\n")
}
// writeBig writes about total bytes of the pattern to w (nil to only measure),
// giving the exact length and its SHA-256. The vendor and the check build the
// same bytes, so a truncation anywhere shows up as a length or hash mismatch.
func writeBig(w io.Writer, total int, sse bool, block []byte) (int64, [32]byte) {
h := sha256.New()
var n int64
for n < int64(total) {
piece := bigPiece(block, sse)
if w != nil {
if _, err := w.Write(piece); err != nil {
break
}
}
h.Write(piece)
n += int64(len(piece))
}
var sum [32]byte
copy(sum[:], h.Sum(nil))
return n, sum
}
// TestFlowBigReplyProd is the production-scale check: 100 MiB of a non-SSE body
// and of an SSE stream, each read through the real host and hashed; an SSE
// stream a reader pauses 12 s in the middle of and then finishes. It is behind
// MAGPIE_FLOW_BIG because each case moves 100 MiB, and it should be run against
// the Bun magpie itself picks (MAGPIE_BUN set to it).
func TestFlowBigReplyProd(t *testing.T) {
if os.Getenv("MAGPIE_FLOW_BIG") == "" {
t.Skip("set MAGPIE_FLOW_BIG=1 to run the 100 MiB flow cases")
}
const total = 100 << 20
block := make([]byte, 64<<10)
for i := range block {
block[i] = byte(i * 7)
}
for _, tc := range []struct {
name string
sse bool
pause time.Duration
}{
{"non-sse", false, 0},
{"sse", true, 0},
{"sse-paused", true, 12 * time.Second},
} {
t.Run(tc.name, func(t *testing.T) {
ctype := "application/json"
if tc.sse {
ctype = "text/event-stream"
}
// how far the vendor has got, and whether it finished, so a pause
// the reader takes shows whether the upstream was held back too
var written atomic.Int64
finished := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer close(finished)
w.Header().Set("Content-Type", ctype)
w.WriteHeader(200)
fl := w.(http.Flusher)
var n int64
for n < int64(total) {
piece := bigPiece(block, tc.sse)
m, err := w.Write(piece)
written.Add(int64(m))
if err != nil {
return
}
n += int64(len(piece))
if n%(8<<20) < int64(len(piece)) {
fl.Flush()
}
}
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
wantLen, wantSum := writeBig(nil, total, tc.sse, block)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
res, err := Fetch(ctx, FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/big", Method: "POST", Body: []byte(`{}`),
})
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
h := sha256.New()
var n int64
paused := false
var pausedAt, resumedAt, pauseOwed, pauseWindow int64
var finishedBeforeResume, windowExhausted bool
buf := make([]byte, 256<<10)
for {
m, err := res.Body.Read(buf)
if m > 0 {
h.Write(buf[:m])
n += int64(m)
if tc.pause > 0 && !paused && n >= 1<<20 {
paused = true
pausedAt = written.Load()
t.Logf("pause_start: delivered=%d producer_written=%d expected=%d", n, pausedAt, wantLen)
// Reflection keeps this public-API fixture compilable with
// the old host.go overlay, which has no credit counters.
b := res.Body.(*body)
pauseEnd := time.Now().Add(tc.pause)
for time.Now().Before(pauseEnd) {
b.c.mu.Lock()
fields := reflect.ValueOf(b.c).Elem()
owed, window := fields.FieldByName("owed"), fields.FieldByName("window")
if owed.IsValid() && window.IsValid() {
pauseOwed, pauseWindow = owed.Int(), window.Int()
windowExhausted = pauseWindow > 0 && pauseWindow-pauseOwed <= 2048
}
b.c.mu.Unlock()
if windowExhausted {
time.Sleep(time.Until(pauseEnd))
break
}
time.Sleep(10 * time.Millisecond)
}
resumedAt = written.Load()
select {
case <-finished:
finishedBeforeResume = true
default:
}
t.Logf("pause_end_before_read: producer_written=%d expected=%d finished=%t window_exhausted=%t owed=%d window=%d", resumedAt, wantLen, finishedBeforeResume, windowExhausted, pauseOwed, pauseWindow)
}
}
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("read at %d bytes: %v", n, err)
}
}
got := h.Sum(nil)
if n != wantLen {
t.Fatalf("read %d bytes, want %d", n, wantLen)
}
if !bytes.Equal(got, wantSum[:]) {
t.Fatalf("sha256 = %x, want %x", got, wantSum)
}
if tc.pause > 0 {
// Preserve the original length/hash failure as the negative
// control; only these new producer assertions are optional.
if os.Getenv("MAGPIE_FLOW_ORIGINAL_BEHAVIOR_ONLY") != "1" {
if !windowExhausted {
t.Error("the paused reader did not exhaust the Go credit window")
}
if finishedBeforeResume || resumedAt >= wantLen {
t.Errorf("producer finished before resume: written=%d expected=%d finished=%t", resumedAt, wantLen, finishedBeforeResume)
}
}
select {
case <-finished:
case <-time.After(5 * time.Second):
t.Fatal("producer did not finish after resume")
}
t.Logf("producer_after_resume: written=%d expected=%d finished=true", written.Load(), wantLen)
}
t.Logf("%s: %d bytes, sha256 %x", tc.name, n, got)
})
}
}
// TestFlowAbortDuringSetupStaysHealthy: many fetches cancelled as soon as they
// are made — while the plugin is still setting them up, or waiting for a slow
// vendor's head — leave the host able to answer a later request. It is the Go
// side of the lifecycle: the host's slots come back, and the JS side's own
// finally (covered by construction) lets each request's controller and gate go.
func TestFlowAbortDuringSetupStaysHealthy(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("no node on PATH")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, node, "-e", hostJSCancellationTest, "mid-setup")
cmd.Stdin = bytes.NewReader(hostJS)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("mid-setup cancellation: %v\n%s", err, out)
}
}
func TestFlowEarlyCancellationStressStaysHealthy(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(300 * time.Millisecond):
case <-r.Context().Done():
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
r := FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/slow", Method: "POST", Body: []byte(`{}`),
}
for i := range 20 {
fctx, fcancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
defer close(done)
res, err := Fetch(fctx, r)
if err == nil {
_, _ = io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
fcancel() // as early as possible: setup, or the head wait
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatalf("fetch %d did not return after cancel", i)
}
}
// the host still answers a request that is not cancelled
res, err := Fetch(ctx, r)
if err != nil {
t.Fatalf("a fetch after the cancelled ones: %v", err)
}
defer res.Body.Close()
if body, err := io.ReadAll(res.Body); err != nil || !bytes.Contains(body, []byte(`"ok":true`)) {
t.Fatalf("body = %q, %v", body, err)
}
}
// TestFlowHeadEnvelopeRejectsHugeHeaders: a vendor that answers with more
// headers than magpie's head envelope allows fails the fetch cleanly rather
// than the host taking an unbounded zero-charge head line.
func TestFlowHeadEnvelopeRejectsHugeHeaders(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Big", strings.Repeat("v", 96<<10)) // past the 64 KiB envelope
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
base := fakeSignedIn(t, srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
_, err := Fetch(ctx, FetchRequest{
Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: base + "/bighead", Method: "POST", Body: []byte(`{}`),
})
if err == nil {
t.Fatal("a reply with an oversized head was accepted")
}
}
+92 -13
View File
@@ -89,9 +89,26 @@ func (c *wireIn) fetchFrame(t *testing.T) []byte {
func newWireHost(tb testing.TB, in *wireIn) (*host, *io.PipeWriter) {
tb.Helper()
pr, pw := io.Pipe()
h := &host{cmd: &exec.Cmd{}, in: in, calls: map[int64]*call{}, dead: make(chan struct{})}
hctx, hcancel := context.WithCancel(context.Background())
h := &host{
cmd: &exec.Cmd{}, in: in,
calls: map[int64]*call{},
dead: make(chan struct{}),
slots: make(chan struct{}, callLimit()),
streams: make(chan struct{}, streamLimit()),
out: make(chan writeReq, callLimit()),
ctrl: map[int64]*ctrl{},
ctrlWake: make(chan struct{}, 1),
ctx: hctx,
cancel: hcancel,
}
go h.read(pr)
tb.Cleanup(func() { _ = pw.CloseWithError(io.EOF) })
go h.writerLoop()
go h.ctrlLoop()
tb.Cleanup(func() {
_ = pw.CloseWithError(io.EOF)
hcancel()
})
return h, pw
}
@@ -187,20 +204,21 @@ func fetchOnce(t *testing.T, r FetchRequest) []byte {
return line
}
// legacyFetchParams is the anonymous params struct Fetch built before the body
// went to encoding/json as a []byte: the same tags, the body as the base64
// string EncodeToString made of it.
func legacyFetchParams(r FetchRequest) any {
// expectedFetchParams is the params struct Fetch builds: the body as the
// base64 string encoding/json writes for a []byte, and the credit window the
// flow control added.
func expectedFetchParams(r FetchRequest) any {
return struct {
FetchRequest
Body string `json:"body,omitempty"`
}{r, base64.StdEncoding.EncodeToString(r.Body)}
Body string `json:"body,omitempty"`
Window int `json:"window"`
}{r, base64.StdEncoding.EncodeToString(r.Body), streamWindow}
}
// legacyFrame is the frame the older Fetch would have written for r, id and all.
func legacyFrame(t *testing.T, id int64, r FetchRequest) []byte {
// expectedFrame is the frame Fetch writes for r, id and all.
func expectedFrame(t *testing.T, id int64, r FetchRequest) []byte {
t.Helper()
b, err := json.Marshal(map[string]any{"id": id, "method": "fetch", "params": legacyFetchParams(r)})
b, err := json.Marshal(map[string]any{"id": id, "method": "fetch", "params": expectedFetchParams(r)})
if err != nil {
t.Fatalf("marshal: %v", err)
}
@@ -264,6 +282,67 @@ func TestFetchHostKeepsTheRestartSignal(t *testing.T) {
}
}
// TestFetchStreamsHeadChunksFinal: a whole reply — head, chunks, final — sent
// in one burst down the same pipe reaches Fetch's body byte for byte, and the
// bytes the reader takes are credited back to the child. Unlike fetchOnce,
// which ends a call by cancelling it, this drives the real final answer, so the
// head/chunks/final ordering is covered end to end.
func TestFetchStreamsHeadChunksFinal(t *testing.T) {
in := newWireIn(true)
h, pw := newWireHost(t, in)
checkList()
hostMu.Lock()
prev, prevStale := current, hostStale.Swap(false)
current = h
hostMu.Unlock()
t.Cleanup(func() {
hostMu.Lock()
current = prev
if prevStale {
hostStale.Store(true)
}
hostMu.Unlock()
})
payload := bytes.Repeat([]byte("0123456789abcdef"), 4096) // 64 KiB
go func() {
<-in.wrote // the fetch frame
var m struct {
ID int64 `json:"id"`
}
if json.Unmarshal(bytes.TrimSuffix(in.lastLine(), []byte("\n")), &m) != nil || m.ID == 0 {
return
}
write := func(v any) {
b, err := json.Marshal(v)
if err != nil {
return
}
_, _ = pw.Write(append(b, '\n'))
}
write(map[string]any{"id": m.ID, "event": "head", "status": 200, "headers": map[string]string{"content-type": "text/event-stream"}})
for off := 0; off < len(payload); off += 4096 {
write(map[string]any{"id": m.ID, "event": "chunk", "data": base64.StdEncoding.EncodeToString(payload[off : off+4096])})
}
write(map[string]any{"id": m.ID, "result": nil})
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
res, err := Fetch(ctx, benchRequest([]byte("hello")))
if err != nil {
t.Fatalf("Fetch: %v", err)
}
got, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("reading: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("body = %d bytes, want %d", len(got), len(payload))
}
res.Body.Close()
}
func TestFetchBodyWireIsUnchanged(t *testing.T) {
htmlUnicode := "a<b>&\"c\" — 你好 <script>"
for _, tc := range []struct {
@@ -298,9 +377,9 @@ func TestFetchBodyWireIsUnchanged(t *testing.T) {
t.Fatalf("frame = %+v", got)
}
// the older params build the same frame, byte for byte (the
// the params Fetch builds give the same frame, byte for byte (the
// metadata above is there to keep escaping and ordering pinned)
want := legacyFrame(t, got.ID, r)
want := expectedFrame(t, got.ID, r)
if !bytes.Equal(line, want) {
t.Fatalf("the wire changed:\n got %s\nwant %s", clip(line), clip(want))
}
+1103 -570
View File
File diff suppressed because it is too large Load Diff