Skip to content

ui-react: late reconnect history removes a delivered queued reply #1917

Closed

Description

@schlessera

Delivered correction — 2026-10-15

Resolved by merged PR #1968, squash 66c370b54e65151c6b56a0466347b609b31571b1, verified on fetched main. Issue and PR closure/milestone 0.44.0 are read back.

Run 38783200249, attempt 1, passes all 14 selected jobs and aggregate on head 8e41b9829715767efa6127c2bf69d77e4f1b2d87, tested main cbf2bb87f8eee79f971099aa4858262888f087ae. Every actual checkout log agrees on 76c16a49930da3192152033a462797c75ce1516b, whose immutable parents are that base/head and tree is 4a0fe6bea400e0dec6a07c27407bb545bfd375d7; API and Git agree. Unit shards pass 3080 /3163 /3449 /3637; browser shards pass 4580 /4228 with four /six existing exclusions; layouts pass 622 /428. All 14 native continuity cases run and pass, including both original ten-drop/IME cells and all four stale/fresh-history cases. Strict verification, packaging, native runtime and captures pass. Contract checks also pass.

Main advanced only with #1992's three unrelated worker-policy documents before this merge. No product/test/harness/configuration/dependency input for this repair changed; combined citation validation passes all 44 cases /113 assertions. The actual squash parent is therefore 090c8a5463effe6811742259bc27af2b5ff6e66c and tree 23abbfe4ff695cc0f7c51f11ed5c5357b39faf57, exactly matching the inspected documentation-adjusted merge tree. The full CI receipt is retained at its actual older base/tree and is not relabelled as testing the newer documents.

The host refuses known-stale overlapping history after one resample; the client preserves real delivered peer answers across an inserted history user while excluding empty uncorrelated connection placeholders. Original guarantees, meaningful failing-first/mutation receipts and the diagnosed intermediate regressions remain below. Patch changeset covers ui-server and ui-react. The controlled defect is resolved; the original historical hosted timeout is not retrospectively attributed beyond the retained evidence. Independent #1993 and #1978 remain open for their distinct missing causal evidence.

Context

Found while qualifying #1764 / draft PR #1907. Original ready CI 38607535922, attempt 1, unit shard 1 job 116002513343 fails 320 phone, dark: ten drops and reconnects move nothing, keep the draft, resume the upload and send nothing. Ten-drop measurements and track upload complete; finishRecoveredTurn receives Landed: Sail past the Sirens. but its original 30-second wait for Noted: Then bind me to the mast. times out after 121384.38ms. That receipt alone does not locate the loss.

Actual original checkout c7cad1fe88e1658d64af41c674a20160f19cdc2d, parents main 4bcfb45135e4191dfd8a009a48805f319ffb6822 / head 8d59a50a43bac9eb059d0d3515d7fdcc31b43335, tree 838ac44469ff974fc706c3fdab769b6c29303db7. The original fixture uses ordinary chat/composer upload, not confirmed share-sheet intake. Native parent #578 and shipped continuity #1013 remain the context.

The late-history stale/fresh reproduction establishes an actionable concurrent-read defect: one reconnect history read samples the completed original two-message transcript and returns after the queued backend emits/stores its reply. Backend/transport succeed; stale history leaves the settled client with two messages instead of four. Identical fresh-history delivery retains four. This does not establish the exact cause of the historical hosted execution.

Out of scope

Interactive intake implementation (#1764), deleting follow-up or continuity assertions, timeout widening or arbitrary new sleeps, reducing device/theme coverage, weakening offline/security guards, or retrying unchanged failures to obtain green. No stronger provider persistence/freshness contract is selected.

Scope

Keep the delivered queued exchange when an asynchronous history read overlaps live turn transitions. Preserve bounded accepted/pending queue, running-slot, backend, host/transport and client-state evidence. When refreshed history inserts one missing peer user before a live assistant, retain that answer's identity, streaming state and intervening deltas across full or chunked replay. Ordinary shorter/empty history remains authoritative.

Acceptance criteria

  • Preserve the original failed hosted receipt and identify the queued entry's server and client lifecycle at failure.
  • Establish a controlled causal reproduction; an isolated unchanged pass is recovery evidence only. The linked stale/fresh pair supplies that evidence; historical attribution remains separate.
  • Retain delivered queued user/assistant messages after late older history and terminal status settle. Check settled store and DOM retention, not transient appearance, and preserve the fresh-history control.
  • Preserve all original ten-drop, geometry, focus/selection, draft, preview, pending-pill, upload, no-extra-send and final original-answer/follow-up assertions.
  • Prove the source correction with meaningful failing-first/restored controls and focused plus complete selected current-candidate hosted proof.

Current implementation and readiness — 2026-10-15

PR #1968, delivered candidate 8e41b9829715767efa6127c2bf69d77e4f1b2d87, qualified against cbf2bb87f8eee79f971099aa4858262888f087ae, now contains the repair and preserved bounded diagnostics.

The concrete host watches only outstanding reads for ordinary turn starts/terminals. An invalidated read is sampled again once. A second invalidation uses existing SESSION_LOAD_ERROR rather than publishing known stale content. Validation and history/pending/current-status publication are synchronous; authorization remains checked across awaits. Both explicit resume and snapshot-on-connect use the guard. A cancelled status preceding result cannot suppress that result's invalidation; result-followed-by-cleanup-idle is deduplicated.

Client reconciliation aligns only the last streaming assistant across exactly one inserted user, requiring a repeated prefix and existing text/tool/turn checks. It retains the answer between chunks and never converts a live turn correlation into a history-proven identity. Snapshot tests now observe the host's current turn status; all original continuity assertions and existing legacy old-status rejection controls remain.

Source anchors on this candidate:

  • (publishHistory, packages/ui-server/src/ws/host.ts:503-535) owns read validation and synchronous publication.
  • (case "session_resume", packages/ui-server/src/ws/dispatch.ts:600-657) retains pending requests and current status.
  • (keepDrawnMessages, packages/ui-react/src/stores/chat-state.ts:718-828) retains guarded live identity across replay.
  • (finishRecoveredTurn, packages/ui-react/tests/connection-continuity-runtime.test.ts:611-692) checks original terminals and settled queued retention.
  • (same, packages/ui-react/tests/connection-continuity-runtime.test.ts:592-608) retains original continuity measurements.
  • (async startTurn, packages/ui-react/tests/connection-continuity-runtime.test.ts:138-191) emits the actual scripted transcript/frames.

Claim token 1917-repair-3d746bc3-20261015 completed this repair. Final local preflight/strict types, meaningful red/restored controls and complete current-candidate hosted proof pass. #1979 delivery is verified; #1968 is merged and this issue is closed. The exact PR-qualified and actual squash states are distinguished above. Earlier failed candidates and cancelled categories remain preserved evidence, never qualification.

Verification

  • Published stale recipe repeated on refreshed source 2c88134afedf22581522d588258b4bdebbc1250e: original queued-reply wait fails after 675 assertions (122919.02ms case /176.96s invocation). JSON: backend 4/client 2, queue empty, replay/streaming false. One held read is released; no setup failure is counted.
  • Durable native stale-history guard mutation: original final wait fails after 7 assertions (42.13s case /90.63s invocation), backend 4/client 2. Restored. A final exact-host guard mutation independently fails on missing queued messages; restore passes 12 cases / 42 assertions.
  • Final focused host/client batch: 146 pass /0 fail /843 assertions across six files. New client full/split×legacy/proven cases all fail on lost answer identity before the correction; conflicting turn, changed prefix and distinct tools stay rejecting. Server stale-publication, retry-exhaustion and cancellation-order controls fail on their named assertions before restoration.
  • First full native candidate (host-only correction): 13 pass /1 fail /1658 assertions,391.94s. It exposes the original newer-answer streaming assertion after a missing user is inserted. This remains failed evidence, not a green retry.
  • Final guarded native file after the source correction: 14 pass /0 fail /1661 assertions,397.58s. Both widths' original ten-drop, missed-progress and IME cases, all four stale/fresh cells and snapshot cases pass. The original ten-drop test body is byte-identical.
  • Final bun run check:pr --base origin/main: 502 pass /0 fail /2974 assertions,24 files, plus all local gates. Pending changeset references and full Changesets plan validate: both changed packages receive patch entries inside the existing 18-package minor fixed group, no major.

These original local runs used the working tree committed as prepared candidate 2c9477aaead747c8048f7f0d92686ef4cb362f5f, with runner HEAD 2c88134afedf22581522d588258b4bdebbc1250e. Frozen host SHA256 395bba54b02567d9ad89d45d7d8a8cc6073c4e09f01eb3c7b0a3bea6d4b27d3f and chat-state SHA256 81143ed4543ea6334c8311b019b03a41ebe2aeda8fe1e1b1d0d2afc7ef557e5e match the candidate. They are local source receipts, not current-head hosted qualification.

Original diagnostic evidence remains preserved in the earlier handoff: exact original-source/full-shard controls, intentional frame-loss proof, and complete earlier ready runs 38702986278/38708024052 at their separately recorded heads/bases. Passing original controls and deliberate frame loss do not explain the original hosted timeout. The later stale/fresh pair and current corrections supersede the old needs:repro handoff without rewriting those receipts.

Use the pinned offline native browser harness. Focus with BRAIN_REQUIRE_CHROME=1 bun run test packages/ui-react/tests/connection-continuity-runtime.test.ts -t '320 phone, dark: a stale late history'; complete current-candidate selected hosted jobs and their actual checkout/parent/tree receipts remain the merge requirement.

Contract impact

No wire/schema/machine-contract change. Patch changesets cover @schlessera/brain-ui-server and @schlessera/brain-ui-react. Priority p2, areas, native parent #578 and milestone 0.44.0 remain. #1764's own implementation/qualification remains separate.

2026-10-15 repair update: consolidated the selected source correction, native-discovered insertion regression, final local proof and remaining hosted requirement; preserved original receipts and historical-attribution limits.

2026-10-15 combined-fixture qualification: rebased the unchanged behavior repair onto #1979's optimizer-refreshed candidate, preserving the actual sources of earlier local receipts. Both layers collect proof in parallel; neither a merge nor current-candidate hosted success is claimed.

2026-10-15 diagnosed typecheck correction: earlier head 1db612bb2a8b82f2a9b8ddcbd28cfd9cb4cdfe9b, run 38779448425 attempt 1, verification job 116575872719, fails TS2345 at the fixture history gate because a spread includes stale/fresh mode in the older failed/empty gate type. Explicitly passing only promise/release/read fields fixes strict types without changing the false hold predicate or runtime sequence. Local strict typecheck and renewed preflight (852 tests /5459 assertions) pass. The superseded run retains the failed verification, two successful jobs and eleven cancelled jobs; executing cancellations consumed 65.27 aggregate runner-minutes. No cancelled result is green. That corrected head subsequently exposes the capacity regression recorded below. Original runtime/mutation receipts retain their actual prepared source; the host bytes remain unchanged; the later narrowed client guard is recorded below.

Corrected capacity-handoff regression — 2026-10-15

Earlier head 5b340c7c20fcd0d38015c4b2fc1eb2d27d7a7fc4, run 38780399184 attempt 1, fails all six existing session-capacity handoff cells across browser shards (four plus two failures). Actual checkout f02eee279b2adb9b8edf3ca9481e9519b47b3c00, parents main b4609b961084268309287fff807b1dbd2687d607 / that head, tree 94e60086b4daf5dcb99bf10b15f93aa60543031c, agrees across logs, API/Git and browser artifact 11995832339. This is a diagnosed regression: cold session_info opens an empty uncorrelated assistant placeholder; inserted-user alignment preserves it as streaming and hides the finished failure action.

The unchanged complete native working-session file reproduces six failures /195 passes /six existing exclusions. Two cold full/split controls fail first on spurious streaming. The correction requires delivered progress or known turn correlation before aligning an answer across an inserted user. Restored unchanged browser proof passes all 201 cases with the same six exclusions. Five positive controls retain text, thinking, tools, turnId and streamTurnId; combined server/client proof passes 153 tests /882 assertions across six files. Existing four full/split identity and three rejection controls remain. No handoff fixture assertion, deadline or guard is weakened. Moved citations are adjusted.

Final head 8e41b9829715767efa6127c2bf69d77e4f1b2d87 includes this correction and passed fresh complete qualification against delivered #1979 main, as recorded above. Strict typecheck and renewed preflight pass locally. The older failed run is superseded with changed source; all unfinished/cancelled results remain nonpassing evidence. Final client SHA256 97b9165f1199859c722b4430fb04a29272919226394d4164e9d95e5633687af2 identifies this local control source; prior source-bound receipts are not relabelled.

Activity

  1. added
    type: test
    area: ui-server
    area: ui-react
    area: ci
    needs: repro
    on Oct 14, 2026
  2. added
    priority: p2
    on Oct 14, 2026
  3. schlessera commented on Oct 14, 2026

    @schlessera
    OwnerAuthor

    2026-10-14 triage at main 155dffdd8237a1543da3109f3de0b659cfac5c93: wanted unscheduled reconnect/queued-follow-up reliability is p2. Preserve native #578, needs:repro and no agent-ready. Existing local passing controls do not establish the missing server/transport/client boundary.

  4. self-assigned this
    on Oct 15, 2026
  5. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Claiming the explicitly requested causal investigation in a separate checkout. Claim token 1917-3d746bc3-20261015; branch test/1917-queued-followup-trace-3d746bc3. I will retain bounded accepted-queue, backend, host/transport and client-state evidence at the original terminal/follow-up check. Original assertions and failed receipts remain binding; needs: repro stays until a responsible condition is established.

  6. added this to the 0.44.0 milestone on Oct 15, 2026
  7. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Diagnostic work — 2026-10-15

    PR #1968, current head 10ed3d794f3e43a92f83318649a08d95b119694b, base 400c50ed231f33eeca875ec9223b24ad535b2b22, preserves bounded server/backend/transport/client evidence when the original final recovery check fails. Full JSON is retained under the existing tmp/*-probe.json unit artifact glob; the console prints its path. The original failure, waits, ten-drop matrix and every continuity/terminal assertion remain unchanged. This is an independently useful diagnostic slice under Refs, not a correction of the historical timeout.

    At earlier base c95223333a83fd3049749a2e68fb0c07963b7ba5, the original phone case with passive tracing passes 676 assertions (153.61 seconds). The complete original native fixture with passive tracing passes 10 cases / 1592 assertions in 356.58 seconds; this predates the artifact-output correction. Neither run reproduces the reported failure.

    Controlled mutation: discard only the queued answer's outbound text frame at the host broadcast boundary. The original final follow-up wait times out after 30 seconds with 674 preceding assertions. The final persisted JSON decodes and independently shows the queued backend start, emitted/stored Noted: Then bind me to the mast. answer and drained queue; that text is absent from both transport and client state. The first large stderr record interleaved with the timeout report, which motivated the artifact output. The second controlled mutation validates the complete artifact and original failure (181.85 seconds). Both mutations are restored. This establishes diagnostic discrimination, not that this artificial loss caused the original hosted timeout.

    On the refreshed exact candidate, the restored phone case passes 676 assertions (152.18 seconds / 92,624.92ms body), preflight passes 54 / 181, strict types pass, and live citation checks pass 44 / 113. Earlier runtime/mutation receipts keep their original base. The 0.43.1 release/Pi-worker/native-fixture and metadata-gate advancement is included before current hosted qualification. The diagnostic slice is scheduled for 0.44.0; selected hosted proof is pending.

    Next action: inspect a naturally failed receipt with this retained queue/backend/host/frame/client lifecycle, establish its responsible condition with a source-bound control, then qualify the smallest correction. Original needs: repro, historical failure and acceptance criteria remain; no causal delivery/concurrency/synchronization fix is claimed.

    2026-10-15 correction: folded scoped observations, restored mutation/artifact evidence, diagnostic PR and exact resumption requirements into the current brief.

  8. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    2026-10-15 bounded reproduction at main 400c50ed231f33eeca875ec9223b24ad535b2b22: the historical queued-follow-up failure did not recur in one CPU-constrained native-browser attempt. This differs from the prior isolated/full-suite controls and deliberate frame-discard mutation: the unchanged test runner, real host and Chromium processes shared one logical CPU, exercising scheduler contention without dropping an application frame or changing source.

    Command:

    BRAIN_REQUIRE_CHROME=1 taskset -c 0 bun run test packages/ui-react/tests/connection-continuity-runtime.test.ts -t '320 phone, dark: ten drops'

    The initial package build inherited that affinity; during setup only the build subprocess tree was returned to the original CPU set so setup could complete within the unchanged hook deadline. The test/host and newly launched browser remained on CPU 0 (verified from process affinity/placement). Conditions: Bun 1.4.2, local Chromium 152.0.7977.82, 320×640 dark viewport; existing loopback/offline guards, all ten drops, upload, geometry, focus/selection, draft, preview, pending-pill, no-extra-send and final terminal/follow-up assertions retained. No source edits, widened deadlines or application sleeps.

    Observed: 1 pass, 9 filtered, 0 fail, 676 assertions; body 104905.17 ms, invocation 294.99 s, exit 0. The final Noted: Then bind me to the mast. appeared and its queued pill drained. Expected failure, if reproduced, was the original 30-second final follow-up wait after Landed: Sail past the Sirens.; that wait succeeded. Re-read the original hosted job log: it does fail precisely that final follow-up wait after all ten cycles, so the historical receipt remains valid.

    Limits: one focused local attempt, a different Chromium version/environment from the pinned hosted browser, without full hosted shard ordering or the diagnostic PR's tracing. This is additional recovery evidence, not a causal explanation, fix, hosted qualification or proof that CPU contention cannot contribute. Preserve needs: repro, p2, the current milestone/assignment and absence of agent-ready. Next evidence remains a naturally failed receipt with #1968's accepted queue/backend/host/frame/client lifecycle, followed by a source-bound control establishing its responsible condition. No new independent prerequisite was identified; body and labels need no correction from this observation.

  9. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Blocked handoff for 1917-3d746bc3-20261015: the original queued-follow-up timeout remains unreproduced. Draft #1968 preserves the validated diagnostic at final head 3ed9d4ab51d603407e613b051679123fa8640f36, base 3100afa2b8efa25ea31114cdee1f2a89a48dd013. Final preflight/types and the 676-assertion phone control pass; new combined hosted proof remains pending after relevant main advancement. Prior ready runs 38702986278 and 38708024052 pass at their separately recorded sources.

    The exact original c7cad1f source with tracing passes all 16 original cases / 3152 assertions. The recovered original 223-file ordering also passes every reconnect case; the whole control has 3743 passes and two non-causal failures (tracing-shifted citations and the known original eager-tool count). It is not called green or a causal repair. Both controlled frame-discard mutations are restored; complete JSON discriminates their injected loss successfully.

    The body now consolidates full provenance, setup limits, the missing natural lifecycle receipt and exact resumption requirements. Original needs: repro, p2, criteria and milestone 0.44.0 remain; no agent-ready or original completion is claimed. The assignment is released after readback; resumable code/evidence remain preserved.

  10. removed their assignment
    on Oct 15, 2026
  11. 2 remaining items

  12. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Continuing the explicitly requested reproduction work. Claim token repro-1917-3d746bc3-20261015-b; investigating ordered terminal/follow-up transport batching with unchanged final assertions. Existing needs: repro, original receipts and acceptance criteria remain; controlled conditions will be distinguished from a demonstrated historical cause.

  13. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    2026-10-15 ordered terminal/follow-up delivery control: the reported timeout did not recur.

    Source: diagnostic draft #1968 at 3ed9d4ab51d603407e613b051679123fa8640f36, based on 3100afa2b8efa25ea31114cdee1f2a89a48dd013, plus a temporary 17-line fixture-only probe. Bun 1.4.2, Google Chrome 140.0.7339.127, original dark 320px phone case and existing offline/browser guards. Command:

    BRAIN_REQUIRE_CHROME=1 bun run test packages/ui-react/tests/connection-continuity-runtime.test.ts -t '320 phone, dark: ten drops'

    The existing lowest shared routeWebSocket server-message callback buffered its real send closures immediately before the original held turn was released. It retained frame bytes/order and flushed synchronously only after receiving the queued answer's real text_delta and subsequent result. There was no dropped frame, added sleep, deadline change or production change. This exercises a buffered burst across the original terminal and queued turn handoff, rather than the previous intentional frame-loss mutation or CPU slowdown.

    The captured 21-frame ordered burst contains Landed: Sail past the Sirens., its result/journal/activity frames, status: idle, session_queue, the queued turn's session/journal frames, Noted: Then bind me to the mast. and its result. The original final wait and drained-pill/node-retention checks pass: 1 pass / 9 filtered / 0 fail / 676 assertions, body 94,425.19ms, invocation 162.31s, exit 0. Every ten-drop/upload/geometry/focus/selection/draft/pending-pill/no-extra-send assertion remains intact.

    The temporary probe is restored, draft checkout is clean, and the reproducible patch/raw log are retained locally. This is a bounded negative result: it shows that this particular ordered burst alone did not reproduce the failure. It does not exclude other ordering/history/dispatch conditions or establish the historical cause, and it is not new hosted qualification. Original needs: repro, criteria, priority and release attribution remain; #1968 remains draft. Still needed: a failed lifecycle receipt distinguishing accepted queue/backend/host/transport/client state, followed by a matching causal control. Claim repro-1917-3d746bc3-20261015-b is released after readback.

  14. removed their assignment
    on Oct 15, 2026
  15. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Terminal-before-backend-completion control — 2026-10-15

    At main d2b4cf941498d1276deee8acf42f411b7d1c8090, attempted a distinct bounded reproduction in an exclusive temporary copy with exact-source built package outputs and remapped workspace links. Source/config/dependency inputs were audited against that SHA; no rebuild was needed. The fixture still bundles its real browser client normally. The temporary setup delta bypasses only the redundant package build, retaining the existing offline preload, loopback browser routing, native host/browser and original assertions/deadlines.

    Unlike the earlier CPU, frame-loss and ordered-frame-burst controls, this probe separates the original turn's terminal emission from completion of its real scripted backend promise. Immediately after the original result emission, the backend waits on a promise barrier. Only after the original browser checks observe Landed: Sail past the Sirens. and non-streaming state does the fixture assert that the backend remains pending and release it. It then executes the original 30-second queued-follow-up wait, retained-answer-node and drained-pill checks. No frame is removed/reordered/buffered, no product state is written, and no new sleep or deadline extension is introduced.

    Actual: 1 pass / 9 filtered / 0 fail, 678 assertions (676 original plus two barrier checks), body 93,029.60ms, invocation 95.34s, exit 0. Ordered markers confirm terminal emitted/backend pending → browser observed terminal → backend return. At the middle marker, the authoritative scripted transcript contains only the original user/assistant exchange, ending in the terminal; the queued user/answer has not yet been appended. After release, Noted: Then bind me to the mast. appears and the queued pill drains through the original assertions. All ten drop/reconnect, geometry, focus/selection, draft, preview, upload and no-extra-send checks pass.

    Command in the isolated copy:

    BRAIN_REQUIRE_CHROME=1 timeout 240s bun run test \
      packages/ui-react/tests/connection-continuity-runtime.test.ts \
      -t '320 phone, dark: ten drops'

    Bun 1.4.2; native Google Chrome 140.0.7339.127; 320×640 dark fixture; one invocation. The probe is restored after saving its patch and raw log. This differs from the pinned hosted browser/environment, does not reconstruct the original shard ordering, and does not carry #1968's complete lifecycle diagnostic. Other host activity is uncontrolled. The original failed-job log still identifies precisely the 30-second final follow-up wait after the original terminal; this passing control does not invalidate it.

    This demonstrates recovery for this controlled terminal/backend-lifetime separation, not the historical cause, a correction, failing-first repair proof or current hosted qualification. Retain needs: repro, type/areas/p2, native parent #578, milestone 0.44.0, no assignment and no agent-ready; draft #1968 remains separately owned. No body correction or label delta is justified. Still needed: a naturally failed lifecycle receipt capturing accepted queue/running slot, backend completion/outcome, actual host/transport frames and client state. The next experiment should use #1968's retained diagnostics at that failure to distinguish a backend promise/host handoff that remains pending from a completed dispatch whose answer fails later in transport/rendering, then establish a matching source-bound causal control.

  16. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    2026-10-15: a controlled late-history read reproduces the original final timeout; the same barrier with fresh history passes.

    The queued backend successfully emits and stores its reply, and the browser receives it. A delayed history response containing only the original completed turn then removes the queued user/assistant messages. This is an actionable reproduction of client transcript loss. Attribution of the historical hosted execution remains unknown.

    Source: fb219e069a8afd7fbc5eac6524b7a77ec08a7560, tree 8f242badad151c6bce8e4ff18d1b45bd96bf0164, plus passive diagnostics from draft #1968 at 3ed9d4ab51d603407e613b051679123fa8640f36. Runtime: Bun 1.4.3, Playwright 1.63.0, native Chromium 152.0.7977.82; lock SHA-256 a33ace577ec87f79769d40c3e8e25d637563b5ec8ea25e5ad40bb9b7a593285c. Lock-matching dependencies and independently built package outputs were used in an isolated checkout. Existing local/keyless/offline guards remain. This is not pinned-image or current-candidate hosted qualification.

    The distinct experiment overlaps one asynchronous history read with queued execution:

    1. Hold exactly the first session-A history read on reconnect ten; assert one held read. Subsequent reads proceed normally.
    2. Capture the actual two-message transcript immediately after the original Landed result, before the queued backend starts.
    3. Release that read immediately after the queued backend emits Noted and its result. In stale mode return the captured two messages; in fresh mode return the current four. The transport forwards all emitted frames in order.
    4. Keep every original continuity/final-answer assertion and deadline. Add a check that queued text remains visible after queued result → later history → later idle have reached the client and replay/streaming have ended.

    The final reconnect deliberately uses the fixture's existing held-history path, deferring recover's usual early history-completion barrier. This is a controlled concurrent-read scenario, not an unchanged historical fixture replay. It uses valid transcript content sampled during an outstanding read. The asynchronous normalized-at-read contract (AgentBackend, packages/ui-sdk/src/server/backend.ts:633-663) has no generation/freshness-at-delivery guarantee. No actual provider timing is claimed.

    Observation Result Final state
    First corrected stale probe, original final checks Exit 0; 678 assertions; 98,195.33ms case / 194.08s invocation Backend 4 messages, client 2; reply absent after settling. The original wait saw it briefly.
    Stale snapshot, with added retention check Exit 1; 675 assertions; 127,717.27ms case / 227.63s invocation Original 30-second Noted wait times out, before the new check; backend 4, client 2.
    Fresh snapshot, identical barrier and source Exit 0; 679 assertions; 96,399.00ms case / 195.62s invocation Backend/client both 4; queued reply retained, replay/streaming false.

    The stale failure has exactly one held read, released successfully. Relative to snapshot capture: queued backend starts at +263ms and emits text/result at +269ms; the client records queued text at +538ms, result at +576ms, stale history at +605ms, and idle at +719ms. At failure, the queue is empty and A has no running slot. Both queued messages remain in the backend transcript but are absent from client state and DOM. The fresh control has the same first-only hold and release, returns four messages, and retains the reply after the diagnostic completion barrier.

    Inspected boundaries: (case "session_resume", packages/ui-server/src/ws/dispatch.ts:600-651) sends awaited history with current running status; (session_history, packages/ui-react/src/hooks/websocket-handlers/chat.ts:436-456) applies it; (finishHistoryReplay, packages/ui-react/src/stores/chat-state.ts:1971-1991) can settle a shorter replay over already-completed messages. These are investigation pointers, not a selected correction.

    This is sufficient reproduction evidence to remove needs: repro, add agent-ready, and change type: test to type: fix: the remaining work restores promised continuity and adds durable regression proof. Priority p2, areas, parent #578, milestone 0.44.0 and the open/unassigned state stay unchanged. The issue body records the current repair target and preserves historical attribution limits; no product fix, PR, claim or closure is made by this investigation.

    Raw commands/logs, lifecycle JSON and patches are retained in brain-repro-evidence-1917. One stopped setup and one contaminated diagnostic that unintentionally held additional reads are explicitly excluded from defect evidence. Each valid invocation was bounded at 420 seconds externally; original fixture deadlines were unchanged.

    To reproduce, use the stated source, apply the passive diagnostic patch from #1968, then the additional temporary patch below. The pair differs only in BRAIN_REPRO_HISTORY:

    git diff 3100afa2b8efa25ea31114cdee1f2a89a48dd013 3ed9d4ab51d603407e613b051679123fa8640f36 -- packages/ui-react/tests/connection-continuity-runtime.test.ts packages/ui-react/tests/fixtures/connection-continuity-client.tsx > passive.patch
    git apply passive.patch
    git apply late-history-after-passive.patch
    BRAIN_REQUIRE_CHROME=1 BRAIN_REPRO_HISTORY=stale bun run test packages/ui-react/tests/connection-continuity-runtime.test.ts -t '320 phone, dark: ten drops'
    BRAIN_REQUIRE_CHROME=1 BRAIN_REPRO_HISTORY=fresh bun run test packages/ui-react/tests/connection-continuity-runtime.test.ts -t '320 phone, dark: ten drops'
    Exact additional diagnostic patch (SHA-256 519d00e92e1ae9de5f57efa203c2c4cc37b5911dd6a266b45f29179b0ad70b36)
    diff --git i/packages/ui-react/tests/connection-continuity-runtime.test.ts w/packages/ui-react/tests/connection-continuity-runtime.test.ts
    index f3a30feb3..fe1f2508c 100644
    --- i/packages/ui-react/tests/connection-continuity-runtime.test.ts
    +++ w/packages/ui-react/tests/connection-continuity-runtime.test.ts
    @@ -44,6 +44,8 @@ let port = 0;
     let origin = "";
     let sequence = 0;
     let diagnosticSequence = 0;
    +const lateHistoryMode = process.env.BRAIN_REPRO_HISTORY === "fresh" ? "fresh" : "stale";
    +let lateHistory: { sessionId: string; promise: Promise<void>; release(): void; reads: number; released: boolean; snapshot?: SessionHistoryMessage[]; capturedAt?: number } | undefined;
     
     const transcripts = new Map<string, SessionHistoryMessage[]>();
     const titles = new Map<string, string>();
    @@ -63,6 +65,7 @@ function describeFrame(value: string | Buffer) {
         const frame = JSON.parse(String(value));
         return { type: frame.type, sessionId: frame.sessionId, turnId: frame.turnId, requestId: frame.requestId,
           status: frame.status, outcome: frame.outcome, code: frame.code, message: frame.message,
    +      history: frame.messages?.map((message: SessionHistoryMessage) => ({ role: message.role, content: message.content.slice(-240) })),
           text: frame.text?.slice(-240), followUps: frame.followUps, started: frame.started, dropped: frame.dropped };
       } catch { return { type: "unreadable" }; }
     }
    @@ -109,6 +112,16 @@ function scriptedBackend(): AgentBackend {
         listProfiles: () => [{ id: "continuity-scripted", label: "Local fixture" }],
         listSessions: async () => [...transcripts.keys()].map((id, i) => ({ id, title: titles.get(id) ?? "Odysseus", createdAt: 1 + i, lastActiveAt: Date.now(), totalCostUsd: 0, numTurns: 1 })),
         getHistory: async (sessionId) => {
    +      if (lateHistory?.sessionId === sessionId && !lateHistory.released && lateHistory.reads === 0) {
    +        const held = lateHistory;
    +        held.reads++;
    +        recordLifecycle("late-history-read-pending", { sessionId, reads: held.reads });
    +        await held.promise;
    +        if (!held.snapshot) throw new Error("Late-history control released without its terminal snapshot");
    +        const returned = lateHistoryMode === "fresh" ? transcripts.get(sessionId) ?? [] : held.snapshot;
    +        recordLifecycle("late-history-return", { sessionId, mode: lateHistoryMode, messages: returned.length, tail: returned.at(-1)?.content.slice(-200) });
    +        return structuredClone(returned);
    +      }
           const waiting = historyWaiters.get(sessionId);
           if (waiting && (!waiting.holdWhile || waiting.holdWhile())) {
             waiting.reads++; await waiting.promise;
    @@ -157,6 +170,19 @@ function scriptedBackend(): AgentBackend {
             emit({ type: "text_delta", sessionId, text: `Noted: ${title}.` });
           }
           emit({ type: "result", sessionId, outcome: "success", durationMs: 0, numTurns: 1, isError: false });
    +      if (lateHistory?.sessionId === sessionId) {
    +        if (prompt.startsWith("Hold: Sail past the Sirens")) {
    +          lateHistory.snapshot = structuredClone(transcript);
    +          lateHistory.capturedAt = Date.now();
    +          recordLifecycle("late-history-captured-original-terminal", { sessionId, messages: lateHistory.snapshot.length,
    +            tail: lateHistory.snapshot.at(-1)?.content.slice(-200), queue: app!.wsHost.followUpQueueFrame(sessionId) });
    +        } else if (prompt.startsWith("Then bind me to the mast")) {
    +          recordLifecycle("late-history-release-after-queued-result", { sessionId, messages: transcript.length,
    +            tail: transcript.at(-1)?.content.slice(-200), queue: app!.wsHost.followUpQueueFrame(sessionId) });
    +          lateHistory.released = true;
    +          lateHistory.release();
    +        }
    +      }
         },
       };
     }
    @@ -200,6 +226,8 @@ beforeAll(async () => {
     }, 240_000);
     
     afterEach(() => {
    +  lateHistory?.release();
    +  lateHistory = undefined;
       lifecycle.length = 0;
       observability.reset();
       for (const release of gates.values()) release();
    @@ -595,18 +623,36 @@ async function finishRecoveredTurn(s: Scene, cell: Cell) {
         await until(s.page, `!p.streaming(${JSON.stringify(s.A)})`);
         await s.page.waitForFunction(() => document.querySelector("[data-reading-column]")?.textContent?.includes("Noted: Then bind me to the mast."));
         await settle(s.page);
    +    if (lateHistory) {
    +      await s.page.waitForFunction((sessionId) => {
    +        const p = (window as unknown as { __continuity: { diagnostic(): {
    +          frames: Array<{ type: string; sessionId?: string; text?: string; status?: string }>;
    +          buffers: Record<string, { streaming: boolean; replay: boolean }>;
    +        } } }).__continuity.diagnostic();
    +        const frames = p.frames.filter(frame => frame.sessionId === sessionId);
    +        const noted = frames.findLastIndex(frame => frame.type === "text_delta" && frame.text?.includes("Noted: Then bind me to the mast."));
    +        const terminal = frames.findIndex((frame, index) => index > noted && frame.type === "result");
    +        const history = frames.findIndex((frame, index) => index > terminal && frame.type === "session_history");
    +        return noted >= 0 && terminal > noted && history > terminal &&
    +          frames.some((frame, index) => index > history && frame.type === "status" && frame.status === "idle") &&
    +          !p.buffers[sessionId]?.streaming && !p.buffers[sessionId]?.replay;
    +      }, s.A);
    +      expect(await s.page.evaluate(() => document.querySelector("[data-reading-column]")?.textContent?.includes("Noted: Then bind me to the mast.")),
    +        "the queued reply remains visible after the late history and terminal status settle").toBe(true);
    +    }
         expect(await s.page.evaluate(() => {
           const marks = (window as unknown as { __marks: { nodes: Element[] } }).__marks;
           const column = document.querySelector("[data-reading-column]")!;
           return marks.nodes.at(-1)?.isConnected && column.children[1] === marks.nodes.at(-1);
         }), "recovered text and the terminal replay kept the original answer node").toBe(true);
         expect(await s.page.locator('[data-row-half="right"] [data-pill]').count(), "the queued follow-up was taken").toBe(0);
    -  } catch (error) {
    +  } finally {
         const client = await s.page.evaluate(() => {
           const state = (window as unknown as { __continuity: { diagnostic(): unknown } }).__continuity;
           return { state: state.diagnostic(), column: document.querySelector("[data-reading-column]")?.textContent?.slice(-2000) };
         }).catch(failure => ({ diagnosticError: String(failure) }));
         const evidence = { capturedAt: Date.now(), cell, sessionId: s.A,
    +      lateHistory: lateHistory ? { mode: lateHistoryMode, reads: lateHistory.reads, released: lateHistory.released, capturedAt: lateHistory.capturedAt, snapshot: lateHistory.snapshot } : null,
           queue: app!.wsHost.followUpQueueFrame(s.A),
           slots: [...app!.wsHost.coordinator.running].map(turn => ({ sessionId: turn.sessionId, turnId: turn.turnId,
             cancelled: turn.cancelled, backendStarted: turn.backendStarted, queue: turn.queue.map(entry => ({ id: entry.followUpId, text: entry.text })) })),
    @@ -623,7 +669,6 @@ async function finishRecoveredTurn(s: Scene, cell: Cell) {
         } catch (captureError) {
           console.error("QUEUED_FOLLOWUP_LIFECYCLE capture failed", String(captureError));
         }
    -    throw error;
       }
     }
     
    @@ -794,7 +839,16 @@ describe.skipIf(!executablePath)("repeated connection drops in the mounted app",
               expect(await drawn(cell, page), `cycle ${cycle}: B's tracker stays drawn offline`).toEqual([B]);
     
               // The last reconnect lets the upload through, so it is seen to finish.
    -          if (cycle === 10) net.holdTracks = false;
    +          if (cycle === 10) {
    +            net.holdTracks = false;
    +            let release!: () => void;
    +            lateHistory = { sessionId: A, reads: 0, released: false,
    +              promise: new Promise<void>(done => { release = done; }), release: () => release() };
    +            // Use the fixture's established held-history path: hello/queue and
    +            // the original negative observation remain, replay settles later.
    +            historyWaiters.set(A, { ...lateHistory, holdWhile: () => false });
    +            recordLifecycle("late-history-armed", { sessionId: A, queue: app!.wsHost.followUpQueueFrame(A) });
    +          }
               const uploadsBefore = net.uploads;
               net.holdQueues = true;
               await recover(s);
    @@ -820,8 +874,12 @@ describe.skipIf(!executablePath)("repeated connection drops in the mounted app",
             expect(net.sent.slice(sentBefore).length, "the spy saw the page's frames").toBeGreaterThan(0);
             expect(await page.evaluate(() => (window as unknown as { __events: Array<{ type: string }> }).__events.map((e) => e.type)), "nothing blurred the field").toEqual([]);
             await hostUntil((d) => d.some((x) => x.sessionId === A && x.attachmentCount === 1 && x.preview === draft));
    +        expect(lateHistory?.reads, "exactly one final reconnect history read is held").toBe(1);
             await finishRecoveredTurn(s, cell);
    +        expect(lateHistory?.released, "the queued backend result released the captured original snapshot").toBe(true);
           } finally {
    +        lateHistory?.release();
    +        historyWaiters.delete(s.A);
             await s.context.close();
           }
         }, 300_000);
  17. added
    agent-ready
    type: fix
    and removed
    type: test
    needs: repro
    on Oct 15, 2026
  18. self-assigned this
    on Oct 15, 2026
  19. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Resuming the explicitly requested repair after the late-history stale/fresh reproduction. Claim token 1917-repair-3d746bc3-20261015; existing branch test/1917-queued-followup-trace-3d746bc3 and draft #1968. I will preserve the historical failed receipt, add settled-retention regression coverage and select a source-bound correction for the concurrent history/queued-turn boundary. Historical hosted attribution remains separate.

  20. changed the title [-]ui-react: hosted reconnect proof misses the queued follow-up after its terminal[/-] [+]ui-react: late reconnect history removes a delivered queued reply[/+] on Oct 15, 2026
  21. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Delivered by merged #1968 / 66c370b54e65151c6b56a0466347b609b31571b1, verified on fetched main. Current-candidate run 38783200249 attempt 1 passes all 14 selected jobs/aggregate, with every actual checkout 76c16a49930da3192152033a462797c75ce1516b matching tested base cbf2bb87f8eee79f971099aa4858262888f087ae, head 8e41b9829715767efa6127c2bf69d77e4f1b2d87, tree 4a0fe6bea400e0dec6a07c27407bb545bfd375d7. All 14 native continuity cases pass, including original ten-drop/IME and four new stale/fresh cells. Main's later #1992 is documentation only; combined citations pass 44 tests. Actual squash parent 090c8a5463effe6811742259bc27af2b5ff6e66c / tree 23abbfe4ff695cc0f7c51f11ed5c5357b39faf57 match the separately inspected combined state, not the older full-CI tree. Issue closure and PR/issue milestone 0.44.0 are read back. Original historical attribution and separate #1993/#1978 causal gaps remain explicit; no failed/cancelled candidate is relabelled green.

  22. schlessera commented on Oct 15, 2026

    @schlessera
    OwnerAuthor

    Post-merge verification is complete: automatic main-push run 38787444974, attempt 1, passes all fourteen selected jobs and aggregate on squash 66c370b54e65151c6b56a0466347b609b31571b1. Every actual job checkout log independently agrees on that exact SHA; its parent/tree remain 090c8a5463effe6811742259bc27af2b5ff6e66c / 23abbfe4ff695cc0f7c51f11ed5c5357b39faf57. This is a fresh main receipt for the documentation-adjusted final state, separate from the earlier PR qualification. It supersedes the prior pending-main status. Passing native PDF/parallel-session executions do not diagnose the independent historical causes on #1978 or #1993, which remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

agent-readyarea: ciarea: ui-reactarea: ui-serverpriority: p2type: fix

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions