From c38728145bbd849cd2f5b106a294aa2718fecc23 Mon Sep 17 00:00:00 2001 From: Snowyy <142957559+Snowyyyyyy1@users.noreply.github.com> Date: Mon, 5 Oct 2026 01:36:20 +0800 Subject: [PATCH] plugin: a slow reader pauses its stream instead of racing a watchdog (#812) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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. --- .github/workflows/test.yml | 14 + internal/plugin/host.go | 984 ++++++++++++----- internal/plugin/host.js | 316 +++++- internal/plugin/host_flow_test.go | 671 ++++++++++++ internal/plugin/host_send_test.go | 105 +- internal/plugin/host_test.go | 1673 +++++++++++++++++++---------- 6 files changed, 2906 insertions(+), 857 deletions(-) create mode 100644 internal/plugin/host_flow_test.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c8ce22dd3..78ee4f2eb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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 diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 0e1f85729..e54e2aeb7 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -42,20 +42,44 @@ type message struct { Error *struct { Message string `json:"message"` } `json:"error"` - Event string `json:"event"` - Status int `json:"status"` - Headers map[string]string `json:"headers"` - Data string `json:"data"` - Provider string `json:"provider"` - Account string `json:"account"` - Said string `json:"said"` - Level string `json:"level"` - Message string `json:"message"` - Title string `json:"title"` - Variant string `json:"variant"` - Count int `json:"count"` + Event string `json:"event"` + Status int `json:"status"` + Headers map[string]string `json:"headers"` + Data string `json:"data"` + // raw is Data decoded, filled by push so the body reads it without + // decoding the same frame a second time. It is never on the wire. + raw []byte + Provider string `json:"provider"` + Account string `json:"account"` + Said string `json:"said"` + Level string `json:"level"` + Message string `json:"message"` + Title string `json:"title"` + Variant string `json:"variant"` + Count int `json:"count"` } +type callState uint8 + +const ( + callSending callState = iota + callActive + callDraining + callAborting + callReleased +) + +type callEvent uint8 + +const ( + callAccepted callEvent = iota + callAnswered + callCancelled + callConsumed + callAbortWritten + callHostFailed +) + type call struct { done chan message // the answer closed atomic.Bool // done has been answered @@ -66,77 +90,155 @@ type call struct { stream bool mu sync.Mutex queue []message - bytes int // the queued chunks' data, as they came (base64) - over error // why the call's backlog passed its limit + queued int // the queued chunks' decoded bytes + over error // why the call was given up on stopped bool // the call is over for good: nothing more is queued wake chan struct{} // buffered 1: something was queued, or the call is over - // h and id are how the stall watchdog gives the call up: the child is - // told to stop its fetch only while the call is still the host's. + // window is this call's credit in charged bytes (a frame's payload plus + // frameOverhead) and owed is how much of it the child has spent and the + // reader has not yet given back: the child sends no more than window-owed, + // so the queue stays within the window however slow the reader is. A child + // that sends past it broke the protocol (see push). + window int + owed int + // headed is whether the reply's head has been queued: a second one is a + // broken child, not another free line. + headed bool + + // h and id are how the call is given up: the child is told to stop its + // fetch only while the call is still the host's. h *host id int64 - // watch is the stall watchdog: it is armed when the backlog first - // passes the soft watermark, and gives the call up only after stallIdle - // without the reader taking anything. lastRead is the last read that - // returned data (the zero time for none yet); before the first read the - // grace runs from armAt, so a plugin thinking for a long while before - // its reply begins is not taken for a stalled reader. watchGen makes a - // callback from a timer that was stopped or re-armed a no-op. - watch *time.Timer - watchGen int64 - armAt time.Time - lastRead time.Time + // The host lock owns lifecycle transitions; the queue lock also protects + // the persistent answer so notifications never own the vendor outcome. + state callState + terminal *message + + // stopCancel stops the context.AfterFunc that gives the call up when its + // request's context ends, so a body nothing reads or closes still stops + // the upstream fetch. It is cleared the once it is called. + stopCancel func() bool } -// A fetch's backlog is watched, not cut, at the soft watermark: past it the -// call's reader has stallIdle to take something, and only a reader that took -// nothing for that long is given up on. A reply larger than the watermark -// that is read, however slowly, still arrives whole; a consumer that stopped -// is let go of. The hard caps are the memory safety net: past either, however -// fast the reader, the call is given up on, one reply the plugin sends whole -// included. The byte caps bound the queued chunks (base64), not the process, -// and one frame already decoded is held besides. Tests lower them. +// The credit window bounds one call's queue; the budget bounds every live +// call's windows together, so the host admits at most streamBudget/streamWindow +// streaming calls at once (see begin). Both count charged bytes: a frame's +// payload plus frameOverhead, so the window bounds a backlog's frame metadata +// as well as its bytes (the base64 on the wire, about 4/3 of the payload, is +// held besides). The child splits its frames to maxFrame and spends its window +// frame by frame, so a compliant child never sends past the window. callLimit +// bounds every live or retiring call together, so the control backlog (at most +// one entry a call) is bounded too. Tests lower them. var ( - softQueuedBytes = 4 << 20 - softQueuedEvents = 4096 - hardQueuedBytes = 64 << 20 - hardQueuedEvents = 65536 - stallIdle = 10 * time.Second - errStalledReader = errors.New("the plugin kept sending a reply whose reader stopped reading (nothing was read for a while); that request was given up on") - errTooMuchQueued = errors.New("the plugin sent more of a reply than the host queues (too much queued); that request was given up on") + streamWindow = 512 << 10 + streamBudget = 64 << 20 + maxFrame = 64 << 10 + // frameOverhead is what one queued frame costs the window besides its + // bytes: the message struct, its base64 string header and the decoded + // slice behind it. Without it a producer of 1-byte frames could keep a + // window's worth of tiny structs queued — bytes are not the only memory + // a backlog holds. It is charged in the same units as the window, so both + // sides count one number. + frameOverhead = 2048 + rpcReserve = 64 + // maxWireLine bounds one line the child writes: a frame's base64 is well + // under it, and so is any RPC result, so a child that never ends a line + // fails the host rather than making it allocate without bound. + maxWireLine = 32 << 20 + // maxHeadBytes and maxHeadEntries are magpie's own head-envelope policy, + // not HTTP's: a fetch's head carries at most maxHeadBytes of header bytes + // (the UTF-8 bytes of every name and value, plus headEntryCost an entry) + // and maxHeadEntries entries, counted the same on both sides. It keeps a + // vendor's unbounded header set from being a free 0-charge line. A head + // handed to its caller is the caller's to hold besides. + maxHeadBytes = 64 << 10 + maxHeadEntries = 256 + headEntryCost = 4 // a name/value pair's JSON punctuation + errTooManyCalls = errors.New("too many plugin calls are in flight; try again shortly") + errProtocolOverrun = errors.New("the plugin sent more of a reply than the host credited; that request was given up on") + errHostGone = errors.New("the plugin host is gone") + errLineTooLong = errors.New("the plugin host sent a line longer than the host reads") ) +// callLimit is the most calls (streaming, RPC or retiring) the host holds at +// once. It follows from the budget: the streaming share of it plus a reserve +// for RPCs, so the control backlog is bounded by it. +func callLimit() int { return streamLimit() + rpcReserve } + +// streamLimit is how many streaming calls the budget's windows allow at once: +// each holds one window of credit, so their queues together stay within the +// budget. It is counted apart from the call limit, so the RPC reserve is never +// spent on one more stream. +func streamLimit() int { return streamBudget / streamWindow } + // push queues m for the call's reader, without waiting for it. It is false -// when the call's backlog passed its hard limit and m was not taken: the call -// is given up on, and its reader is told why rather than a chunk going -// missing unnoticed. +// when the call was given up on and m was not taken: a compliant child never +// sends past the call's window, so this is a call already stopped, or a child +// that broke the protocol (see errProtocolOverrun). func (c *call) push(m message) bool { - c.mu.Lock() - taken := false - switch { - case c.stopped || c.over != nil: - // a call given up on takes nothing more - default: - // the backlog the queue would hold with this chunk in it, not the - // chunk alone: the memory safety net counts the whole reply - nbytes, nevents := c.bytes+len(m.Data), len(c.queue)+1 - if nbytes > hardQueuedBytes || nevents > hardQueuedEvents { - c.over = errTooMuchQueued - // the resource cap is terminal: the encoding is dropped now, not - // held for a reader that may never come - c.queue, c.bytes = nil, 0 - c.stopWatchLocked() - } else { - c.queue = append(c.queue, m) - c.bytes = nbytes - taken = true - c.armWatchLocked() - } + c.h.mu.Lock() + if c.state != callActive { + c.h.mu.Unlock() + return false } + c.mu.Lock() + if c.stopped || c.over != nil { + c.mu.Unlock() + c.h.mu.Unlock() + return false + } + cost := 0 + switch m.Event { + case "head": + // exactly one head, and it is free: a repeat would be an unbounded + // run of zero-cost lines. Its headers are capped by magpie's own + // envelope, so an unbounded header set is not a free line either. + if c.headed || len(m.Headers) > maxHeadEntries || headCost(m.Headers) > maxHeadBytes { + return c.rejectFrameLocked() + } + c.headed = true + case "chunk": + // a chunk carries the reply's bytes: it must be base64 of one to + // maxFrame bytes. An empty, malformed or oversized frame is refused + // before it is queued, so a flood of empty chunks cannot grow the + // queue without spending the window. The frame is decoded once, here, + // so the body reads it without decoding the same bytes again. + raw, err := base64.StdEncoding.DecodeString(m.Data) + if err != nil || len(raw) == 0 || len(raw) > maxFrame { + return c.rejectFrameLocked() + } + m.raw = raw + cost = len(raw) + frameOverhead + default: + // an event the host does not know: refuse it rather than queue it for + // free + return c.rejectFrameLocked() + } + if c.window > 0 && c.owed+cost > c.window { + // more than the window ahead of the reader: the child broke the + // protocol. The call is given up on and its queue dropped, rather + // than growing without bound. + return c.rejectFrameLocked() + } + c.queue = append(c.queue, m) + c.queued += len(m.raw) + c.owed += cost c.mu.Unlock() + c.h.mu.Unlock() c.notify() - return taken + return true +} + +func (c *call) rejectFrameLocked() bool { + c.mu.Unlock() + stop := c.transitionLocked(callCancelled, errProtocolOverrun, nil) + c.h.mu.Unlock() + if stop != nil { + stop() + } + return false } // pop takes the next chunk queued for the call; false when none is queued. @@ -152,91 +254,29 @@ func (c *call) pop() (message, bool) { if len(c.queue) == 0 { c.queue = nil } - c.bytes -= len(m.Data) - if !c.overSoftLocked() { - // the backlog is back under the watermark: nothing left to watch - c.stopWatchLocked() - } + c.queued -= len(m.raw) return m, true } -// overSoftLocked is whether the backlog passed the soft watermark. -func (c *call) overSoftLocked() bool { - return c.bytes > softQueuedBytes || len(c.queue) > softQueuedEvents -} - -// armWatchLocked starts the stall watchdog when the backlog first passes the -// soft watermark; from then on the call's reader has stallIdle to take -// something. The callback carries the generation, so one left from a timer -// the call has since drained, closed or given up on does nothing. -func (c *call) armWatchLocked() { - if c.watch != nil || c.stopped || c.over != nil || !c.overSoftLocked() { +// credit gives back the bytes the reader took, so the child may send that much +// more of this call's reply. It is what keeps a slow reader's upstream paused +// and a fast reader's flowing, without the host ever cutting a reply short. +func (c *call) credit(n int) { + if n <= 0 { return } - c.watchGen++ - gen := c.watchGen - c.armAt = time.Now() - c.watch = time.AfterFunc(stallIdle, func() { c.onStall(gen) }) -} - -// stopWatchLocked drops the stall watchdog: the call was drained, closed, -// cancelled or given up on, so there is nothing left to watch. Bumping the -// generation makes a callback already under way a no-op. -func (c *call) stopWatchLocked() { - if c.watch != nil { - c.watch.Stop() - c.watch = nil - } - c.watchGen++ - c.armAt = time.Time{} -} - -// noteRead is the reader saying it took data: real progress, unlike a chunk -// arriving or a read that asked for nothing. It only stamps the time under -// the call's own mutex; the watchdog reads it when it fires, so a read -// allocates no timer. -func (c *call) noteRead() { c.mu.Lock() - c.lastRead = time.Now() - c.mu.Unlock() -} - -// onStall is the stall watchdog firing: the backlog passed the soft watermark -// and the reader took nothing for stallIdle, so the call is given up on. What -// it queued is dropped and its reader is told why; the child is told to stop -// only while the call is still the host's to give up (an answered call the -// host has already forgotten is left alone). gen is the generation this -// callback was armed with. -func (c *call) onStall(gen int64) { - c.mu.Lock() - if c.watchGen != gen || c.stopped || c.over != nil || !c.overSoftLocked() { + if c.stopped || c.over != nil { c.mu.Unlock() return } - ref := c.armAt - if c.lastRead.After(ref) { - ref = c.lastRead + if n > c.owed { + n = c.owed } - if wait := stallIdle - time.Since(ref); wait > 0 { - // the reader took something since the grace began: wait the rest - c.watchGen++ - gen = c.watchGen - c.watch = time.AfterFunc(wait, func() { c.onStall(gen) }) - c.mu.Unlock() - return - } - // nothing was read for stallIdle: the call is given up on. Its own body - // ends here, whether or not the host still holds the call. - c.stopWatchLocked() - c.over = errStalledReader - c.queue, c.bytes = nil, 0 + c.owed -= n c.mu.Unlock() - c.notify() - // Whether this call is still the host's is what tells the child to stop: - // forget takes h.mu, so it is taken after c.mu is let go, and an answered - // call the host already forgot is left alone. - if c.h.forget(c.id) { - c.h.abort(c.id) + if n > 0 { + c.h.credit(c, n) } } @@ -247,15 +287,114 @@ func (c *call) givenUp() error { return c.over } -// release ends the call for good: nothing more is queued for it, and what it -// held is dropped, so a body given up on holds nothing. The stall watchdog -// goes with it. -func (c *call) release() { +// watchCtx arms the context watcher that gives the call up when its request's +// context ends, so a body nothing reads or closes still stops the upstream +// fetch. The watcher is registered under h.mu and the callback settles outside +// it, so a context already cancelled can fire before stopCancel is set without +// racing it. +func (c *call) watchCtx(ctx context.Context) { + stop := context.AfterFunc(ctx, func() { c.settle(context.Cause(ctx)) }) + c.h.mu.Lock() + if c.state == callReleased || c.state == callAborting { + c.h.mu.Unlock() + stop() + return + } + c.stopCancel = stop + c.h.mu.Unlock() +} + +// transitionLocked owns cleanup under h.mu, always taking c.mu after it. +// The returned watcher detachment runs outside both locks. A retiring call +// stays registered until its abort write is acknowledged, even when the +// control loop has already taken its work out of the control map. +func (c *call) transitionLocked(event callEvent, why error, answer *message) func() bool { + if c.state == callReleased { + return nil + } + if event == callAccepted { + if c.state == callSending { + c.state = callActive + } + return nil + } + if event == callAnswered && c.state != callActive || + event == callHostFailed && c.state == callDraining || + event == callAbortWritten && c.state != callAborting || + event == callConsumed && c.state == callAborting || + event == callCancelled && c.state == callAborting { + return nil + } c.mu.Lock() + if event == callAnswered { + c.terminal = answer + c.state = callDraining + } else { + if c.state != callDraining && c.over == nil { + c.over = why + } + c.queue, c.queued, c.owed = nil, 0, 0 + if c.terminal == nil && why != nil { + m := message{Error: &struct { + Message string `json:"message"` + }{c.over.Error()}} + c.terminal = &m + } + if event == callCancelled && c.state == callActive && c.stream { + c.state = callAborting + } else { + c.state = callReleased + } + } c.stopped = true - c.queue, c.bytes = nil, 0 - c.stopWatchLocked() + if c.terminal != nil && c.closed.CompareAndSwap(false, true) { + c.done <- *c.terminal + } c.mu.Unlock() + c.h.ctrlMu.Lock() + delete(c.h.ctrl, c.id) + if c.state == callAborting { + c.h.ctrl[c.id] = &ctrl{c: c, abort: true} + c.h.wakeCtrl() + } + c.h.ctrlMu.Unlock() + if c.state != callAborting { + delete(c.h.calls, c.id) + } + if c.state == callReleased { + c.h.releaseSlot(c) + } + // Readers may consume wake, so lifecycle changes broadcast to every + // writer-room waiter rather than competing for a reader notification. + if c.h.outSpace != nil { + close(c.h.outSpace) + c.h.outSpace = nil + } + c.notify() + if c.state == callDraining { + return nil + } + stop := c.stopCancel + c.stopCancel = nil + return stop +} + +func (c *call) transition(event callEvent, why error, answer *message) { + c.h.mu.Lock() + stop := c.transitionLocked(event, why, answer) + c.h.mu.Unlock() + if stop != nil { + stop() + } +} + +func (c *call) settle(why error) { c.transition(callCancelled, why, nil) } +func (c *call) release() { c.transition(callConsumed, nil, nil) } + +func (c *call) result() *message { + c.mu.Lock() + defer c.mu.Unlock() + return c.terminal } // notify wakes the call's reader, without waiting for it. @@ -268,22 +407,79 @@ func (c *call) notify() { // host is one Bun process running host.js. type host struct { - cmd *exec.Cmd - in io.WriteCloser - wmu sync.Mutex - mu sync.Mutex - calls map[int64]*call - next int64 - dead chan struct{} - err error - loaded []Loaded + cmd *exec.Cmd + in io.WriteCloser + // out carries messages to the single writer goroutine that owns the + // child's stdin. A caller enqueues and returns, so it is never parked in + // a blocked write; the queue is bounded by the call limit, so a wedged + // child applies backpressure instead of growing the backlog. + out chan writeReq + outSpace chan struct{} + mu sync.Mutex + calls map[int64]*call + next int64 + dead chan struct{} + err error + loaded []Loaded // renewing is how many sign-ins the host is renewing: stop lets them // end, their new tokens saved, before it kills the host renewing atomic.Int32 - // aborts are the fetch ids to tell the child to stop, taken by one - // goroutine (abortLoop): the child's stdin can be full when it stopped - // reading it, and no caller may wait on that. - aborts chan int64 + // slots bounds every live or retiring call together (see callLimit), so + // neither the calls nor the control backlog can grow without bound. + slots chan struct{} + // streams bounds the streaming calls to the budget's windows (see + // streamLimit), counted apart from slots so the RPC reserve is kept. + streams chan struct{} + // ctrl is the control work waiting for the child: credit to give back + // and fetches to abort. One goroutine (ctrlLoop) writes it, so a fetch's + // reader never blocks on the child's stdin; the backlog is bounded by + // slots, one entry a call, so no control message is dropped. + ctrlMu sync.Mutex + ctrl map[int64]*ctrl + ctrlWake chan struct{} + // ctx ends when the host does, so a control write waiting on the child + // gives up rather than parking on a host that is gone. + ctx context.Context + cancel context.CancelFunc + // maxLine overrides maxWireLine for this host; tests lower it. + maxLine int + // failOnce makes the one failure that ends the host run once, whatever + // noticed it (the stdout reader or the stdin writer). + failOnce sync.Once +} + +// lineLimit is the longest line this host reads from the child. +func (h *host) lineLimit() int { + if h.maxLine > 0 { + return h.maxLine + } + return maxWireLine +} + +// headCost is a head's header cost: the UTF-8 bytes of every name and value, +// plus headEntryCost an entry. The child's side counts the same, so neither +// counts JSON escaping the other does not (a Link header's angle brackets, say) +// and a head one side takes is not refused by the other. +func headCost(h map[string]string) int { + n := 0 + for k, v := range h { + n += len(k) + len(v) + headEntryCost + } + return n +} + +// ctrl is a call's pending control work: credit coalesces, an abort is once. +type ctrl struct { + c *call + abort bool + credit int +} + +// writeReq is one message for the writer: its result goes to done, when the +// sender needs it (a control abort, whose slot comes back once it is written). +type writeReq struct { + b []byte + done chan error } // Loaded is how a plugin fared when the host loaded it. @@ -384,11 +580,10 @@ func (h *host) retire() { }() } -// busy is whether h is answering a call. +// busy is whether h is answering a call: a slot is held by every live or +// retiring call, so this counts a call whose body is still draining too. func (h *host) busy() bool { - h.mu.Lock() - defer h.mu.Unlock() - return len(h.calls) > 0 + return len(h.slots) > 0 } // Running is whether a host is up. @@ -545,7 +740,19 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { if err := cmd.Start(); err != nil { return nil, false, err } - h := &host{cmd: cmd, in: in, calls: map[int64]*call{}, dead: make(chan struct{}), aborts: make(chan int64, 64)} + hctx, hcancel := context.WithCancel(context.Background()) + h := &host{ + cmd: 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 func() { sc := bufio.NewScanner(stderr) sc.Buffer(make([]byte, 64<<10), 4<<20) @@ -554,7 +761,8 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { } }() go h.read(out) - go h.abortLoop() + go h.writerLoop() + go h.ctrlLoop() generation.Add(1) l := Load() @@ -599,33 +807,47 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { func (h *host) read(out io.Reader) { r := bufio.NewReaderSize(out, 1<<20) for { - line, err := r.ReadBytes('\n') + line, err := readLine(r, h.lineLimit()) if len(line) > 0 { var m message if json.Unmarshal(line, &m) == nil { h.dispatch(m) } } + if errors.Is(err, errLineTooLong) { + // a child that never ends a line: stop it rather than allocate + h.fail(fmt.Errorf("the plugin host sent a line longer than %d bytes", h.lineLimit())) + if h.cmd.Process != nil { + _ = h.cmd.Process.Kill() + } + break + } if err != nil { break } } err := h.cmd.Wait() - h.mu.Lock() if err == nil { err = errors.New("the plugin host quit") } - h.err = fmt.Errorf("the plugin host quit: %v", err) - calls := h.calls - h.calls = map[int64]*call{} - h.mu.Unlock() - close(h.dead) - for _, c := range calls { - if c.closed.CompareAndSwap(false, true) { - c.done <- message{Error: &struct { - Message string `json:"message"` - }{h.err.Error()}} + h.fail(fmt.Errorf("the plugin host quit: %v", err)) +} + +// readLine reads one '\n'-terminated line, at most max bytes, so a child that +// never ends a line cannot make the host allocate without bound. It is +// errLineTooLong once max is passed. +func readLine(r *bufio.Reader, max int) ([]byte, error) { + var line []byte + for { + part, err := r.ReadSlice('\n') + if len(line)+len(part) > max { + return nil, errLineTooLong } + line = append(line, part...) + if errors.Is(err, bufio.ErrBufferFull) { + continue + } + return line, err } } @@ -652,96 +874,309 @@ func (h *host) dispatch(m message) { } h.mu.Lock() c := h.calls[m.ID] - if m.Event == "" { - delete(h.calls, m.ID) - } h.mu.Unlock() if c == nil { return } if m.Event != "" { - if c.stream && !c.push(m) { - // its backlog passed its limit: the call is over. Whoever - // takes it out of the host's hands tells the child, once. - if h.forget(m.ID) { - h.abort(m.ID) - } + if c.stream { + c.push(m) } return } - if c.closed.CompareAndSwap(false, true) { - c.done <- m - } + c.transition(callAnswered, nil, &m) } -func (h *host) send(v any) error { +// enqueue hands one message to the writer goroutine. It waits only for room in +// the bounded queue, honoring ctx and the host's own end, so a caller is never +// parked in a blocked write and a host that is gone makes it return. Messages +// keep their order, so an abort is written after the fetch it belongs to. +func (h *host) enqueue(ctx context.Context, v any) error { + return h.enqueueDone(ctx, v, nil) +} + +// enqueueDone is enqueue, asking the writer to report the write's result on +// done (nil for a write that succeeded). +func (h *host) enqueueDone(ctx context.Context, v any, done chan error) error { + return h.enqueueCall(ctx, v, done, nil) +} + +// enqueueCall commits acceptance with the lifecycle while holding h.mu. +// Waiting for writer room owns no lifecycle lock, so cancellation can +// release an unsent call and the next attempt cannot enqueue it. +func (h *host) enqueueCall(ctx context.Context, v any, done chan error, c *call) error { + return h.enqueueOwned(ctx, v, done, c, callSending) +} + +func (h *host) enqueueOwned(ctx context.Context, v any, done chan error, c *call, state callState) error { b, err := json.Marshal(v) if err != nil { return err } - h.wmu.Lock() - defer h.wmu.Unlock() - _, err = h.in.Write(append(b, '\n')) - return err -} - -// abort tells the child to stop a fetch, without waiting for it: the child's -// stdin can be full when it stopped reading it, so the id is queued for -// abortLoop instead. Aborts are best-effort: a full queue drops the id, so -// its upstream fetch may keep running, including an endless stream. -func (h *host) abort(id int64) { - select { - case h.aborts <- id: - default: - } -} - -// abortLoop is the one goroutine that writes the aborts abort queued, until -// the host is gone. -func (h *host) abortLoop() { + req := writeReq{b: append(b, '\n'), done: done} for { + h.mu.Lock() + if !h.alive() { + h.mu.Unlock() + return errHostGone + } + if err := ctx.Err(); err != nil { + h.mu.Unlock() + return err + } + if c != nil && c.state != state { + h.mu.Unlock() + if err := c.givenUp(); err != nil { + return err + } + return errHostGone + } select { + case h.out <- req: + if c != nil && state == callSending { + c.transitionLocked(callAccepted, nil, nil) + } + h.mu.Unlock() + return nil + default: + } + if h.outSpace == nil { + h.outSpace = make(chan struct{}) + } + space := h.outSpace + h.mu.Unlock() + select { + case <-space: + case <-ctx.Done(): + return ctx.Err() case <-h.dead: - return - case id := <-h.aborts: - _ = h.send(map[string]any{"method": "abort", "params": map[string]any{"id": id}}) + return errHostGone } } } -func (h *host) begin(stream bool) (int64, *call) { - c := &call{done: make(chan message, 1), stream: stream} - if stream { - c.wake = make(chan struct{}, 1) - } +func (h *host) tookWrite() { h.mu.Lock() + if h.outSpace != nil { + close(h.outSpace) + h.outSpace = nil + } + h.mu.Unlock() +} + +// writerLoop is the one goroutine that writes the child's stdin, until the +// host is gone or a write fails. A failed write fails the host, so nobody +// waiting on a write result is left waiting for a host that is already gone. +func (h *host) writerLoop() { + for { + select { + case <-h.dead: + return + case req := <-h.out: + h.tookWrite() + if !h.alive() { + if req.done != nil { + req.done <- errHostGone + } + return + } + _, err := h.in.Write(req.b) + if req.done != nil { + req.done <- err + } + if err != nil { + h.fail(fmt.Errorf("writing to the plugin host: %w", err)) + return + } + } + } +} + +// fail ends the host once: its context and dead channel, every message still +// queued for the writer answered with err, and every incomplete call let go — +// so no caller waits for a write that will never come, and a body nothing reads +// or closes cannot keep its buffer or slot. +func (h *host) fail(err error) { + h.failOnce.Do(func() { + h.mu.Lock() + if h.err == nil { + h.err = err + } + why := h.err + close(h.dead) + var stops []func() bool + for _, c := range h.calls { + if stop := c.transitionLocked(callHostFailed, why, nil); stop != nil { + stops = append(stops, stop) + } + } + h.mu.Unlock() + for _, stop := range stops { + stop() + } + h.cancel() + h.dropCtrl() + drain: + for { + select { + case req := <-h.out: + if req.done != nil { + req.done <- err + } + default: + break drain + } + } + }) +} + +// credit queues the bytes the reader gave back for a call. The control loop +// coalesces them with any already waiting, so a fast reader's many small +// credits become one write. +func (h *host) credit(c *call, n int) { + h.mu.Lock() + defer h.mu.Unlock() + h.ctrlMu.Lock() + if !h.alive() || c.state != callActive { + h.ctrlMu.Unlock() + return + } + ct := h.ctrl[c.id] + if ct == nil { + ct = &ctrl{c: c} + h.ctrl[c.id] = ct + } + ct.credit += n + h.ctrlMu.Unlock() + h.wakeCtrl() +} + +// abort queues a fetch to stop. It is not dropped: the call keeps its slot +// until the abort is written (or the host dies), so a child that stopped +// reading its stdin cannot grow the backlog past the call limit. +func (h *host) abort(c *call) { + c.settle(context.Canceled) +} + +func (h *host) wakeCtrl() { + select { + case h.ctrlWake <- struct{}{}: + default: + } +} + +// ctrlLoop is the one goroutine that writes control work to the child, until +// the host is gone. +func (h *host) ctrlLoop() { + for { + select { + case <-h.dead: + h.dropCtrl() + return + case <-h.ctrlWake: + } + h.pumpCtrl() + } +} + +// pumpCtrl writes the control work waiting, an abort before a credit, until +// none is left. A call settling with an abort owed keeps its slot until that +// abort's write is known (written, or failed with the host), so a child that +// stopped reading its stdin cannot grow the backlog past the call limit. +func (h *host) pumpCtrl() { + for { + h.ctrlMu.Lock() + var ct *ctrl + for id, v := range h.ctrl { + ct = v + delete(h.ctrl, id) + break + } + h.ctrlMu.Unlock() + if ct == nil { + return + } + if ct.abort { + done := make(chan error, 1) + if err := h.enqueueOwned(h.ctx, map[string]any{"method": "abort", "params": map[string]any{"id": ct.c.id}}, done, ct.c, callAborting); err == nil { + select { + case <-done: + case <-h.dead: + } + } + ct.c.transition(callAbortWritten, nil, nil) + } + if ct.credit > 0 { + _ = h.enqueueOwned(h.ctx, map[string]any{"method": "credit", "params": map[string]any{"id": ct.c.id, "n": ct.credit}}, nil, ct.c, callActive) + } + } +} + +// dropCtrl drops work after lifecycle transitions have released failed calls. +func (h *host) dropCtrl() { + h.ctrlMu.Lock() + defer h.ctrlMu.Unlock() + for id := range h.ctrl { + delete(h.ctrl, id) + } +} + +// begin takes a call's admission slot and registers it. It is errTooManyCalls +// when the host already holds its limit of live and retiring calls, so a new +// call fails clearly rather than a legitimate accepted reply being cut short. +func (h *host) begin(stream bool) (int64, *call, error) { + h.mu.Lock() + defer h.mu.Unlock() + if !h.alive() { + return 0, nil, errHostGone + } + c := &call{done: make(chan message, 1), stream: stream, wake: make(chan struct{}, 1), state: callSending} + if stream { + c.window = streamWindow + // a stream holds one window of the budget as well as a call slot, so + // the RPC reserve is never spent on one more stream + select { + case h.streams <- struct{}{}: + default: + return 0, nil, errTooManyCalls + } + } + select { + case h.slots <- struct{}{}: + default: + if stream { + <-h.streams + } + return 0, nil, errTooManyCalls + } h.next++ id := h.next c.h, c.id = h, id h.calls[id] = c - h.mu.Unlock() - return id, c + return id, c, nil } -// forget takes the call out of the host's hands, and is true when it was -// still there: the one that takes it out is the one that tells the child. -func (h *host) forget(id int64) bool { - h.mu.Lock() - _, ok := h.calls[id] - delete(h.calls, id) - h.mu.Unlock() - return ok +// releaseSlot is called only by the transition that enters released. +func (h *host) releaseSlot(c *call) { + <-h.slots + if c.stream { + <-h.streams + } } // call asks the host method with params and reads its answer into out. func (h *host) call(ctx context.Context, method string, params, out any) error { - id, c := h.begin(false) - if err := h.send(map[string]any{"id": id, "method": method, "params": params}); err != nil { - h.forget(id) + id, c, err := h.begin(false) + if err != nil { + return err + } + if err := h.enqueueCall(ctx, map[string]any{"id": id, "method": method, "params": params}, nil, c); err != nil { + c.settle(err) return err } select { case m := <-c.done: + c.release() if m.Error != nil { return errors.New(m.Error.Message) } @@ -750,8 +1185,23 @@ func (h *host) call(ctx context.Context, method string, params, out any) error { } return nil case <-ctx.Done(): - h.forget(id) + c.settle(ctx.Err()) return ctx.Err() + case <-h.dead: + // the host is gone: a waiter must not be left waiting for an answer + // that will never come, even with a context that never ends + m := c.result() + c.release() + if m != nil { + if m.Error != nil { + return errors.New(m.Error.Message) + } + if out != nil && len(m.Result) > 0 { + return json.Unmarshal(m.Result, out) + } + return nil + } + return errHostGone } } @@ -856,22 +1306,25 @@ func Fetch(ctx context.Context, r FetchRequest) (*http.Response, error) { if r.Proxy == "" { r.Proxy = proxyOf(ctx) } - id, c := h.begin(true) + id, c, err := h.begin(true) + if err != nil { + return nil, err + } params := struct { FetchRequest - Body []byte `json:"body,omitempty"` - }{r, r.Body} - if err := h.send(map[string]any{"id": id, "method": "fetch", "params": params}); err != nil { - h.forget(id) + Body []byte `json:"body,omitempty"` + Window int `json:"window"` + }{r, r.Body, streamWindow} + c.watchCtx(ctx) + err = h.enqueueCall(ctx, map[string]any{"id": id, "method": "fetch", "params": params}, nil, c) + if err != nil { + c.settle(err) return nil, err } head, answer, err := c.headRead(ctx) if err != nil { - // no answer: the call is still the host's to give up, and its - // taker is the one that tells the child - if answer == nil && h.forget(id) { - h.abort(id) - } + // Settling either releases a completed answer or stops an active fetch. + c.settle(err) return nil, err } b := &body{h: h, id: id, c: c, ctx: ctx, answer: answer, closed: make(chan struct{})} @@ -904,6 +1357,12 @@ func (c *call) headRead(ctx context.Context) (head message, answer *message, err if err := c.givenUp(); err != nil { return message{}, nil, err } + if m := c.result(); m != nil { + if m.Error != nil { + return message{}, m, errors.New(m.Error.Message) + } + return message{}, m, errors.New("the plugin answered no response") + } select { case <-c.wake: case m := <-c.done: @@ -917,6 +1376,10 @@ func (c *call) headRead(ctx context.Context) (head message, answer *message, err return message{}, &m, errors.New("the plugin answered no response") case <-ctx.Done(): return message{}, nil, ctx.Err() + case <-c.h.dead: + // the host is gone: no head is coming, so the fetch gives up + // rather than waiting on a context that may never end + continue } } } @@ -933,6 +1396,7 @@ type body struct { c *call ctx context.Context buf []byte // the chunk in hand, not yet read + frame int // the frame in hand's overhead, credited when it is done answer *message // the call's answer, once it came closed chan struct{} // closed when the body is closed or given up on once sync.Once @@ -957,20 +1421,20 @@ func (b *body) Read(p []byte) (int, error) { if len(b.buf) > 0 { n := copy(p, b.buf) b.buf = b.buf[n:] - if n > 0 { - // real progress: the reader is taking the reply, so the - // stall watchdog's grace starts over - b.c.noteRead() - } + // the bytes are the reader's now: give the child that much + // credit back, so a slow reader pauses its upstream and a fast + // one keeps it flowing + b.c.credit(n) return n, nil } if m, ok := b.c.pop(); ok { - chunk, err := base64.StdEncoding.DecodeString(m.Data) - if err != nil { - b.giveUp() - return 0, err + if b.frame > 0 { + // the frame that was in hand is done: its overhead comes back + // with the bytes already credited for it + b.c.credit(b.frame) } - b.buf = chunk + b.buf = m.raw + b.frame = frameOverhead continue } if err := b.c.givenUp(); err != nil { @@ -979,11 +1443,16 @@ func (b *body) Read(p []byte) (int, error) { } if b.answer != nil { // the answer ends the reply: its error, or the end of it + b.c.release() if b.answer.Error != nil { return 0, errors.New(b.answer.Error.Message) } return 0, io.EOF } + if m := b.c.result(); m != nil { + b.answer = m + continue + } select { case <-b.c.wake: case m := <-b.c.done: @@ -995,6 +1464,8 @@ func (b *body) Read(p []byte) (int, error) { case <-b.ctx.Done(): b.giveUp() return 0, b.ctx.Err() + case <-b.h.dead: + continue } } } @@ -1012,9 +1483,10 @@ func (b *body) Close() error { func (b *body) giveUp() { b.once.Do(func() { close(b.closed) - b.c.release() - if b.h.forget(b.id) { - b.h.abort(b.id) + why := errBodyClosed + if err := context.Cause(b.ctx); err != nil { + why = err } + b.c.settle(why) }) } diff --git a/internal/plugin/host.js b/internal/plugin/host.js index c7679e015..f4e631b54 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -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}` } }) diff --git a/internal/plugin/host_flow_test.go b/internal/plugin/host_flow_test.go new file mode 100644 index 000000000..adefd1941 --- /dev/null +++ b/internal/plugin/host_flow_test.go @@ -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") + } +} diff --git a/internal/plugin/host_send_test.go b/internal/plugin/host_send_test.go index 152d6f5ed..dc258ef7b 100644 --- a/internal/plugin/host_send_test.go +++ b/internal/plugin/host_send_test.go @@ -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&\"c\" — 你好