Skip to content

fix(native-chat): keep every received reply and tool result when the journal save queue is busy - #37216

Merged
AmoabaKelvin merged 3 commits into
mainfrom
fix/journal-received-output-pressure
Nov 1, 2026
Merged

AmoabaKelvin merged 3 commits into
mainfrom
fix/journal-received-output-pressure

Conversation

@AmoabaKelvin

@AmoabaKelvin AmoabaKelvin commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197 $\color{#cf222e}{\Huge{\mathbf{−}}}$​540 $\color{#cf222e}{\Huge{\mathbf{−}}}$​343
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​116 $\color{#cf222e}{\Huge{\mathbf{−}}}$​217 $\color{#cf222e}{\Huge{\mathbf{−}}}$​101

Supersedes #36059: same fix and design, without the lifecycle rewrite that grew around it.

ELI5

If a native chat got a lot of output at once, like one Claude message with more than 1,024 tool results, the save queue turned away everything past the 1,024th pending save. Those replies and tool results were gone when you reopened the chat, and nothing reported an error. Now the queue keeps everything it receives and slows down reading from the agent instead.

What Changed

  • Before: the journal sink queue refused a write once 1,024 writes were pending. The fire-and-forget appendItem, publish, appendTombstone and setActivity paths dropped that refusal, so the row was lost while drained() still said ok.
  • After: the queue never refuses output for pressure. The existing byte and op watermarks only pause provider reading, and reading resumes at the low watermark. Real failures (closed sink, failed write) still refuse as before.
  • Removed what only served the refusal: the max* watermarks, the lifecycle op/byte counters and the final-tail reservation. The final-tail reservation let a finishing agent's last rows get past the op limit, and its 512-op cap would otherwise have become the only count limit left.
  • Pi: it never bound the sink's reading control and only paused when refusals reached its timeline lane. PiRpcSession now binds it after startup, so startup replies stay readable, and unbinds at exit. A small ReaderPauseHolds keeps the lane's own pause and the journal's pause from undoing each other. The lane resumes reading on every retry(), including when a compaction starts.
  • Tests that only asserted the op-count refusal are deleted. The rest now check pacing.

Why

A bookkeeping limit must never throw away a reply the provider already delivered. Ordered handoff plus pacing future reads is the design #36059 chose, and it keeps the journal format, fences, item identities and wire payloads unchanged.

#36059 also rewrote startup and exit ownership to keep output that arrives while a chat is still starting. That rewrite caused a regression in startup-failure diagnosis (event order decided which error Claude showed), and later commits had to repair the fallout (SDK patch, Codex reclaim, Antigravity, text generation). That startup loss is real but separate, and it happens far below 1,024 writes. It's filed as #37208 with the ordering question attached.

Linked Issue

Fixes #37209

Linear: STA-10949

Visual Proof

N/A: nothing on screen changes. Saved chat content is checked in the journal after close and reopen.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • structured-agent-session-received-output.test.ts: one Claude message with 1,025 tool results, then close and reopen the real SQLite journal. On main it saves 1,024 with no failure reported; on this branch all 1,025 are there, in order, with distinct ids.

  • rpc-session-startup.test.ts: Pi isn't paused during startup, is paused by journal pressure afterwards, stays paused when a compaction starts (fails without ReaderPauseHolds), resumes once after the drain, and keeps all 2,050 rows through reopen.

  • Real agents (macOS, hidden dev build of this branch, pause watermark patched locally to 1 op so pacing engaged on every write): Claude ran 16 parallel Bash calls and Codex 12 commands. The journal saved all 16 and 12 outputs, completed, plus both final replies. After an app restart both chats reopened with everything ("Ran 16 commands", all 12 Codex outputs, both DONE replies). A real agent can't be made to emit 1,025 tool results in one frame, so the drop itself can't be shown live. A baseline build of main with the limit cut to 2 kept these turns too, because reading paused between small frames. The 1,025-result test above is the proof of that path.

  • Focused suites: native-chat, jsonl-rpc, claude, codex, pi, acp, runtime/agent-session (10k+ tests) pass. Changed-code quality gate, including type-aware lint, passes. macOS only.

Risk

Riskiest part: pressure handling for every native-chat provider. If pacing failed, a flood of agent output would sit in memory instead of being refused. The bound is the output already received plus what is read before the pause lands. The pause and low watermarks are unchanged, and Claude, Codex and ACP pace exactly as before. Pi now pauses at the same byte and op watermarks as the others, where before it paused only once refusals started.

No saved-format, setting or wire change, so mixed-version hosts and phones are unaffected. A plain revert backs it out.

Level: Medium

AI Disclosure

Review

Two review rounds (Codex and Claude). The last round had no P0 or P1. Rejected or deferred:

  • The lane's pause hold looked unreachable. Rejected: JsonlRpcTimelineLane.beginCommand → retry() → resumeReading() runs on compaction, and the Pi test now covers it.
  • lifecycle options on publish, tombstone, batch and transition are now unread by the sink. Deferred to a follow-up cleanup.
  • If a provider exits while the journal holds its reader paused, the connection waits 1 s for stdout end and then drops unread output. Not new: Claude, Codex and ACP already pause at these watermarks on main. Follow-up.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Host-side only, so folder workspaces, git worktrees, SSH and paired phones go through the same path unchanged. No platform-specific code.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

The journal sink refused its 1,025th outstanding write, and the
fire-and-forget append, publish and tombstone paths dropped that
refusal, so a reply or tool result vanished on reopen while the drain
still reported success. Pressure now only pauses provider reading; the
sink no longer refuses output it has already received. The final-tail
reservation existed only to get past that refusal, so it goes too.

Pi relied on refusals to pause its reader, so it now binds the sink's
reading control after startup, alongside the lane's own hold.
@coderabbitai

coderabbitai Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The event sink queue no longer rejects queued output at hard operation or byte limits. Queue pressure pauses reading while accepted operations drain. The Pi session now coordinates reader pauses through owner-specific controls. Tests cover output persistence, pause and resume behavior, and updated handling of closed sinks.

Severity of issue fixed: Medium

Merge Risk: Low · up to 5333e

The change is mergeable with a bounded test-coverage gap: strengthen the result assertion so the persistence test detects a missing tool result.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: preserving native-chat replies and tool results when the journal save queue is busy.
Linked Issues check Passed Issue #37209 requires durable saving of all provider-delivered replies and tool results, plus pacing under heavy output. StructuredAgentSessionSinkQueue.submit now rejects only closed or failed sink…
Out of Scope Changes check Passed The changes stay within issue #37209. Queue watermark changes, removal of pressure-refusal accounting, reader-pause coordination, Pi wiring, and related test updates all support lossless output or its…
Description check Passed The pull request description is complete and follows the repository template. It explains the user impact, mechanism, rationale, linked issue, testing, risk, rollback, visual proof, platform considera…
Full details: Linked Issues check

Explanation

Issue #37209 requires durable saving of all provider-delivered replies and tool results, plus pacing under heavy output. StructuredAgentSessionSinkQueue.submit now rejects only closed or failed sinks. Queue pressure sets backpressured and pauses the bound reader. The queue resumes reading below the low watermarks. The received-output test covers 1,025 tool results, ordered unique items, journal close and reopen, and no failure callback. Pi binds journal reading control after startup and coordinates it with lane pauses.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #37209. Queue watermark changes, removal of pressure-refusal accounting, reader-pause coordination, Pi wiring, and related test updates all support lossless output or its pacing. The changes do not add unrelated product behavior, UI changes, format changes, or wire changes.

Full details: Description check

Explanation

The pull request description is complete and follows the repository template. It explains the user impact, mechanism, rationale, linked issue, testing, risk, rollback, visual proof, platform considerations, review notes, and checklist status. The AI Disclosure section is blank, which is permitted for internal contributors and does not prevent assessment because the rest of the description is sufficiently detailed.

Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 2 functions across 19 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick comments: 1
src/main/native-chat/agent-session-wire/structured-agent-session-received-output.test.ts: 1

66-68: Trivial · Functional Correctness · Quick win

Tighten the per-row result match so it detects a missing result replaced by a higher-numbered result.

A duplicate result can retain a distinct tool_use_id, so the count and unique-ID checks do not detect it. For example, saved-result-10 satisfies the current check for index 1 because it contains saved-result-1. Match the index with a digit boundary.

Proposed fix
-    tools.forEach((item, index) =>
-      expect(JSON.stringify(item.body)).toContain(`saved-result-${index}`)
-    )
+    tools.forEach((item, index) =>
+      expect(JSON.stringify(item.body)).toMatch(new RegExp(`saved-result-${index}(?!\\d)`))
+    )

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f92e9c45-d8f9-4e5f-b223-8da65f673a7d
Commits

Reviewing files that changed from the base of the PR and between f41f72a and 5333e4f.

Files selected for processing: 23
  • src/main/claude/structured/claude-structured-session-reading-control.test.ts
  • src/main/claude/structured/claude-structured-turn-resume-point.test.ts
  • src/main/claude/structured/journal/claude-structured-journal-translation-background-tasks.test.ts
  • src/main/codex/codex-structured-journal-exit-convergence.test.ts
  • src/main/codex/codex-structured-journal-goal-resume.test.ts
  • src/main/codex/codex-structured-journal-translation-settlement.test.ts
  • src/main/codex/codex-structured-journal-translation.test.ts
  • src/main/jsonl-rpc/reader-pause-holds.ts
  • src/main/jsonl-rpc/timeline-final-tail.test.ts
  • src/main/jsonl-rpc/timeline-lane.test.ts
  • src/main/jsonl-rpc/timeline-lane.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-final-tail-reservation.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-final-tail-reservation.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-received-output.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts
  • src/main/pi/rpc-session-startup.test.ts
  • src/main/pi/rpc-session.ts
Files with no reviewable changes: 4
  • src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts
  • src/main/jsonl-rpc/timeline-lane.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-final-tail-reservation.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-final-tail-reservation.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@AmoabaKelvin
AmoabaKelvin merged commit 1fb7995 into main Nov 1, 2026
52 of 53 checks passed
AmethystLiang pushed a commit that referenced this pull request Nov 1, 2026
…journal save queue is busy (#37216)

* fix(native-chat): keep received output when the journal queue is busy

The journal sink refused its 1,025th outstanding write, and the
fire-and-forget append, publish and tombstone paths dropped that
refusal, so a reply or tool result vanished on reopen while the drain
still reported success. Pressure now only pauses provider reading; the
sink no longer refuses output it has already received. The final-tail
reservation existed only to get past that refusal, so it goes too.

Pi relied on refusals to pause its reader, so it now binds the sink's
reading control after startup, alongside the lane's own hold.

* test(pi): prove a command start keeps a journal-paused reader paused

* test(native-chat): drop pressure tests that no longer guard a contract
AmoabaKelvin added a commit that referenced this pull request Nov 2, 2026
Resolve import conflicts from main's module moves. #37216 stopped the
journal sink refusing writes under backpressure, so drop the tests that
forced a sink refusal and keep one that proves a time-gated tail is saved
before an incoming stream evicts it. Move the scheduled plan owner check
out of codex-structured-session-acquire.ts to stay under its line cap.
@brennanb2025

Copy link
Copy Markdown
Contributor

Two follow-ups from our work on #36059, both about output already sent by the agent being lost when the chat closes or the agent exits while journal pressure has reading paused.

1. Pi can now lose output it already sent (new with this PR; traced from source, not run). src/main/pi/rpc-session.ts:188 pauses Pi at 512 pending writes. On main, Pi kept reading until 1,024 refusals. While Pi is paused:

  • a requested close resets the framer and drops complete records it still holds (src/main/jsonl-rpc/peer.ts:223 → main-process-ndjson-framer.ts:212-213, 284-291);
  • on exit, the connection waits 1 s for a stdout end that a paused stream never emits (src/main/jsonl-rpc/agent-connection.ts:132-135).

Example: a stdout chunk crosses 512 pending writes and a complete tool result follows in the same chunk. The user then closes the chat, or Pi exits while the queue stays above the low mark. The tool reopens as interrupted with no result.

Suggested fix: once the root process has exited, resume reading so the rest drains to end, as the Claude connection already does (claude-stream-json-connection.ts:175-176). On a requested close, hand held complete records to the lane before the reset.

2. Codex and ACP have the same gap (already on main; you listed exit-while-paused as a follow-up). We reproduced it on main before this merge, and the code is unchanged here.

  • Codex: send item/started, get 512 writes pending, then a separate complete item/completed, then exit. 211 bytes stay unread in stdout, written() reports ok, and the reopened tool is interrupted with no output. codex/app-server/codex-app-server-connection.ts:66-80 reports the exit without resuming the paused reader, then codex-structured-session-close.ts:79-82 unbinds pacing.
  • ACP: a separate tool_call_update is stranded the same way, because the peer close removes the data listener first (acp-agent-connection.ts:144-150, acp-json-rpc-peer.ts:185-189).

One fix in a single place could cover all three providers: stop pacing once the root has exited and read the rest to EOF. Could this get a tracking issue, or fold into #37208?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Native chat loses received replies and tool results past 1,024 pending journal saves

2 participants