Repository navigation
fix(journal): retain payload overflow and quarantine rejected rows before dropping them (STA-6924, STA-6925) - #19717
brennanb2025 wants to merge 2 commits into
Conversation
…fore dropping them The journal was the sole holder of bytes it destroyed in two places, both introduced by the SQLite migration. `boundPayload` clipped a payload to a 16 KiB head and let the remainder go unreferenced. The bound itself is right — a row every reconnecting client replays must stay small — but it was applied in provider translation, which had no storage authority to hand the rest to. Bounding now takes a `JournalOverflowSink` as part of its limits and retains the whole payload under the sha256 it already computes before it clips, so a call site cannot bound without answering where the remainder goes. Bounds over derived keys (prompt ids, turn ordinals) answer with the explicit unretained sink. Repair called `DELETE ... seq >= ?` as its FIRST action, taking the rejected row and every valid row behind it, including Orca-minted submission receipts no provider transcript can rebuild. The rows are now copied to a durable quarantine file and fsynced before the delete transaction opens; a repair that cannot write the copy deletes nothing and latches the journal read-only. Both sidecars live inside the session's journal directory, so removing a session removes them with it. Refs STA-6924, STA-6925
There was a problem hiding this comment.
ℹ️ Two rough edges worth a look — nothing blocking.
Reviewed changes
This run reviewed the full PR at e0debf9 against main (65631e4): the overflow-retention store and its bounds threading, plus the quarantine-before-delete repair path.
- Overflow retention before the clip —
boundPayloadnow writes the clipped remainder to<journalDir>/overflow/<sha256>.txt(staged →fsyncSync→rename) before returning the head, so a bound becomes a display limit rather than a delete; derived-key bounds opt out viaUNRETAINED_JOURNAL_PAYLOAD_LIMITS. - Quarantine-before-delete repair —
quarantineJournalRowscopies rejected rows (and every valid row behind them, receipts included) to<journalDir>/quarantine/*.jsonlwithfsyncbefore the delete transaction; a repair that cannot write the copy deletes nothing and latches the journal read-only. - Limits threading —
JournalPayloadLimitsis threaded through every Codex/Claude translator and resolved from the bound journal viastructuredAgentSessionPayloadLimits. - Wire compatibility — additive
spilled?: trueonAgentJournalBoundedPayload/NativeChatTextBlock, non-strict zod schema, no DB schema bump.
I traced the repair ordering, the truncateFrom/fromSeq/contentFrom range math against deleteJournalRowSuffix, and the mixed-version wire path, and I found no correctness issues: the quarantine happens strictly before BEGIN IMMEDIATE, the marker commits atomically with the delete, and the read-only latch is sound. The new tests assert byte-for-byte round trips and exact eviction/refusal behavior, so they genuinely fail when the mechanism regresses. The two inline notes are performance/design observations, not bugs.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change adds journal overflow storage for clipped payloads and reports successful retention with Priority: ⬆️ High Merge Risk: 🟠 High · up to Reachable repair, overflow, suppression, and stream-eviction paths can still lose journal payload data, so the PR should not merge before these issues are fixed. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
src/main/native-chat/agent-session-journal/journal-repair-suffix.ts (1)
38-45: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winRead the suffix inside the deletion transaction.
The write queue serializes only one
AgentSessionJournalinstance, whileopenAgentSessionJournalcan create another database connection. That connection can append afterreadJournalRowsAfterreturns and beforeBEGIN IMMEDIATE.deleteJournalRowSuffixthen removes the new row without a quarantine copy. Begin the transaction before reading, fsync the quarantine file, then delete and commit.src/main/native-chat/agent-session-journal/journal-store-open.ts (1)
69-72: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPreserve the quarantine error before latching read-only.
quarantineAndDeleteJournalRepairedSuffixreturns{ quarantined: false, error }whenquarantineJournalRowsfails.openJournalStoreStatechecks onlyquarantined, then latches read-only and returns. The branch drops the failure cause.Use the repository’s
console.warnconvention.♻️ Proposed change
- if (!input.repairSuffix(loaded.truncateFrom, loaded.state.lastSequence + 1).quarantined) { + const repaired = input.repairSuffix(loaded.truncateFrom, loaded.state.lastSequence + 1) + if (!repaired.quarantined) { + console.warn( + '[agent-session-journal] journal repair could not quarantine the rejected suffix:', + repaired.error + ) input.latchReadOnly() return }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 3de42532-7f99-414e-91b8-8b5fccec2b35
📒 Files selected for processing (40)
src/main/claude/claude-structured-item-translation.tssrc/main/claude/claude-structured-journal-translation.test.tssrc/main/claude/claude-structured-journal-translation.tssrc/main/claude/claude-structured-prompt-items.tssrc/main/claude/claude-structured-provider-fallback.tssrc/main/codex/codex-image-item-translation.tssrc/main/codex/codex-notice-item-translation.test.tssrc/main/codex/codex-prompt-registry-bounds.tssrc/main/codex/codex-structured-item-streams.tssrc/main/codex/codex-structured-item-translation.test.tssrc/main/codex/codex-structured-item-translation.tssrc/main/codex/codex-structured-journal-generic-frames.tssrc/main/codex/codex-structured-journal-items.tssrc/main/codex/codex-structured-journal-prompts.tssrc/main/codex/codex-structured-journal-settlement.tssrc/main/codex/codex-structured-prompt-items.test.tssrc/main/codex/codex-structured-prompt-items.tssrc/main/codex/codex-tool-identity-translation.test.tssrc/main/codex/codex-turn-ordinals.tssrc/main/native-chat/agent-session-journal/journal-legacy-import.test.tssrc/main/native-chat/agent-session-journal/journal-legacy-import.tssrc/main/native-chat/agent-session-journal/journal-overflow-store.test.tssrc/main/native-chat/agent-session-journal/journal-overflow-store.tssrc/main/native-chat/agent-session-journal/journal-payload-bounds.tssrc/main/native-chat/agent-session-journal/journal-prompt-body-bounds.tssrc/main/native-chat/agent-session-journal/journal-repair-marker.tssrc/main/native-chat/agent-session-journal/journal-repair-suffix.tssrc/main/native-chat/agent-session-journal/journal-row-quarantine.test.tssrc/main/native-chat/agent-session-journal/journal-row-quarantine.tssrc/main/native-chat/agent-session-journal/journal-store-open.tssrc/main/native-chat/agent-session-journal/journal-store-restore.tssrc/main/native-chat/agent-session-journal/journal-store.test.tssrc/main/native-chat/agent-session-wire/provider-frame-disposition.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.tssrc/main/native-chat/agent-session-wire/unhandled-provider-frame.test.tssrc/main/native-chat/agent-session-wire/unhandled-provider-frame.tssrc/shared/agent-session-journal-schemas.tssrc/shared/agent-session-journal-types.tssrc/shared/native-chat-types.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| const translated = unhandledProviderFrameJournalItem( | ||
| 'codex', | ||
| kind, | ||
| payload, | ||
| structuredAgentSessionPayloadLimits(this.deps.sink) | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Cap timeline-substantive frames before payload retention.
appendUnhandled() calls unhandledProviderFrameJournalItem() before the cap. An oversized, over-cap timeline-substantive frame therefore creates an overflow file before its row is suppressed. The quota can then evict overflow referenced by accepted rows. Pre-classify with classifyProviderFrame(), cap only timeline-substantive frames before translation, and preserve the existing error-surface exception. Do not cap classifications that the translator declines.
| return true | ||
| } | ||
| const directory = journalOverflowDirectory(journalDir) | ||
| mkdirSync(directory, { recursive: true }) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
file='src/main/native-chat/agent-session-journal/journal-overflow-store.ts'
cat -n "$file" | sed -n '1,125p'
printf '\n--- related directory and sink references ---\n'
rg -n -C 3 'journalOverflowDirectory|mkdirSync|openSync|retainJournalOverflow|journalDir|chmod|umask' \
src/main/native-chat/agent-session-journal src/main | sed -n '1,220p'Repository: stablyai/orca
Length of output: 26495
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- journal directory creation ---'
rg -n -C 6 'function ensureJournalDir|ensureJournalDir|mkdirSync\(' \
src/main/native-chat/agent-session-journal | sed -n '1,180p'
printf '%s\n' '--- journal root/path ownership setup ---'
rg -n -C 4 'journalDirectoryFor|agent-session-journal|mkdirSync|mode:|chmodSync|umask' \
src/main | sed -n '1,240p'Repository: stablyai/orca
Length of output: 24839
Security Misconfiguration
Reachability: External
Exploitability: Moderate
CWE: CWE-732 — Incorrect Permission Assignment for Critical Resource
Set restrictive permissions for overflow sidecars.
mkdirSync(directory, { recursive: true }) and openSync(staging, 'w') use default permissions. Create or enforce the overflow directory with mode 0o700 and the staging file with mode 0o600 so local accounts cannot read provider or tool payloads.
| const staging = join(directory, `${digest}.${process.pid}.partial`) | ||
| const handle = openSync(staging, 'w') | ||
| try { | ||
| writeSync(handle, bytes) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 24824
🏁 Script executed:
#!/bin/bash
set -eu
file="src/main/native-chat/agent-session-journal/journal-overflow-store.ts"
printf '%s\n' '--- target file ---'
cat -n "$file"
printf '%s\n' '--- related symbols ---'
rg -n -C 4 'writeOverflowFile|retainJournalOverflow|writeSync|renameSync|fsyncSync|openSync|spilled|overflow' src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 33307
🌐 Web query:
site:nodejs.org/api/fs.html writeSync returns number of bytes written buffer partial write
💡 Result:
In Node.js, the fs.writeSync method returns the number of bytes written to the file descriptor [1]. When using fs.writeSync(fd, buffer, offset, length, position), the method attempts to write the specified number of bytes (defined by the length parameter) from the buffer to the file [1]. If the entire buffer or the specified length cannot be written in a single operation, fs.writeSync returns the actual number of bytes that were successfully written. It is the responsibility of the developer to check this return value and handle any remaining data if a partial write occurs [1].
Citations:
Handle partial writes before marking the payload retained.
writeSync can return fewer bytes than requested without throwing. The current code then fsyncs and renames the incomplete file, while retainJournalOverflow records spilled: true. Write until the complete buffer is written, and throw when writeSync returns zero or a negative value.
Proposed fix
- writeSync(handle, bytes)
+ let offset = 0
+ while (offset < bytes.byteLength) {
+ const written = writeSync(handle, bytes, offset)
+ if (written <= 0) {
+ throw new Error('Failed to write journal overflow payload')
+ }
+ offset += written
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| writeSync(handle, bytes) | |
| let offset = 0 | |
| while (offset < bytes.byteLength) { | |
| const written = writeSync(handle, bytes, offset) | |
| if (written <= 0) { | |
| throw new Error('Failed to write journal overflow payload') | |
| } | |
| offset += written | |
| } |
| closeSync(handle) | ||
| } | ||
| try { | ||
| renameSync(staging, file) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings
Length of output: 17137
🏁 Script executed:
#!/bin/bash
set -eu
file="src/main/native-chat/agent-session-journal/journal-overflow-store.ts"
printf '%s\n' '--- target file ---'
nl -ba "$file" | sed -n '1,180p'
printf '%s\n' '--- related symbols and callers ---'
rg -n -C 4 "writeOverflowFile|retainJournalOverflow|spilled|journal-overflow-store|overflow" src/main/native-chat/agent-session-journal
printf '%s\n' '--- package/runtime context ---'
rg -n -C 3 '"(typescript|node|engines)"|fsync|mkdirSync|chmodSync|openSync|writeSync|renameSync' package.json pnpm-lock.yaml package-lock.json yarn.lock 2>/dev/null || trueRepository: stablyai/orca
Length of output: 26480
🏁 Script executed:
#!/bin/bash
set -eu
nl -ba src/main/native-chat/agent-session-journal/journal-overflow-store.ts | sed -n '1,180p'Repository: stablyai/orca
Length of output: 233
🏁 Script executed:
#!/bin/bash
set -eu
file="src/main/native-chat/agent-session-journal/journal-overflow-store.ts"
wc -l "$file"
sed -n '1,180p' "$file"Repository: stablyai/orca
Length of output: 5306
Persist the parent-directory rename before returning true.
retainJournalOverflow returns true after writeOverflowFile fsyncs the staging file and calls renameSync. On Linux, this does not make the directory entry durable. A crash can leave spilled: true while the overflow file is unavailable. Fsync the containing directory, or return false when that guarantee is unavailable.
| const handle = openSync(file, 'w') | ||
| try { | ||
| writeSync(handle, Buffer.from(`${lines.join('\n')}\n`, 'utf8')) | ||
| fsyncSync(handle) | ||
| } finally { | ||
| closeSync(handle) | ||
| } | ||
| return file |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Find platform targets and existing fsync/durability helpers to reuse.
set -euo pipefail
rg -n --type=ts -C3 'fsyncSync|fsync\(' -g '!**/node_modules/**' | head -60
rg -n '"platform"|win32|darwin|linux' package.json electron-builder* 2>/dev/null | head -30Repository: stablyai/orca
Length of output: 4833
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- quarantine implementation ---'
cat -n src/main/native-chat/agent-session-journal/journal-row-quarantine.ts
printf '%s\n' '--- existing durable directory helper ---'
cat -n src/main/durable-file-write.ts | sed -n '1,50p'
printf '%s\n' '--- quarantine callers and delete flow ---'
rg -n -C4 --type=ts 'quarantine|journal-row-quarantine|delete.*row|delete.*journal|remove.*row' src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 33931
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 26166
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- platform and packaging configuration ---'
rg -n -C3 --glob 'package.json' --glob 'electron-builder*' --glob '*.yml' --glob '*.yaml' \
'"win"|"mac"|"linux"|win32|darwin|linux|electron-builder|build:' . | head -120 || true
printf '%s\n' '--- syncDirectorySync bindings and uses ---'
rg -n -C4 'syncDirectorySync|syncDirectory\(' src/main/durable-file-write.ts src/main --glob '*.ts' | head -100
printf '%s\n' '--- nearby synchronous write patterns ---'
cat -n src/main/native-chat/agent-session-journal/journal-overflow-store.ts | sed -n '1,130p'Repository: stablyai/orca
Length of output: 22178
🌐 Web query:
Node.js fs.writeSync documentation bytesWritten partial writes regular file
💡 Result:
In Node.js, the fs.writeSync function is a synchronous wrapper around the underlying system's write operation [1][2]. When using fs.writeSync to write to a regular file, it returns the number of bytes actually written [3][2]. Crucially, fs.writeSync does not automatically retry if a partial write occurs; it is the responsibility of the developer to handle partial writes if the returned value is less than the number of bytes requested to be written [2]. If fs.writeSync returns a number smaller than the length of the data provided, you must call it again with updated offset and length parameters to write the remaining data [2]. While fs.writeSync generally behaves as a blocking operation for regular files, historical issues and differences in how underlying file descriptors (like TTYs or pipes versus regular files) handle non-blocking I/O can lead to partial writes [2]. Always check the integer return value of fs.writeSync, which explicitly indicates the number of bytes successfully written to the destination [3][2].
Citations:
- 1: https://nodejs.org/docs/latest-v26.x/api/fs.html
- 2: GitHub issue 1541 in nodejs/node (link omitted to avoid creating a cross-reference)
- 3: https://beta.docs.nodejs.org/fs/synchronous-api
Make the quarantine copy durable before deleting journal rows.
writeSync returns the number of bytes written and does not retry short writes. Loop until all bytes are written before calling fsyncSync(handle).
On POSIX targets, also fsync the quarantine directory after fsyncing the file. Because mkdirSync can create that directory, fsync its parent directory when necessary. The existing syncDirectorySync helper is best effort and is not exported; do not treat its result as a fully durable copy without defining the Windows behavior. This repository packages Windows, where directory fsync is unsupported.
…ly on terminal rows Review found the retention wired to mutable state and paid for on the wrong rows. D1: `payloadLimits()` read `target?.journal.directory`, so a payload bounded while the sink was unbound answered "discard" — even though the session's journal existed the whole time. A payload is bounded when its frame is handled but journaled when the queue drains, and a native handoff unbinds across the whole `acquire` while the provider child is still emitting. The directory is a property of the session, not of the publish binding: it now survives `unbind`, and the host supplies an identity-derived fallback so a frame arriving before the first bind retains too. A required limits field guarantees a call site answers where the remainder goes; it cannot guarantee the answer is right, so the answer no longer depends on when a rebind happened to land. D2: the only tests were unit tests of the store, which pass with the production wiring severed. Added a suite that drives a real Codex translator over a real deferred sink from the real host runtime state, bound to a real journal, and asserts the bytes come back by the digest on the row. D3: retention ran per stream checkpoint. Content addressing only dedupes identical republishes, so a growing payload rewrote its whole prefix at every checkpoint — the sum of all prefixes for one long answer, against a 64 MiB budget. Only terminal rows retain now: the completed item, and the settlement row an interrupt writes. Checkpoints and pending patches are provisional and a later row carries their text in full. The per-write `readdir`+`stat` sweep is replaced by a cached running total, and a repeated payload's mtime is refreshed so eviction is least-recently-used rather than first-written. Also: the read-only latch no longer claims a newer schema, which was never the only reason it latches; the quarantine-failure test forces failure with a file where a directory must go rather than a permission bit that is a no-op on Windows; and `node:fs` is imported once, which unbreaks CI static analysis. Refs STA-6924, STA-6925
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 77e6d04b-1565-4dca-b9ce-d9b13f0267bd
📒 Files selected for processing (9)
src/main/codex/codex-structured-item-streams.tssrc/main/codex/codex-structured-journal-items.tssrc/main/native-chat/agent-session-journal/journal-overflow-store.tssrc/main/native-chat/agent-session-journal/journal-row-quarantine.test.tssrc/main/native-chat/agent-session-journal/journal-write-guards.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.tssrc/main/native-chat/agent-session-wire/structured-agent-session-payload-retention.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/native-chat/agent-session-journal/journal-row-quarantine.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-event-sink-queue.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| const translated = codexStreamingJournalItem( | ||
| state.item, | ||
| text, | ||
| UNRETAINED_JOURNAL_PAYLOAD_LIMITS |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Retain the forced capacity-eviction snapshot.
trimStates calls persist(..., true) before forgetState discards the buffered stream text. This call now uses UNRETAINED_JOURNAL_PAYLOAD_LIMITS, so an oversized stream retains only its clipped head when capacity evicts it. If the provider then interrupts before a completed item is available, the overflow tail has no remaining source for settlement.
Use retaining payload limits for this forced final snapshot, or emit it through the terminal lifecycle path. Keep ordinary coalesced checkpoints unretained.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This run reviewed the incremental commit 88f1a9d since the prior Pullfrog review (e0debf9): retention is now independent of the sink binding, and only terminal rows retain.
- Decoupled retention from the publish binding —
journalDirsurvivesunbind, andpayloadLimits()falls back to a record-derived directory before the first bind, so a payload bounded during a native handoff (or before the first bind) still retains into the session's journal. - Restricted retention to terminal rows — in-flight stream checkpoints and pending patches now bound with
UNRETAINED_JOURNAL_PAYLOAD_LIMITS; onlyitem/completedand the settlement rows retain, removing the per-checkpoint prefix amplification raised last run. - Cached the overflow directory size — a module-level
directoryBytesrunning total lets eviction skip the per-writereaddirSync/statSyncsweep, and eviction is now LRU (touch-on-republish) rather than oldest-first. - Made the quarantine-failure test cross-platform — it blocks
mkdirwith a plain file instead of a Unix-onlychmod. - Generalized the read-only latch message —
assertJournalWritablenow reports "latched read-only" since two causes set the flag, not just a newer schema.
I traced the byte accounting through the cache (including the rmSync decrement and the error-path invalidation, which self-heals on the next sweep), confirmed the fallback directory matches the journal's real location in the normal case, and confirmed the settlement paths retain the accumulated stream text for item types that never emit item/completed. The new retention suite's ablation table matches the tests — severing payloadLimits() turns every assertion red.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Status: readyAll three readiness gates cleared at Independent review — CLEAN WITH NITSReviewed adversarially, then re-reviewed after a NOT CLEAN first round that found three blockers. All three fixed and independently re-verified:
Re-measured rather than asserted: per-retain cost is essentially unchanged (5.73 ms at a near-full store), because the running total only short-circuits below budget and the The architecture was challenged, not just validated: the reviewer argued the SQLite-blob-table alternative that STA-6924's own suggested fix names, and it failed on this PR's principle — committing a large payload inside a Manual validation — run in the real appOverflow retention: validated end-to-end. A real Codex structured chat turn ran Quarantine and the read-only latch: not reachable through the app. Documented in Known limitations. Quarantine runs from Not validatedNo packaged build, no Linux/Windows/WSL/live-SSH/mobile run, no paired client/host version-skew run, no power-loss testing ( Follow-ups, not blockersPer-retain cost at a full store; overflow misplacement if |
|
Closing as superseded: a merged PR already covers this change. Merged #29982 (6c7a6dd, 2026-10-20) says 'Supersedes #19717'. It saves every chat reply and tool output whole and bounds only the copy sent to clients. journal-repair-marker.ts was deleted by (Stale-PR cleanup 2026-10-20, approved by Brennan. Reopen if something here is still missing on main.) |

ELI5
Two places in the structured-chat journal threw away bytes that only it had. A big
tool result was cut down to 16 KB and the rest was simply dropped. And when Orca
opened a damaged journal, it deleted the damaged row and every good row after it
— including receipts that prove a message was sent, which no provider transcript
can rebuild. Now the journal writes a durable copy first, every time, and only then
shortens or drops anything.
The principle
The journal never drops or destroys data without first writing a durable copy.
Both P0s are the same defect wearing different clothes: the journal decided
something was too big or too broken to keep, and acted on that decision while it
was still the only holder of the bytes.
STA-6924 — clipped payload bytes were unreferenced, not stored
Mechanism.
boundPayloadclipped to a 16 KiB head and returned. The remainderhad no other reference and was collected. The bound itself is correct — a row that
every reconnecting client replays must stay small — but it was applied in provider
translation, a context-free library with no database handle, no session directory
and nothing to hand the rest to. The bug class is not "the number 16 KiB"; it is
that the only code holding the full payload had no storage authority.
Fix.
JournalPayloadLimitsnow carries aJournalOverflowSink, andboundPayloadretains the whole payload through it before it clips. Because thesink is a required field, a call site cannot bound without answering where the
remainder goes. Bounds over derived keys — prompt option ids, turn ordinal keys,
image references, and the legacy importer, whose source transcript file is itself
the durable copy and is named in the timeline — answer with the explicitly named
UNRETAINED_JOURNAL_PAYLOAD_LIMITS, so every discard is a visible, reviewabledecision rather than a default.
The sink is threaded from the structured-session event sink, which already binds to
the journal;
structuredAgentSessionPayloadLimits(sink)resolves it from the boundjournal's directory. No new ownership mechanism was invented for this.
The sink is not keyed on the publish binding. A payload is bounded when its
frame is handled but journaled when the queue drains, and a native handoff unbinds
the sink across the whole
acquirewhile the provider child is still emitting.Resolving the directory from the bound target would therefore have decided "retain
or discard" from whether a rebind happened to have landed — a 40 MB tool result
during a handoff would have been clipped with the remainder gone. The journal
directory is a property of the session, so it survives
unbind, and the hostsupplies an identity-derived fallback for a frame that arrives before the first
bind. A required limits field guarantees a call site answers where the remainder
goes; it cannot guarantee the answer is correct, so the answer no longer depends on
mutable binding state.
Only terminal rows retain. Content addressing dedupes identical republishes but
not a growing one, so retaining every stream checkpoint would rewrite the whole
prefix each time — the sum of all prefixes for one long answer. The completed item
retains; checkpoints and pending patches do not, and a later row carries their text
in full.
Storage.
<journalDir>/overflow/<sha256>.txt, addressed by the digest the boundalready computed. Content addressing makes retention idempotent, so republished item
revisions and repeated identical tool output retain once. Written to a staging file
and fsynced before the rename, so a reader never sees a partial payload under a
digest that claims to describe it.
Failure is soft, deliberately. If retention fails the row carries exactly the
head, byte length and digest it carries today — never worse. Refusing the append
instead would turn a full disk into a lost turn.
STA-6925 — repair deleted first and copied never
Mechanism. On meeting a row it could not parse, the store called
DELETE FROM journal_rows WHERE ... seq >= ?as its first action. That takes therejected row and every valid row behind it. Among them are Orca-minted submission
receipts — the durable answer to "did my send land?" — which exist nowhere else.
Fix. The rejected rows are read out and written to
<journalDir>/quarantine/<epoch>-<seq>-<ts>.jsonlwith their exact stored bytes,and the file is fsynced, before the delete transaction opens. Ordering is the
whole contract: a crash between the two leaves the rows still live plus an orphan
quarantine file, never the reverse. A repair that cannot write the copy deletes
nothing and latches the journal read-only, so the timeline stays exactly as found
and the next open retries.
Each row is stored as
{epoch, seq, ts, rowJson}withrowJsonas a JSON string,because a quarantined row is very often not valid JSON — that is why it is there.
The epoch, anchor and repair-marker semantics are unchanged.
Superseding #19399
#19399 is a draft addressing STA-6925 alone. This PR replaces it rather than
extending it. Its recheck-under-the-write-lock idea and its crash-boundary test
methodology are good and worth keeping; its delivery mechanism is not:
journal_rowsand makes thempermanently undeletable via SQLite triggers. That is a new, unbounded, never
reclaimable growth class in the same table STA-6837 already says grows without
bound.
BEFORE INSERT/UPDATE/DELETEtriggers withWHEN EXISTSsubqueries land onthe append hot path of a
synchronous = FULLjournal.DELETE FROM journal_rows, whose comment records ameasured 0.26%-vs-99% WAL win from SQLite's truncate optimization, with a
correlated
NOT EXISTSdelete that gives that up.directory latch read-only. Copying out of SQLite needs no schema change at all,
so mixed-version hosts are unaffected.
Keeping the evidence outside the live store also makes it trivially copyable and
inspectable, and lets one budget cover both sidecars.
Deliberately out of scope
STA-6837 (bounded journal growth) is NOT closed here. It is about row growth in
journal_rows, which needs retention or compaction policy and interacts with theappend-only and repair invariants; folding that in would balloon this PR. What this
PR does do is refuse to add a new unbounded surface: the overflow store enforces a
64 MiB per-session budget, shedding oldest-first, and a payload larger than the whole
budget is not retained rather than evicting everything else for it. An evicted row
still carries its head, length and digest — today's behaviour.
Also out of scope: a recovery UI, automatic re-application of a quarantined suffix
(a valid-looking row behind a rejected one is evidence, not proof it can be safely
replayed), and quarantine retention policy.
Cross-cutting
AgentJournalBoundedPayloadgains one optional field,spilled?: true. Additive, no new opcode, no negotiation needed; the admissionschema already passes unknown keys, so an older host reads a newer row and an
older client ignores the field and renders the head as it always did. No row
version bump, no DB schema bump, so a downgrade needs no migration.
owns the journal, through the journal directory it already owns. Nothing crosses
the boundary and no client-side repair exists.
directory, which is keyed by workspace id and never by path, so a worktree, a
folder workspace, a WSL distro and an SSH host are identical here.
path.join; the staging file is renamed withinits own directory. Digests are hex, so filenames are safe on Windows.
removing a session removes its retained payloads and quarantine with it — no
reference counting and no cross-session leakage of chat content.
Testing
At
88f1a9d9f454ed1fc158dfe790f3c9705f6e7dd2.src/main/native-chat src/main/codex src/main/claude src/shared— 1065 files /11180 tests passed.
src/renderer— 3675 files / 30636 tests passed (at theprevious head; no renderer code changed since).
journal-overflow-store.test.ts(8),journal-row-quarantine.test.ts(3),
structured-agent-session-payload-retention.test.ts(4).pnpm run check:code-quality:changed— 0 new findings across 43 changed files.oxlint --config config/oxlint-code-quality-native-plugins.json src config tests mobile --deny-warnings— clean. This is the CI static-analysis gate, and it isNOT covered by
check:code-quality:changed.npx tsc --noEmitrun sequentially againstconfig/tsconfig.node.json,config/tsconfig.tc.web.jsonandconfig/tsconfig.tc.cli.json— no diagnostics.Ablations. Each restores with
git checkout HEAD --(orcp+cmpforuncommitted arms), verified by a clean
git statusand a non-zero grep for therestored mechanism, and every one was re-run at the final commit.
payloadLimits()always unretainedboundPayloaddiscards againjournal-store-open,-restore,-repair-markerall atmainThe 3 that survive the mechanism arm are the cases asserting a deliberate
non-retaining bound, which should be insensitive to it.
Validated in the packaged app. A real Codex structured-chat turn,
catof adeterministic 540,894-byte file. The completed tool-call row carried
truncated: true,spilled: true,byteLength: 540894and a 16,384-byte head; theretained overflow file was
cmp-identical to the original, its sha256 matched thedigest on the row, and the row head was a byte-prefix of it. The remainder is
recoverable in full, demonstrated rather than asserted. The quarantine half could not
be exercised end-to-end for the reachability reason under Known limitations.
Not validated: no Linux, Windows, WSL, live SSH, mobile or paired client/host
version-skew run. The
fsynccalls are exercised as ordinary writes; no power-loss testing was done. The~5.6 ms-per-payload figure that motivated the D3 work was measured on local APFS and
has now been re-measured after the fix: per-retain cost is essentially unchanged
(5.73 ms at a near-full 64 MiB store, 4.02 ms lightly loaded). The cached running
total short-circuits only below budget, so a full store still sweeps, and the ~4 ms
fsyncdominated in either case. The win is in retain frequency, not per-retaincost: only terminal rows retain, which removes the per-checkpoint prefix
amplification entirely. A ~4-6 ms synchronous stall per terminal oversized row
remains and is tracked as a follow-up.
Known limitations
readJournalOverflowhas no productioncaller: nothing in the UI yet offers the retained bytes back. The row carries the
digest, and the bytes are on the execution host beside the journal, so the
recovery path exists — but a reader and a UI affordance are follow-up work.
spilledis never revised. It records that the bytes were durable when therow was written. Eviction under the 64 MiB budget can later remove them, and the
row is append-only, so it will still say
spilled. A reader must treat a missingpayload as "evicted", not as a contradiction.
bound without retaining, because a growing payload hashes differently at every
checkpoint and retaining each would write the sum of all prefixes. Their text is
carried in full by the completed item, or by the settlement row an interrupt
writes. If a turn ends in a way that produces neither, that text is bounded
without retention — the pre-existing behaviour, not a regression.
directory. A recovery attach opens a different directory, so a payload retained in
that window would not be found from the recovered journal. Bound targets win as
soon as one exists.
the quarantine — runs from
openAgentSessionJournal, viajournal-store-open.ts->repairSuffix. On workspace restore,structured-agent-session-read-restore.ts:43-45drops a session whose probereports
corruptand returns before that open happens, so a corrupt journal metduring restore is never repaired and nothing is quarantined. Verified in the
packaged app: across six launches the corrupted session's tab did not restore, no
quarantine/directory was created, andjournal.dbkept all of its rowsbyte-identical. That early return is pre-existing behaviour, identical on
mainand untouched by this PR, so routing a corrupt journal into the repairing open is
deliberately out of scope here — it is a design change with its own consequences
and deserves its own review. Nothing in this PR makes that path worse, and the
quarantine it would reach is now non-destructive.
Visual Proof
N/A — storage and translation-layer changes; no layout or interaction surface changed.
Agent skill upstream boundary
Linked Issues