Repository navigation
fix(ui-server): defer eligible result observations until inference dispatch - #4395
schlessera wants to merge 16 commits into
Conversation
Independent reviewReviewed head e7385d7 against base 61b8b2e. Reviewer: agent. 13 findings: 0 fixed, 0 filed, 0 rejected, 13 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "e7385d7710a65b7e2e445c540bb889df40359918",
"base": "61b8b2e052fbb35b2a544ee6c42849d8fa592581",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-egress.ts:307 reads the current pause when upstream headers arrive. If the observation hits a cap and the owner selects Continue before those headers arrive, responseAllowed returns true. The relay forwards the capped request’s response and records it as completed. The refusal must belong to that request’s observation verdict."
},
{
"summary": "F2 packages/ui-sdk/src/server/inference-relay.ts:186 returns a credential error before prepareDispatch claims the armed observation. A fast credential failure can therefore deliver a 503 to the still-running worker before its tool-result observation even starts. Early admission and body-size refusals take the same path."
},
{
"summary": "F3 packages/ui-sdk/src/server/inference-relay.ts:220 returns the cap denial after finish submits the egress record. The FULL write is still pending in turn-egress.ts:148. A crash at that point can leave the scope pause on disk with no record of the refused in-flight request. The durability test checks only the scope row."
},
{
"summary": "F4 packages/ui-server/src/brain/turn-scope.ts:267 trusts freeze() returning true as confirmation for the whole process tree. The production freezer checks only the PIDs enumerated before signaling (worker-freezer.ts:43–48). A child created during that scan can remain running when dispatch proceeds. The runtime test substitutes a single-PID freezer."
},
{
"summary": "F5 packages/ui-server/src/brain/turn-journal.ts:720 deletes the entire call entry on its first result, even when duplicate starts made its identity ambiguous. A different call finishing next can see an empty calls map and arm while the duplicate is still pending. The lasting-producer check excludes the current turn."
},
{
"summary": "F6 packages/ui-server/src/brain/deferred-observation.ts:11 lets dispatch claim an expired deadline whenever the timer callback has not run yet. Synchronous request decoding or an event-loop stall can put dispatch past 50 ms in the same turn. Without an elapsed-time check, the late request still leaves before the verdict."
},
{
"summary": "F7 packages/ui-server/src/brain/turn-scope.ts:353 allows deferral after a prior unreadable path has made the journal partial and the scope observer has set changedPaths and observedBytes to null. The turn can speculate again even though its file and byte cap measurements are unknown."
},
{
"summary": "F8 packages/ui-server/src/brain/turn-journal.ts:595 waits for the global journal queue on every governed inference that has no matching armed result. Even a first request or a proven-read continuation can now wait for another session’s managed-worktree initialization at line 746. The #4293 harness supplies no journal, so its dispatch timings omit this new wait."
},
{
"summary": "F9 packages/ui-server/src/brain/turn-journal.ts:355 extends every journal hold until all active turns’ scope writes settle. A slow FULL scope save now keeps workers stopped even for ordinary immediate, periodic and finish observations. This changes the existing hold schedule beyond the deferred response that needs the durable verdict."
},
{
"summary": "F10 packages/ui-server/tests/deferred-freeze-runtime.test.ts:50 sets committed in onObservation. That callback runs at turn-journal.ts:550, before the native observation and worktree commits at lines 554–555. PROCESS_CANNOT_RESUME_BEFORE_COMMIT therefore accepts a resume during the commit it claims to protect."
},
{
"summary": "F11 packages/ui-server/src/brain/turn-journal.ts:592 samples only the current in-flight count. If two relay requests overlap after arming and one disconnects before the other finishes reading its body, the count returns to one and the survivor can speculate. Nothing remembers that the continuation was ambiguous."
},
{
"summary": "F12 packages/ui-server/src/brain/turn-scope.ts:336 ignores a false or void freeze receipt from a worker admitted during a deferred observation. The initial dispatch confirmed only the original worker. Capture can now complete and release the response while the newly admitted worker’s stop was never confirmed."
},
{
"summary": "F13 packages/ui-server/src/brain/turn-egress.ts:272 registers eligibility from scope and request count alone. Pi turns using OpenAI routes can arm the 50 ms window even though their relay cannot send a Messages continuation. The unsupported transport is discovered only after the worker has been allowed to run past the result."
}
]
} |
Independent reviewReviewed head e7385d7 against base e46e01c. Reviewer: agent. 13 findings: 9 fixed, 3 filed, 1 rejected, 0 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "e7385d7710a65b7e2e445c540bb889df40359918",
"base": "e46e01ccd8ffe75d71a6abffdddfe662c8271c80",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-egress.ts:307 reads the current pause when upstream headers arrive. If the observation hits a cap and the owner selects Continue before those headers arrive, responseAllowed returns true. The relay forwards the capped request’s response and records it as completed. The refusal must belong to that request’s observation verdict.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F2 packages/ui-sdk/src/server/inference-relay.ts:186 returns a credential error before prepareDispatch claims the armed observation. A fast credential failure can therefore deliver a 503 to the still-running worker before its tool-result observation even starts. Early admission and body-size refusals take the same path.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F3 packages/ui-sdk/src/server/inference-relay.ts:220 returns the cap denial after finish submits the egress record. The FULL write is still pending in turn-egress.ts:148. A crash at that point can leave the scope pause on disk with no record of the refused in-flight request. The durability test checks only the scope row.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4401"
},
{
"summary": "F4 packages/ui-server/src/brain/turn-scope.ts:267 trusts freeze() returning true as confirmation for the whole process tree. The production freezer checks only the PIDs enumerated before signaling (worker-freezer.ts:43–48). A child created during that scan can remain running when dispatch proceeds. The runtime test substitutes a single-PID freezer.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4400"
},
{
"summary": "F5 packages/ui-server/src/brain/turn-journal.ts:720 deletes the entire call entry on its first result, even when duplicate starts made its identity ambiguous. A different call finishing next can see an empty calls map and arm while the duplicate is still pending. The lasting-producer check excludes the current turn.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F6 packages/ui-server/src/brain/deferred-observation.ts:11 lets dispatch claim an expired deadline whenever the timer callback has not run yet. Synchronous request decoding or an event-loop stall can put dispatch past 50 ms in the same turn. Without an elapsed-time check, the late request still leaves before the verdict.",
"disposition": "rejected",
"reason": "Whichever of dispatch or the late timer claims, the same hold is taken at the same instant, so the unobserved window is identical and the request is still the verified continuation (triage)."
},
{
"summary": "F7 packages/ui-server/src/brain/turn-scope.ts:353 allows deferral after a prior unreadable path has made the journal partial and the scope observer has set changedPaths and observedBytes to null. The turn can speculate again even though its file and byte cap measurements are unknown.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F8 packages/ui-server/src/brain/turn-journal.ts:595 waits for the global journal queue on every governed inference that has no matching armed result. Even a first request or a proven-read continuation can now wait for another session’s managed-worktree initialization at line 746. The #4293 harness supplies no journal, so its dispatch timings omit this new wait.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F9 packages/ui-server/src/brain/turn-journal.ts:355 extends every journal hold until all active turns’ scope writes settle. A slow FULL scope save now keeps workers stopped even for ordinary immediate, periodic and finish observations. This changes the existing hold schedule beyond the deferred response that needs the durable verdict.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F10 packages/ui-server/tests/deferred-freeze-runtime.test.ts:50 sets committed in onObservation. That callback runs at turn-journal.ts:550, before the native observation and worktree commits at lines 554–555. PROCESS_CANNOT_RESUME_BEFORE_COMMIT therefore accepts a resume during the commit it claims to protect.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F11 packages/ui-server/src/brain/turn-journal.ts:592 samples only the current in-flight count. If two relay requests overlap after arming and one disconnects before the other finishes reading its body, the count returns to one and the survivor can speculate. Nothing remembers that the continuation was ambiguous.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
},
{
"summary": "F12 packages/ui-server/src/brain/turn-scope.ts:336 ignores a false or void freeze receipt from a worker admitted during a deferred observation. The initial dispatch confirmed only the original worker. Capture can now complete and release the response while the newly admitted worker’s stop was never confirmed.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4400"
},
{
"summary": "F13 packages/ui-server/src/brain/turn-egress.ts:272 registers eligibility from scope and request count alone. Pi turns using OpenAI routes can arm the 50 ms window even though their relay cannot send a Messages continuation. The unsupported transport is discovered only after the worker has been allowed to run past the result.",
"disposition": "fixed",
"commit": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0"
}
]
} |
Independent reviewReviewed head 164ec36 against base e46e01c. Reviewer: agent. 10 findings: 0 fixed, 0 filed, 0 rejected, 10 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0",
"base": "e46e01ccd8ffe75d71a6abffdddfe662c8271c80",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-journal.ts:632 authorizes dispatch from boundary.settled even when the verdict is false. With a token-count request and a files_changed cap, the fixture returned dispatch=true and responseReady=false while the turn was paused. The provider receives a request after the immediate observation has already refused it."
},
{
"summary": "F2 packages/ui-sdk/src/server/inference-relay.ts:120 returns 405 or 403 for a wrong method or unauthorized route before creating an operation or entering the answer gate. With a result armed, the running worker can receive that response before its observation starts. The request also goes unseen by the ambiguity latch."
},
{
"summary": "F3 packages/ui-server/src/brain/turn-journal.ts:366 handles a thrown speculative freeze by calling after(false), which kills the worker and rejects the result without running its observation. The production process-tree and cgroup freezers both throw on timeout. A fixture freezer that threw once and would then succeed received one stop attempt and one kill."
},
{
"summary": "F4 packages/ui-server/src/brain/turn-journal.ts:617 detects overlapping requests only while their result boundary is in the deferred or claimed map. If the first observation commits while its request still awaits headers, a second request can overlap and close without setting immediateOnly. After both requests closed, the fixture armed the next result despite the ambiguous parallel chains."
},
{
"summary": "F5 packages/ui-server/src/brain/turn-journal.ts:742 treats a reused tool ID as new once toolEnded deletes the first entry. A retry of the first Messages body then matches the second result by ID and can dispatch speculatively. The fixture armed and dispatched for the reused ID. The per-turn identity latch covers only overlapping starts."
},
{
"summary": "F6 packages/ui-server/src/brain/turn-scope.ts:273 treats scope-write settlement as proof of persistence. The save returns false when its UPDATE matches no row, and the tail discards that result. With a missing turn_scope row, the fixture dispatched, hit a cap, and stayed paused in memory with no persisted receipt for Continue or Stop."
},
{
"summary": "F7 packages/ui-server/src/brain/turn-journal.ts:329 calls summary() synchronously before taking the hold. A malformed persisted scope summary throws during JSON parsing. In the fixture, toolEnded threw without returning a promise, taking a stop, or arming a deadline. The bridge's promise catch therefore cannot contain the failure and the required observation is skipped."
},
{
"summary": "F8 packages/ui-sdk/src/server/inference-relay.ts:227 finishes the egress record as failed before checking the request's cap verdict. If an upstream fetch fails during a deferred observation that hits a cap, the relay answers deferred_observation_refused, but its second finish is a no-op. Even a fully committed connection record reports upstream_unreachable instead of the refusal."
},
{
"summary": "F9 scripts/native-proof/admission-join.ts:65 leaves the 50 ms fallback active in the cells labelled removed. At 50 ms it can race the measured request, and at 500 ms it has already taken the hold. Those cells measure admission with a fallback observation and cannot establish the no-hold comparison required by #4293."
},
{
"summary": "F10 packages/ui-server/tests/deferred-freeze.test.ts:117 checks for commit only after awaiting both the response and the observation. If a false or void stop incorrectly permits immediate upstream dispatch while the response gate still waits for commit, every assertion passes. The test needs to check upstream arrival while the fallback observation is held."
}
]
} |
…x/4292-deferred-freeze # Conflicts: # packages/ui-server/src/brain/turn-journal.ts
Independent reviewReviewed head 93989b0 against base 3bf5a9e. Reviewer: agent. 4 findings: 0 fixed, 0 filed, 0 rejected, 4 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f",
"base": "3bf5a9e29d804f341b3d64f6dbee1ccec5ff2e96",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-journal.ts:806 deletes a refused boundary even when the fallback deadline claimed it before any request arrived. A buffered continuation accepted after the cap commits, while the turn is still paused, finds no boundary. Both dispatch() and responseReady() return true, so the request can go upstream before Continue."
},
{
"summary": "F2 packages/ui-server/src/brain/turn-journal.ts:810 starts the immediate observation without retaining its promise for the relay. If the arming predicate throws, or a previous false/void stop latched immediate-only, a continuation arriving during an unconfirmed hold finds no boundary. It can go upstream and receive a response while its checkpoint is still pending. A3 covers only the first, armed result."
},
{
"summary": "F3 packages/ui-sdk/src/server/inference-relay.ts:141 gates a false admission result but lets a rejected admit() escape the handler. The safety snapshot read in egress-proxy.ts:312 can throw on an invalid live safety revision. Bun can then send a 500 to the running worker before its armed observation starts. The second admission at line 213 has the same gap."
},
{
"summary": "F4 packages/ui-server/src/brain/turn-journal.ts:374 treats a registered observer and an unchanged flag as a confirmed stop. If principal authority expires between canDefer() and the scope observer’s turn.current() check, turn-scope.ts:261 skips the worker entirely. The flag stays true and dispatch sends the request even though no worker acknowledged a stop."
}
]
} |
Independent reviewReviewed head 164ec36 against base 3bf5a9e. Reviewer: agent. 10 findings: 3 fixed, 7 filed, 0 rejected, 0 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "164ec363a1f074b3492a364a0fa2a3d4af56b8e0",
"base": "3bf5a9e29d804f341b3d64f6dbee1ccec5ff2e96",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-journal.ts:632 authorizes dispatch from boundary.settled even when the verdict is false. With a token-count request and a files_changed cap, the fixture returned dispatch=true and responseReady=false while the turn was paused. The provider receives a request after the immediate observation has already refused it.",
"disposition": "fixed",
"commit": "93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f"
},
{
"summary": "F2 packages/ui-sdk/src/server/inference-relay.ts:120 returns 405 or 403 for a wrong method or unauthorized route before creating an operation or entering the answer gate. With a result armed, the running worker can receive that response before its observation starts. The request also goes unseen by the ambiguity latch.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4427"
},
{
"summary": "F3 packages/ui-server/src/brain/turn-journal.ts:366 handles a thrown speculative freeze by calling after(false), which kills the worker and rejects the result without running its observation. The production process-tree and cgroup freezers both throw on timeout. A fixture freezer that threw once and would then succeed received one stop attempt and one kill.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4400"
},
{
"summary": "F4 packages/ui-server/src/brain/turn-journal.ts:617 detects overlapping requests only while their result boundary is in the deferred or claimed map. If the first observation commits while its request still awaits headers, a second request can overlap and close without setting immediateOnly. After both requests closed, the fixture armed the next result despite the ambiguous parallel chains.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4427"
},
{
"summary": "F5 packages/ui-server/src/brain/turn-journal.ts:742 treats a reused tool ID as new once toolEnded deletes the first entry. A retry of the first Messages body then matches the second result by ID and can dispatch speculatively. The fixture armed and dispatched for the reused ID. The per-turn identity latch covers only overlapping starts.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4427"
},
{
"summary": "F6 packages/ui-server/src/brain/turn-scope.ts:273 treats scope-write settlement as proof of persistence. The save returns false when its UPDATE matches no row, and the tail discards that result. With a missing turn_scope row, the fixture dispatched, hit a cap, and stayed paused in memory with no persisted receipt for Continue or Stop.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4401"
},
{
"summary": "F7 packages/ui-server/src/brain/turn-journal.ts:329 calls summary() synchronously before taking the hold. A malformed persisted scope summary throws during JSON parsing. In the fixture, toolEnded threw without returning a promise, taking a stop, or arming a deadline. The bridge's promise catch therefore cannot contain the failure and the required observation is skipped.",
"disposition": "fixed",
"commit": "93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f"
},
{
"summary": "F8 packages/ui-sdk/src/server/inference-relay.ts:227 finishes the egress record as failed before checking the request's cap verdict. If an upstream fetch fails during a deferred observation that hits a cap, the relay answers deferred_observation_refused, but its second finish is a no-op. Even a fully committed connection record reports upstream_unreachable instead of the refusal.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4401"
},
{
"summary": "F9 scripts/native-proof/admission-join.ts:65 leaves the 50 ms fallback active in the cells labelled removed. At 50 ms it can race the measured request, and at 500 ms it has already taken the hold. Those cells measure admission with a fallback observation and cannot establish the no-hold comparison required by #4293.",
"disposition": "filed",
"issue": "schlessera/brain-kit#4429"
},
{
"summary": "F10 packages/ui-server/tests/deferred-freeze.test.ts:117 checks for commit only after awaiting both the response and the observation. If a false or void stop incorrectly permits immediate upstream dispatch while the response gate still waits for commit, every assertion passes. The test needs to check upstream arrival while the fallback observation is held.",
"disposition": "fixed",
"commit": "93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f"
}
]
} |
Independent reviewReviewed head 93989b0 against base 1f827e5. Reviewer: agent. 4 findings: 4 fixed, 0 filed, 0 rejected, 0 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f",
"base": "1f827e50ad09be6a54dcf07ca753075dac869056",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-journal.ts:806 deletes a refused boundary even when the fallback deadline claimed it before any request arrived. A buffered continuation accepted after the cap commits, while the turn is still paused, finds no boundary. Both dispatch() and responseReady() return true, so the request can go upstream before Continue.",
"disposition": "fixed",
"commit": "435896e36b6384190c95ae042c2a9cb259e4162f"
},
{
"summary": "F2 packages/ui-server/src/brain/turn-journal.ts:810 starts the immediate observation without retaining its promise for the relay. If the arming predicate throws, or a previous false/void stop latched immediate-only, a continuation arriving during an unconfirmed hold finds no boundary. It can go upstream and receive a response while its checkpoint is still pending. A3 covers only the first, armed result.",
"disposition": "fixed",
"commit": "435896e36b6384190c95ae042c2a9cb259e4162f"
},
{
"summary": "F3 packages/ui-sdk/src/server/inference-relay.ts:141 gates a false admission result but lets a rejected admit() escape the handler. The safety snapshot read in egress-proxy.ts:312 can throw on an invalid live safety revision. Bun can then send a 500 to the running worker before its armed observation starts. The second admission at line 213 has the same gap.",
"disposition": "fixed",
"commit": "435896e36b6384190c95ae042c2a9cb259e4162f"
},
{
"summary": "F4 packages/ui-server/src/brain/turn-journal.ts:374 treats a registered observer and an unchanged flag as a confirmed stop. If principal authority expires between canDefer() and the scope observer’s turn.current() check, turn-scope.ts:261 skips the worker entirely. The flag stays true and dispatch sends the request even though no worker acknowledged a stop.",
"disposition": "fixed",
"commit": "435896e36b6384190c95ae042c2a9cb259e4162f"
}
]
} |
Independent reviewReviewed head 435896e against base 1f827e5. Reviewer: agent. 14 findings: 0 fixed, 0 filed, 0 rejected, 14 without a disposition. {
"version": 1,
"kind": "brain-review-receipt",
"pr": 4395,
"head": "435896e36b6384190c95ae042c2a9cb259e4162f",
"base": "1f827e50ad09be6a54dcf07ca753075dac869056",
"reviewer": "agent",
"outcome": "findings",
"findings": [
{
"summary": "F1 packages/ui-server/src/brain/turn-journal.ts:888 allows dispatch when the generation counters match even if the request carries the result of a call still pending in the journal. The relay socket and SDK result stream are independent. If the continuation arrives first, it can reach upstream and receive an answer before toolEnded registers its observation or any worker acknowledges a stop."
},
{
"summary": "F2 packages/ui-server/src/brain/turn-journal.ts:870 checks denials only through the generation captured at arrival. If a request is waiting for upstream headers when a later result trips a cap, responseReady waits for that commit and then returns true while the turn is paused. The relay forwards the response, which the worker can read after Continue."
},
{
"summary": "F3 packages/ui-sdk/src/server/inference-relay.ts:319 checks only egress authority when delivering each stream chunk and EOF. A tool result can start an immediate observation after the Response was returned while an upstream read is pending. The next chunk can reach the worker socket during that observation, including when the immediate hold has no confirmed stop."
},
{
"summary": "F4 packages/ui-server/src/brain/turn-egress.ts:425 excludes the worker’s CLI provider relay from request tracking and the result gate. Its paid completion requests use relayed(). One can dispatch and answer during an armed result window without claiming the hold, while the inference relay can still treat a separate Messages request as the sole continuation."
},
{
"summary": "F5 packages/ui-sdk/src/server/inference-relay.ts:136 puts the gate inside Bun’s fetch handler. Bun 1.4.4 can write its own 413 for an oversized declared body or an informational 100 Continue before invoking that handler. Either answer can reach the worker while the result is still armed. The body-size test covers the application’s smaller limit."
},
{
"summary": "F6 packages/ui-sdk/src/server/inference-relay.ts:262 waits for prepareDispatch after the final session-binding admission. On the immediate path this can span the entire observation. Once it commits, dispatchReady can succeed and skip re-admission even if a session binding started or failed during the wait. The typed dispatch fence does not read the bridge’s pending or failed binding."
},
{
"summary": "F7 packages/ui-server/src/brain/turn-egress.ts:464 receives the route at arrival but passes it to the gate only during body preparation. A token-count request is already known to be ineligible, yet its admission, body read and credential lookup can leave the worker running until the fallback timer."
},
{
"summary": "F8 packages/ui-sdk/src/server/inference-relay.ts:161 awaits the final responseReady boolean, then passes the Response through further promise continuations. A queued SDK result can increment required after the check and before Bun receives the Response. No synchronous generation check accompanies the handoff, so even a non-streaming relay answer can escape with a new observation pending."
},
{
"summary": "F9 packages/ui-server/src/brain/turn-journal.ts:503 reads the full SQLite journal summary before checking an unsupported relay, multiple active turns or a pending sibling. These synchronous queries now precede even the immediate stop. They also precede creation of the 50 ms deadline, so time spent waiting for SQLite extends the unobserved window."
},
{
"summary": "F10 packages/ui-server/src/brain/turn-journal.ts:505 permanently sets immediateOnly when dispatch notices an expired deadline. When the timer callback wins instead, it clears only the armed observation. The same missed deadline therefore forces every later eligible result in the turn back onto the immediate schedule depending on event-loop ordering."
},
{
"summary": "F11 packages/ui-server/src/brain/turn-journal.ts:1017 creates a gate even for a tool result outside an active journal turn. With a journal but no governed hold, finish returns at line 1163 before deleting it, and no relay cleanup exists. Those gates accumulate for the host lifetime and every subsequent hold or tool event scans them in flushDeferred."
},
{
"summary": "F12 packages/ui-server/src/brain/deferred-observation.ts:32 counts only assistant blocks whose type is tool_use. It ignores unknown blocks and never compares the tool name with the journaled call. A matching ID with contradictory call identity can therefore qualify for speculative dispatch despite the requirement that unknown Messages shapes take the immediate hold."
},
{
"summary": "F13 packages/ui-server/src/brain/turn-journal.ts:899 removes a disconnected operation from the relay set but never releases its responseReady waiter. If a native checkpoint stalls, cancelled handlers and their buffered request or upstream response stay reachable via gateWaiters until that checkpoint settles. Repeated disconnects accumulate these waits on one turn."
},
{
"summary": "F14 packages/ui-sdk/src/server/inference-relay.ts:290 constructs a streaming success response after waiting on the journal, using a header charge taken before the wait. If egress authority was withdrawn during that interval, the next typed fence is inside the stream reader. The relay can report a forwarded success and surface a stream error in place of the typed HTTP refusal."
}
]
} |
Refs #4292
Refs #4293
What changed
Eligible Messages continuations overlap their per-result observation with upstream inference. One synchronous predicate runs at arming and dispatch; unknown coverage, unsupported routes, an expired deadline or ambiguous work takes the existing immediate hold. Duplicate starts and second arrivals after arming remain latched as ambiguous even after their entries disappear. Reused IDs after completion remain tracked in #4427.
Each turn retains required and committed result generations, a sticky failure state and denied generations. Each arrival binds the generations pending at that instant. One branded exit gates every response, including wrong methods/routes and thrown admission failures. A cap's response stays refused even if Continue is accepted before upstream headers arrive. False or void stop acknowledgements fall back to the base immediate observation without adding a turn-abort path. Only confirmed deferred stops wait for scope writes; ordinary inference with no pending results and live scope authority never waits for unrelated journal work.
Why this shape
This implements #4292's 2026-11-20 Option A ruling and review round 3's G1–G4 / S1–S2 design, retaining the eligibility predicate and atomic observation claim. Relay configuration establishes Messages support, and synchronous operation-creation notifications establish uniqueness; an in-flight count is not authority. The request body is fully read before successful speculative dispatch. Supported public signatures, admission fences, session binding and provider bytes remain unchanged. The internal export-name inventory adds the first-party
InferenceArrivaltype; no supported signature changes.The epic refresh is merged at
1f827e50ad09be6a54dcf07ca753075dac869056, including mainb7202e638and #4409's connection ownership change. The final head is435896e36b6384190c95ae042c2a9cb259e4162f. Inference retains its Fetch transport;egress-proxy.tsis identical to the refreshed epic.Proof
Review round 3 — monotonic result gate
G1. Every required result increments
requiredbefore eligibility or arming can fail. The read-only decision is guarded; uncertainty means required. Every result retains its own observation. Arming failures take the immediate observation for that generation.G2. Only that result's successful observation sets
committed = gen, after native/worktree commits and the established scope schedule. Its denial remains in the gate. Rejection fails only that turn's gate. Begin, scope and periodic observations never advance result generations.G3. Every arrival registers before method/route checks and binds
(committed, required]. The relay's inner handler returns a brandedGatedresult; a rawResponsecannot satisfy its return type. The outer catch records failure and uses the same gated exit with a sanitized 500 envelope. Response construction and cancellation waits recheck the gate.G4.
before()reports the count of workers that acknowledged stopping for the cause turn. Dispatch requires a nonzero count equal to that turn's worker count. An observer that skips expired authority cannot manufacture a receipt.S1. Synchronous dispatch fails closed on a rejected observation; with all generations committed it requires both the arrival's bound verdicts and live
allowed(). Only the latest sole pending generation may speculate after a matched continuation, eligibility recheck and confirmed stop. Other pending generations take the immediate hold and the relay's existing wait/re-admit/re-dispatch path.S2. Every response claims any armed observation and loops until all required generations commit or the turn's gate fails. It preserves denied verdicts bound at arrival after Continue. It never joins unrelated journal work.
The refreshed typed operation retains
prepare()anddispatch(send). The concrete turn's separatedispatchReady()runs S1 synchronously, with no await before the unchanged transport dispatch fence and handoff. A pending gate never marks the operation dispatched or constructs an upstream request. Typed charge failures preserve their failure category through the same branded exit. Received upstream headers are charged before any observation wait; body delivery and EOF retain the refreshed transport fences. Trust subscriptions, session binding and cleanup are retained.Behaviour change: a straggler request on a paused turn now receives 403 where main dispatches it. This follows the ruling that the turn pauses before a response reaches the worker. After Continue, a new request may dispatch; an earlier request remains bound to its own denied generations.
Failing-first:
bun run test packages/ui-server/tests/deferred-freeze-gate.test.tsagainst reviewed head93989b03dfails the immediate-path, paused-straggler, 405/403, both thrown-admission, false-receipt, periodic-generation and rejected-observation assertions. The already-covered exit cases, older-generation control and synchronous-dispatch control stay green. All T1–T9 mutations were rerun on the merged final implementation and restored. 11 reachable mutations were killed: the nine table entries below, the S2 loop recheck, and H1 header ordering. The exact redundant T6 mutation survives as disclosed below. Restored proof: 73 deferred tests across 5 files, including the original 72 tests and the additional H1 regression; 196 SDK tests across 6 files, including the relay, diagnostic, accounting, failure-category and socket-ownership suites.NODE_OPTIONS=--max-old-space-size=6144 bun run typecheckandbun scripts/build.ts --for ui-sdk,ui-serverpass.bun run lintand finalbun run check:pr --base origin/epic/4278-host-overheadpass; preflight runs 1,285 selected fast invariants across 54 files. The exact final-head receipt is below.Run each mutation with
bun run test packages/ui-server/tests/deferred-freeze-gate.test.ts -t '<case>':predicate throwREQUIRED_RESULT_BLOCKS_UPSTREAM_UNTIL_COMMITimmediate void stopREQUIRED_RESULT_BLOCKS_UPSTREAM_UNTIL_COMMITfallback capallowed()from S1PAUSED_STRAGGLER_CANNOT_DISPATCHadmit throwsexitEVERY_EXIT_STARTS_THE_REQUIRED_OBSERVATION, both admission sitesauthority lostZERO_ACKNOWLEDGED_WORKERS_CANNOT_SPECULATEsecond result cannotOLDER_GENERATION_CANNOT_AUTHORIZE_SPECULATIONN results retaincommitted = requiredPERIODIC_COMMIT_CANNOT_SATISFY_RESULT_GENERATIONSN results retainRESPONSE_GATE_RECHECKS_AFTER_EACH_RESULT_COMMITrejected observationcommitted = genon reject instead of failing the gateREJECTED_OBSERVATION_NEVER_OPENS_ITS_GATEnothing pendingEMPTY_GATE_DISPATCH_IS_A_SYNCHRONOUS_BOOLEANThe exact T6 mutation
armed.gen === required→<=survives. G1 flushes the old armed result before the next generation and arms only the latest generation; S1 additionally requirescommitted === required - 1, a matched request, andmayDefer's absence of another hold. Those clauses make an older armed generation unreachable. The strict equality remains as defence in depth. T6's reachable mutation above proves that a second result cannot authorize dispatch through the fallback.H1 preserves the refreshed transport's header-first accounting.
bun run test packages/ui-server/tests/deferred-freeze-header.test.tsfailed first atUPSTREAM_HEADERS_ARE_CHARGED_BEFORE_THE_OBSERVATION_WAIT(expected true, received false). MovingreadRelayResponseback inside the post-gate response producer kills the same assertion; restoring header accounting before the wait passes. The response itself remains gated. The internal inventory mismatch was corrected by regeneratingapi-report/ui-sdk.txt; only the internalInferenceArrivalname changes.No tests were removed: the existing suites assert observable eligibility, verdict binding, hold schedules and runtime ordering; none inspects the deleted
Boundaryorclaimedmap. Their assertions remain applicable to the gate. Boolean dispatch assertions now call the concretedispatchReady()gate; the actual typed transport is exercised by the relay/runtime suites. Typed budget mocks return{ok:false, reason:"budget"}, and the credential-error expectation follows the refreshed base's captured 502 cause. The ten-second / 8 MiB real-process proof is retained.Prior review round 2 — A1–A3
A1 (R2 F1): a claimed boundary authorizes dispatch only when it is both settled and allowed. The allowed verdict is latched on the boundary at observation completion. A token-count request whose immediate observation reaches
files_changedreturns 403 with zero upstream requests.A2 (R2 F7): every predicate read is inside one exception boundary. A read failure latches this turn as immediate-only and returns false. Malformed
turn_scope.summarytests cover arming and synchronous dispatch: both take the hold without throwing, return/retain the required observation promise, and remain immediate after the row is repaired and a healthy observation commits.A3 (R2 F10): the false/void-stop tests hold the fallback checkpoint open. They observe whether the fallback gate or an actual upstream request arrives first, and assert
upstream === 0before releasing the observation. This checks dispatch ordering independently of the final response gate.Failing-first at the reviewed implementation:
bun run test packages/ui-server/tests/deferred-freeze-review.test.ts -t 'R2 A'fails the token-count assertion (expected 0, received 1) and both predicate assertions (uncaught JSON parse errors). Restored proof and the strengthened fallback tests pass.Round-2 mutations, each run and restored:
bun run test packages/ui-server/tests/deferred-freeze-review.test.ts -t 'R2 A1'boundary.settledCAPPED_IMMEDIATE_BOUNDARY_CANNOT_DISPATCH_AUXILIARY_REQUEST— expected 0, received 1bun run test packages/ui-server/tests/deferred-freeze-review.test.ts -t 'R2 A2'PREDICATE_READ_FAILURE_RETURNS_TO_IMMEDIATE_HOLD— JSON parse error, both pathsPREDICATE_READ_FAILURE_LATCH_REMAINS_IMMEDIATE_ONLY— expected true, received false, both pathsbun run test packages/ui-server/tests/deferred-freeze.test.ts -t 'stop receipt falls back'UPSTREAM_STAYS_EMPTY_WHILE_FALLBACK_OBSERVATION_IS_HELD— expected 0, received 1, false and void receiptsAll 4 round-2 mutations were killed. The restored deferred suites pass 51 tests. Round-2 compatibility/runtime proof passed 35 tests across 5 files, including the ten-second / 8 MiB real-process test. Typecheck and lint pass. Round-2
bun run check:pr --base origin/epic/4278-host-overheadpassed 1,284 tests across 54 files. The final round-3 receipt replaces it below.Prior-round focused proof
observe_commitcompletion, after both native and worktree commits. An early-resume mutation failsPROCESS_CANNOT_RESUME_BEFORE_COMMIT; restoring it passes the ten-second observation and 8 MiB real process/socket test.Failing-first and mutation receipts
With the reviewed
e7385d771runtime source restored, this command fails all 21 new review regressions on their named assertions:bun run test packages/ui-server/tests/deferred-freeze-review.test.tsThe revised false/void-stop cases also fail first at
UNCONFIRMED_STOP_FALLS_BACK_WITHOUT_NEW_REFUSAL:Every mutation below was run, failed on the listed assertion, and was restored. Run a row with
bun run test <file> -t '<case>'. T1 =packages/ui-server/tests/deferred-freeze-review.test.ts, T2 =packages/ui-server/tests/deferred-freeze.test.ts, T3 =packages/ui-server/tests/deferred-freeze-runtime.test.ts.unsupported relayUNSUPPORTED_RELAY_USES_IMMEDIATE_HOLDambiguous call identityAMBIGUITY_LATCH_SURVIVES_CALL_ENTRY_DELETIONpartial coverage forbids deferral at armingPARTIAL_COVERAGE_NEVER_ARMSnull scope measurementsUNKNOWN_SCOPE_MEASUREMENTS_USE_IMMEDIATE_HOLDsecond inference arrivalSECOND_ARRIVAL_FLUSHES_SYNCHRONOUSLYelapsed deadlineELAPSED_DEADLINE_CANNOT_SPECULATEsynchronous dispatch predicateDISPATCH_HAS_THE_SAME_DEFERRAL_PREDICATEContinue before headersCAPPED_REQUEST_VERDICT_SURVIVES_CONTINUErefusal joins its result observationALL_RELAY_ANSWERS_JOIN_THE_RESULT_OBSERVATIONunrelated global journal workORDINARY_INFERENCE_DOES_NOT_JOIN_GLOBAL_TAILholds do not gain scopeBASE_HOLD_SCHEDULE_HAS_NO_NEW_SCOPE_WAITnon-deferred dispatch retainsORDINARY_DISPATCH_HAS_NO_NEW_HOLD_REFUSALbase skip for ended authorityENDED_AUTHORITY_IS_NOT_NEWLY_FROZENstop receipt falls backUNCONFIRMED_STOP_FALLS_BACK_WITHOUT_NEW_REFUSALreal stopped workerPROCESS_CANNOT_RESUME_BEFORE_COMMITPrior-round evidence: all 15 mutation cases were killed. Restored proof: 140 tests pass across 10 focused files, plus the real process/socket runtime test.
NODE_OPTIONS=--max-old-space-size=6144 bun run typecheck,bun run lintand the prior-roundbun run check:pr --base origin/epic/4278-host-overheadpassed. Those are prior-round results; current-head proof and its exact receipt are recorded separately.The initial response-before-commit and FULL-scope-write mutations remain covered by the result/answer gate and the held-writer test. The FULL test reads the old committed scope row while the actual writer is blocked, then requires the pause to commit before a confirmed deferred refusal answers.
#4293 remains open
#4293 is still open. The existing cell labelled “hold removed” reports
admitMs = 27.1 msat 10 ms. The join is not narrowed, and the reason is not recorded yet. Round-2 F9 is tracked in #4429 because those cells still run the 50 ms fallback; they are not qualified no-hold measurements.The prior journal-attached local figures are retained below as evidence, not as completion of #4293. Five samples per cell, twenty queued FULL inference audit commits, medians in milliseconds. Actual arrival/dispatch use the same monotonic host clock. Hosted measurement uses the app's native journal/writer, standalone measurement uses copied checkpoints, and worker-control acknowledgements are simulated. Qualified native/runtime assembly proof remains open.
admitMsThese cells include the fallback observation wait and do not isolate admission-queue cost. The join itself is unchanged; the reason for not narrowing it has not yet been recorded.
Acceptance criteria
#4292:
#4293:
Preflight receipt
{"version":1,"kind":"brain-check-pr-receipt","head":"435896e36b6384190c95ae042c2a9cb259e4162f","base":"origin/epic/4278-host-overhead","mode":"focused","startedAt":"2026-11-21T15:52:19.815Z","finishedAt":"2026-11-21T15:54:22.983Z","checks":[{"name":"all lint and leakage gates","categories":["changeset"],"outcome":"passed","elapsedMs":14611.244131},{"name":"environment documentation","categories":["changeset"],"outcome":"passed","elapsedMs":131.4800720000021},{"name":"pending changeset package names","categories":["changeset"],"outcome":"passed","elapsedMs":96.1775839999973},{"name":"contribution changeset","categories":["changeset"],"outcome":"passed","elapsedMs":22.283618999997998},{"name":"affected fast invariants","categories":["verify","unit"],"outcome":"passed","elapsedMs":108288.206819}]}Checklist
.changeset/tidy-ithaca-freeze.mdcovers ui-server/ui-sdk.InferenceArrival.Proportionate containment
G1. Only speculative deferral is withdrawn for missing coverage, unsupported transport, expired deadline or ambiguity. An unconfirmed receipt selects the existing immediate observation; it adds no abort cause.
G2. Only the affected request waits for its result boundary. Ordinary inference, unrelated journal work and existing hold schedules keep base behavior. A cap retains its existing paused worker/owner decision.
G3. Successful observations resume automatically. A cap uses the existing authorized Continue/Stop flow, and its original request keeps its committed refusal after Continue. Existing recording failures retain their established containment.
G4. Scope receipts and ordinary egress records remain in authenticated journal/Activity surfaces. #4401 owns the separate egress-record durability ordering; this PR does not claim it fixed.
G5. Existing second-session, binding and recording isolation tests pass. No process-wide failure latch is introduced; the immediate-only latch belongs to one turn and ends with it.
Anything left open
Round 1: F4/F12 are #4400; F3 is #4401; F6 was dropped. Round 2: #4427 tracks arrival/identity ambiguity, including reused IDs; the round-3 gate now registers early-route arrivals and remembers overlaps independently of result completion. Thrown freezer and fork/receipt work remains #4400; egress durability and failure attribution remain #4401. Measurement qualification is #4429. These adjacent issues are not claimed complete.
The last native proof attempt failed before application startup:
TMPDIR="$PWD/.wi-tmp" bun scripts/prove-native-host.ts --backend=claude --observation-timingexited 1 withPermissionError: [Errno 13] Permission denied: '/dev/loop-control'atos.open("/dev/loop-control", os.O_RDWR)inscripts/native-proof/fixture.py. The existing Claude hosted fixture also uses a mock query, so it does not establish actual Claude assembly time.The prior provider-history attempt remains an independent verification gap: SDK 0.3.293 exits with code 1 before history assertions, reproduced with the reviewed runtime source restored to the epic base. No history assertion was weakened. Its failure and the base-source control were recorded in the prior round. No new maintainer decision is needed for the gate design.
Follow-ups to file
Retain the prior handoff: brain-kit: the offline Claude provider-history guard exits before capturing requests. Repo
schlessera/brain-kit. Reproduce and retain the pinned offline fixture's startup error; identify and fix or route the cause without weakening prefix assertions or network guards; demonstrate the complete guard reaching and passing its history assertions. The orchestrator should reconcile existing tracker coverage before filing.