Skip to content

fix(journal): retain payload overflow and quarantine rejected rows before dropping them (STA-6924, STA-6925) - #19717

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/journal-durable-storage
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/journal-durable-storage

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​873 $\color{#cf222e}{\Huge{\mathbf{−}}}$​143 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​730
Prod 31 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​663 $\color{#cf222e}{\Huge{\mathbf{−}}}$​153 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​510

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. boundPayload clipped to a 16 KiB head and returned. The remainder
had 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. JournalPayloadLimits now carries a JournalOverflowSink, and
boundPayload retains the whole payload through it before it clips. Because the
sink 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, reviewable
decision 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 bound
journal'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 acquire while 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 host
supplies 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 bound
already 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 the
rejected 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>.jsonl with 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} with rowJson as 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:

  • It seals rejected rows in place inside journal_rows and makes them
    permanently undeletable via SQLite triggers. That is a new, unbounded, never
    reclaimable growth class in the same table STA-6837 already says grows without
    bound.
  • Five BEFORE INSERT/UPDATE/DELETE triggers with WHEN EXISTS subqueries land on
    the append hot path of a synchronous = FULL journal.
  • It replaces the unqualified DELETE FROM journal_rows, whose comment records a
    measured 0.26%-vs-99% WAL win from SQLite's truncate optimization, with a
    correlated NOT EXISTS delete that gives that up.
  • It parses every row in the table on every journal open.
  • It bumps the DB schema to v3, which makes every older host sharing the state
    directory latch read-only. Copying out of SQLite needs no schema change at all,
    so mixed-version hosts are unaffected.
  • It solves one of the two P0s, leaving two unrelated mechanisms for one principle.

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 the
append-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

  • Wire compatibility. AgentJournalBoundedPayload gains one optional field,
    spilled?: true. Additive, no new opcode, no negotiation needed; the admission
    schema 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.
  • SSH / execution boundary. Both sidecars are written by the execution host that
    owns the journal, through the journal directory it already owns. Nothing crosses
    the boundary and no client-side repair exists.
  • Folder workspaces and worktrees. Both sidecars live under the journal
    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.
  • Cross-platform. All paths via path.join; the staging file is renamed within
    its own directory. Digests are hex, so filenames are safe on Windows.
  • Lifecycle. Both sidecars sit inside the session's journal directory, so
    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 the
    previous head; no renderer code changed since).
  • New suites: 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 is
    NOT covered by check:code-quality:changed.
  • Typecheck: npx tsc --noEmit run sequentially against config/tsconfig.node.json,
    config/tsconfig.tc.web.json and config/tsconfig.tc.cli.json — no diagnostics.

Ablations. Each restores with git checkout HEAD -- (or cp + cmp for
uncommitted arms), verified by a clean git status and a non-zero grep for the
restored mechanism, and every one was re-run at the final commit.

Arm Severed Result
Production wire payloadLimits() always unretained retention suite 4/4 failed
D1 only limits keyed on the publish binding 2 failed / 2 passed — the unbound and never-bound cases
Mechanism boundPayload discards again 9 failed / 3 passed across both payload suites
Amplification checkpoints retain again checkpoint case failed (4 payloads on disk, not 1)
STA-6925 journal-store-open, -restore, -repair-marker all at main quarantine suite 3/3 failed

The 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, cat of a
deterministic 540,894-byte file. The completed tool-call row carried
truncated: true, spilled: true, byteLength: 540894 and a 16,384-byte head; the
retained overflow file was cmp-identical to the original, its sha256 matched the
digest 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
fsync calls 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
fsync dominated in either case. The win is in retain frequency, not per-retain
cost: 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

  • Retention is write-only for now. readJournalOverflow has no production
    caller: 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.
  • spilled is never revised. It records that the bytes were durable when the
    row 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 missing
    payload as "evicted", not as a contradiction.
  • Only terminal rows retain. An in-flight stream checkpoint and a pending patch
    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.
  • A frame arriving before the first bind retains into the identity-derived
    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.
  • Quarantine covers the attach path, not the restore path. The repair — and so
    the quarantine — runs from openAgentSessionJournal, via
    journal-store-open.ts -> repairSuffix. On workspace restore,
    structured-agent-session-read-restore.ts:43-45 drops a session whose probe
    reports corrupt and returns before that open happens, so a corrupt journal met
    during 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, and journal.db kept all of its rows
    byte-identical. That early return is pre-existing behaviour, identical on main
    and 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

  • Not applicable; no upstream skill-installer material is included.

Linked Issues

…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

@pullfrog pullfrog 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.

ℹ️ 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 — boundPayload now 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 via UNRETAINED_JOURNAL_PAYLOAD_LIMITS.
  • Quarantine-before-delete repair — quarantineJournalRows copies rejected rows (and every valid row behind them, receipts included) to <journalDir>/quarantine/*.jsonl with fsync before the delete transaction; a repair that cannot write the copy deletes nothing and latches the journal read-only.
  • Limits threading — JournalPayloadLimits is threaded through every Codex/Claude translator and resolved from the bound journal via structuredAgentSessionPayloadLimits.
  • Wire compatibility — additive spilled?: true on AgentJournalBoundedPayload / 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds journal overflow storage for clipped payloads and reports successful retention with spilled. Payload limits now come from the configured event sink and flow through Claude and Codex translation paths. Derived identifiers use an unretained limit. Journal repair now quarantines rejected suffix rows before deletion and records the repair in the same transaction. Failed quarantine leaves rows intact and latches the journal read-only.

Priority: ⬆️ High

Merge Risk: 🟠 High · up to 88f1a

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 43 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes both primary journal fixes: overflow retention and quarantine before deletion. It is specific and related to the changes.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issues, testing, visual proof, compatibility, limitations, and scope. It omits several template headings and checklist items, but t…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@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.

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 win

Read the suffix inside the deletion transaction.

The write queue serializes only one AgentSessionJournal instance, while openAgentSessionJournal can create another database connection. That connection can append after readJournalRowsAfter returns and before BEGIN IMMEDIATE. deleteJournalRowSuffix then 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 win

Preserve the quarantine error before latching read-only.

quarantineAndDeleteJournalRepairedSuffix returns { quarantined: false, error } when quarantineJournalRows fails. openJournalStoreState checks only quarantined, then latches read-only and returns. The branch drops the failure cause.

Use the repository’s console.warn convention.

♻️ 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

📥 Commits

Reviewing files that changed from the base of the PR and between 65631e4 and e0debf9.

📒 Files selected for processing (40)
  • src/main/claude/claude-structured-item-translation.ts
  • src/main/claude/claude-structured-journal-translation.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-prompt-items.ts
  • src/main/claude/claude-structured-provider-fallback.ts
  • src/main/codex/codex-image-item-translation.ts
  • src/main/codex/codex-notice-item-translation.test.ts
  • src/main/codex/codex-prompt-registry-bounds.ts
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-item-translation.test.ts
  • src/main/codex/codex-structured-item-translation.ts
  • src/main/codex/codex-structured-journal-generic-frames.ts
  • src/main/codex/codex-structured-journal-items.ts
  • src/main/codex/codex-structured-journal-prompts.ts
  • src/main/codex/codex-structured-journal-settlement.ts
  • src/main/codex/codex-structured-prompt-items.test.ts
  • src/main/codex/codex-structured-prompt-items.ts
  • src/main/codex/codex-tool-identity-translation.test.ts
  • src/main/codex/codex-turn-ordinals.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.ts
  • src/main/native-chat/agent-session-journal/journal-overflow-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-overflow-store.ts
  • src/main/native-chat/agent-session-journal/journal-payload-bounds.ts
  • src/main/native-chat/agent-session-journal/journal-prompt-body-bounds.ts
  • src/main/native-chat/agent-session-journal/journal-repair-marker.ts
  • src/main/native-chat/agent-session-journal/journal-repair-suffix.ts
  • src/main/native-chat/agent-session-journal/journal-row-quarantine.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-quarantine.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-restore.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-wire/provider-frame-disposition.test.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.ts
  • src/main/native-chat/agent-session-wire/unhandled-provider-frame.test.ts
  • src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts
  • src/shared/agent-session-journal-schemas.ts
  • src/shared/agent-session-journal-types.ts
  • src/shared/native-chat-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +67 to +72
const translated = unhandledProviderFrameJournalItem(
'codex',
kind,
payload,
structuredAgentSessionPayloadLimits(this.deps.sink)
)

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.

🗄️ 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 })

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.

🔒 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)

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.

🗄️ 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-journal

Repository: 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.

Suggested change
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)

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.

🗄️ 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 || true

Repository: 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.

Comment on lines +44 to +51
const handle = openSync(file, 'w')
try {
writeSync(handle, Buffer.from(`${lines.join('\n')}\n`, 'utf8'))
fsyncSync(handle)
} finally {
closeSync(handle)
}
return file

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.

🗄️ 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 -30

Repository: 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-journal

Repository: 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:


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

@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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 77e6d04b-1565-4dca-b9ce-d9b13f0267bd

📥 Commits

Reviewing files that changed from the base of the PR and between e0debf9 and 88f1a9d.

📒 Files selected for processing (9)
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-journal-items.ts
  • src/main/native-chat/agent-session-journal/journal-overflow-store.ts
  • src/main/native-chat/agent-session-journal/journal-row-quarantine.test.ts
  • src/main/native-chat/agent-session-journal/journal-write-guards.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.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.ts
  • src/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

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.

🗄️ 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.

@pullfrog pullfrog 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.

✅ 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 — journalDir survives unbind, and payloadLimits() 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; only item/completed and the settlement rows retain, removing the per-checkpoint prefix amplification raised last run.
  • Cached the overflow directory size — a module-level directoryBytes running total lets eviction skip the per-write readdirSync/statSync sweep, and eviction is now LRU (touch-on-republish) rather than oldest-first.
  • Made the quarantine-failure test cross-platform — it blocks mkdir with a plain file instead of a Unix-only chmod.
  • Generalized the read-only latch message — assertJournalWritable now 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready

All three readiness gates cleared at 88f1a9d9f4. CI green (18 passed, 0 failed).

Independent review — CLEAN WITH NITS

Reviewed adversarially, then re-reviewed after a NOT CLEAN first round that found three blockers. All three fixed and independently re-verified:

  • A surviving STA-6924 hole. payloadLimits() read the publish binding, and its comment claimed "there is no session directory to retain into yet" — untrue during handoff, where session.journal exists throughout. A large payload emitted in the unbind window was journaled after rebind with a 16 KiB head and the remainder gone. Confirmed empirically against the real deferred sink. The fix removes the binding dependency entirely rather than patching the window, and the author found a third window (a frame before the first bind) that the review had not named.
  • Tests that did not pin the shipping path. Severing only the production wiring previously left 298 files / 2889 tests passing. The replacement suite drives a real translator over the real host runtime state and a real journal on disk; the same severed-wiring arm now fails 4/4.
  • Synchronous I/O on the append path. Retention ran before coalescing and admission, and a growing payload rehashed at every checkpoint, rewriting the whole prefix each time.

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 fsync dominates either way. The real win is retain frequency — only terminal rows retain, which removes the per-checkpoint amplification. The PR body has been corrected to say this; it previously implied the per-retain cost was the win.

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 synchronous=FULL transaction couples timeline durability to payload durability, turning a full disk into a lost turn.

Manual validation — run in the real app

Overflow retention: validated end-to-end. A real Codex structured chat turn ran cat on a deterministic 540,894-byte file. The terminal row carries spilled: true, byteLength: 540894, head exactly 16,384 bytes. The overflow file is cmp-identical to the original, sha256(overflow) == row digest == sha256(original), and the row head is a byte-prefix of it. The remainder is genuinely recoverable, not merely present.

Quarantine and the read-only latch: not reachable through the app. Documented in Known limitations. Quarantine runs from openAgentSessionJournal, and on workspace restore structured-agent-session-read-restore.ts:43-45 drops a session whose probe reports corrupt before that open happens. Verified pre-existing: identical on main, untouched here (git diff against the merge-base on that file is empty). Reproduced across six launches — no quarantine/ directory, journal.db byte-identical, nothing deleted. Control: restoring the journals intact brought both chat tabs back, single variable. So that half remains unit-tested only, and routing a corrupt journal into the repairing open is deliberately out of scope here.

Not validated

No packaged build, no Linux/Windows/WSL/live-SSH/mobile run, no paired client/host version-skew run, no power-loss testing (fsync is exercised as an ordinary write).

Follow-ups, not blockers

Per-retain cost at a full store; overflow misplacement if workspaceId changes across a recovery attach; spilled going stale after eviction (correctly judged unfixable in an append-only row and disclosed). Separately, a corrupt journal met during restore drops the session with no disclosure — data intact but unreachable — which is an availability concern distinct from this PR's destruction fix, and is being tracked separately rather than widened into it.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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.)

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.

1 participant