Repository navigation
refactor(agent-session-journal): move the session journal onto SQLite - #18652
Conversation
The agent-session journal kept its state in three hand-rolled file formats: an append-only `log.jsonl` with torn-tail repair, a `snapshot.json` holding folded state plus a retained tail, and byte-quarantine files for anything unreadable. This replaces all of it with one SQLite database per session — `journal.db` beside the existing `blobs/` store — using the in-house adapter and the open/pragma/migrate/harden pattern the orchestration database already follows. Two tables: `journal_rows` (the append-only log, keyed by `(session_id, epoch, seq)`) and `journal_sessions` (the derived projection, upserted in the SAME transaction as every insert). Rows stay JSON in one column, so the row schema, the version upcast chain, and the reducer survive byte for byte — `journal-reducer.test.ts` and four other suites pass unchanged and are the regression proof. Deleted: `journal-log-file.ts`, `journal-compaction.ts`, `journal-corruption-quarantine.ts`, and the public `compact()` / `compactionBoundary` / `autoCompact` members, none of which had a non-test caller. Existing `log.jsonl` / `snapshot.json` journals are deliberately abandoned. No importer: a session created on the old path stops working, which is acceptable because the feature is off by default. ## The physical quota is repriced, because SQLite does not charge like a file The 256 MiB per-session bound is unchanged, but the arithmetic under it could not survive: SQLite grows the database in pages and the WAL in frames, and the checkpoint that copies the WAL forward holds the same pages in both files at once, so a transaction's peak is about twice its content. Admission now charges the candidate transaction's own measured page cost, validated against a sweep that runs as a regression test (`journal-database-space.test.ts`) rather than derived from reasoning about the allocator. Four things are load-bearing rather than tuning, each measured: - `auto_vacuum = INCREMENTAL` must be set BEFORE `journal_mode = WAL`. Set it after and it is ignored with no error, reclamation silently becomes a no-op, and the file never shrinks again. Both halves are asserted. - `wal_autocheckpoint = 0` plus an explicit `wal_checkpoint(TRUNCATE)` at the end of every write path, so the one moment the same pages live in two files is a moment the charge accounts for. - Reclamation runs in bounded chunks. A single unbounded `incremental_vacuum` took a 252 MB directory to 504 MB — the reclamation added to defend the bound would have breached it. `PRAGMA incremental_vacuum(N)` also frees exactly one page unless it is stepped to completion, which no size assertion catches, so the freed page count is asserted directly. - A blocked checkpoint leaves the WAL on disk together with the database growth it already copied, so admission charges that deferred copy explicitly. The term is zero whenever the last checkpoint succeeded, so the uncontended path admits and refuses an identical set. The epoch discard is `DELETE FROM journal_rows` with no WHERE clause, which takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL bytes where the `WHERE session_id = ?` form rewrote every emptied leaf at up to 99%. One database per session is what makes the unqualified form correct. An open, empty journal costs 57,344 bytes before a single row exists, so a configured quota below `JOURNAL_MIN_SESSION_BYTES` now fails loudly at open with the existing `journal_bound_exceeded` instead of as a run of identical append failures. No production caller configures one; the affected surface is test fixtures, rescaled to the smallest value that restores what each case proves. ## One deliberate behaviour change Compaction was the only mechanism that shed bytes inside an epoch, and the write path called it precisely so an append at the bound was not refused. The SQLite-shaped replacement — a bounded prefix delete — cannot be used: with the snapshot gone the surviving rows ARE the state, so dropping the oldest of them loses the oldest transcript silently at the next reopen. So no row is ever shed inside an epoch, and a session whose row bytes alone reach the bound now refuses every append where it previously compacted and continued. A loud typed refusal beats silent data loss. What still sheds is unreferenced BLOB bytes — the dominant and unbounded byte source — on the same write-path hook. The escape from the hard stop is the fold that already exists, `replaceEpochItems`, which now actually returns bytes to the filesystem instead of leaving them on the freelist. The prune's protected set is a union of live reducer digests AND the candidate row's own digests, including those cited only by a nested lifecycle-batch mutation. Content addressing never rewrites a digest already on disk, so protecting live state alone deletes the blob the append is about to cite — a dangling reference that surfaces one reopen later as an empty expansion on an item the user can see. `journal-store-blob-budget.test.ts` pins it, and it goes red when the set is narrowed back. ## Handle ownership A file handle used to be opened and closed per append; a SQLite handle is held for the session's lifetime. Every path that can open a connection now has one owner: the open function owns its raw connection until it returns, the store owns its retained one and releases it in a new `close()`, and every other connection is closed by the call that opened it. The attach, recovery, eviction, map-overwrite and host-teardown paths close what they drop, and host teardown is failure-complete — the sink-barrier flush throws by design, so a trailing close statement would be skipped on exactly the path that leaks. `close()` has a stated contract: admission at enqueue and permanent, the close step on the same queue past that gate, one shared in-flight attempt, fulfilment terminal, and the release last and deliberately unguarded so a retry re-enters it. Guarding the release would skip it on retry, guaranteeing a permanent leak in exactly the case where it did not release. `journal_closed` joins the error union for a write after `close()`; no file outside the directory references any of these codes.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe journal storage model changes from snapshot and log files to a SQLite database with epoch rows and session projections. Journal writes, epoch replacement, rollover, replay, quarantine, quota checks, WAL handling, and space reclamation now use database transactions and physical page accounting. Blob pruning protects referenced and candidate digests. Journal closure and wire-layer teardown now close handles, support retries, and aggregate failures. Tests now use tracked openers and direct SQLite fixtures. Merge Risk: 🟡 Moderate · up to This changes session persistence to SQLite and adds recovery behavior for empty provider history. Recovery-marker handling is covered, but unresolved journal replay-integrity and quota/lifecycle concerns remain; these should be addressed before merge to avoid retaining corrupted session state or unnecessarily refusing session writes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides extensive technical context, rationale, behavior changes, and testing details. However, it omits required template sections, including ELI5, Why, Linked Issue, Visual Proof or N/A, checklist items, and review notes. Resolution Add the missing template sections. Include a linked issue using ✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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: 12
🧹 Nitpick comments (3)
src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts (1)
101-107: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCharge the WAL only once.
journalDirectoryBytes(input.journalDir)already includes the database-walsidecar, whilejournalWalBytes(input.dbPath)reads that same file. This double-counts the existing WAL and can cause prematurejournal_bound_exceededrefusals during checkpoint contention. Remove the separate WAL term or exclude sidecars frommeasured.src/main/native-chat/agent-session-journal/journal-database-space.test.ts (1)
193-211: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRelease
readerin afinallyblock.If any assertion between lines 197 and 208 fails, lines 210-211 never run and the second SQLite handle stays open. The
afterEachhook closes onlyopened.db, sorm(root, ...)then runs with a live handle on the database file. On Windows that removal fails and reports an error that hides the assertion that actually failed.Wrap the reader in
try/finally, or register it with the same tracking the other suites use.src/main/native-chat/agent-session-journal/journal-write-guards.ts (1)
94-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake
assertLifecycledelegate toassert. The test is the only remaining caller, and both methods perform the same size check and rate check. Delegation prevents future drift.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: dd36a1fa-4495-4091-aa61-94a5146d0f37
📒 Files selected for processing (64)
src/main/native-chat/agent-session-journal/journal-compaction.tssrc/main/native-chat/agent-session-journal/journal-corruption-quarantine.tssrc/main/native-chat/agent-session-journal/journal-crash-boundary.test.tssrc/main/native-chat/agent-session-journal/journal-cursor.tssrc/main/native-chat/agent-session-journal/journal-database-schema.tssrc/main/native-chat/agent-session-journal/journal-database-space.test.tssrc/main/native-chat/agent-session-journal/journal-database-space.tssrc/main/native-chat/agent-session-journal/journal-database.test.tssrc/main/native-chat/agent-session-journal/journal-database.tssrc/main/native-chat/agent-session-journal/journal-epoch-controller.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.test.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.tssrc/main/native-chat/agent-session-journal/journal-epoch-rollover.tssrc/main/native-chat/agent-session-journal/journal-handle-ownership.test.tssrc/main/native-chat/agent-session-journal/journal-legacy-import.test.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-admission.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-capacity.tssrc/main/native-chat/agent-session-journal/journal-log-file.test.tssrc/main/native-chat/agent-session-journal/journal-log-file.tssrc/main/native-chat/agent-session-journal/journal-open.tssrc/main/native-chat/agent-session-journal/journal-paths.tssrc/main/native-chat/agent-session-journal/journal-physical-quota.test.tssrc/main/native-chat/agent-session-journal/journal-physical-quota.tssrc/main/native-chat/agent-session-journal/journal-quota-test-peak.tssrc/main/native-chat/agent-session-journal/journal-row-table.tssrc/main/native-chat/agent-session-journal/journal-row-writer.test.tssrc/main/native-chat/agent-session-journal/journal-row-writer.tssrc/main/native-chat/agent-session-journal/journal-store-blob-budget.test.tssrc/main/native-chat/agent-session-journal/journal-store-close.test.tssrc/main/native-chat/agent-session-journal/journal-store-close.tssrc/main/native-chat/agent-session-journal/journal-store-collaborators.tssrc/main/native-chat/agent-session-journal/journal-store-contracts.tssrc/main/native-chat/agent-session-journal/journal-store-escape.test.tssrc/main/native-chat/agent-session-journal/journal-store-open.tssrc/main/native-chat/agent-session-journal/journal-store-schema.test.tssrc/main/native-chat/agent-session-journal/journal-store-test-open.tssrc/main/native-chat/agent-session-journal/journal-store.test.tssrc/main/native-chat/agent-session-journal/journal-store.tssrc/main/native-chat/agent-session-journal/journal-wal-contention.test.tssrc/main/native-chat/agent-session-journal/journal-write-guards.tssrc/main/native-chat/agent-session-wire/agent-session-history-page.test.tssrc/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.tssrc/main/native-chat/agent-session-wire/agent-session-journal-recovery.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach.tssrc/main/native-chat/agent-session-wire/structured-agent-session-eviction.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-eviction.tssrc/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-lifetime.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.tssrc/main/native-chat/agent-session-wire/structured-agent-session-journal-handles.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-send-idempotency.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.tssrc/main/native-chat/agent-session-wire/structured-tui-transcript-catchup.test.tssrc/main/runtime/orchestration/db/database-file-permissions.tssrc/main/runtime/structured-agent-session-integration-replay.test.tssrc/main/runtime/structured-agent-session-integration.test.tssrc/main/sqlite/harden-database-files.ts
💤 Files with no reviewable changes (5)
- src/main/native-chat/agent-session-journal/journal-store-contracts.ts
- src/main/native-chat/agent-session-journal/journal-log-file.ts
- src/main/native-chat/agent-session-journal/journal-log-file.test.ts
- src/main/native-chat/agent-session-journal/journal-corruption-quarantine.ts
- src/main/native-chat/agent-session-journal/journal-compaction.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| /** Bumps `user_version` only on success, so the database is never half-migrated. */ | ||
| function migrateJournalDatabase(db: Database.Database, stored: number): void { | ||
| if (stored >= JOURNAL_DB_SCHEMA_VERSION) { | ||
| return | ||
| } | ||
| db.exec('BEGIN IMMEDIATE') | ||
| try { | ||
| db.pragma(`user_version = ${JOURNAL_DB_SCHEMA_VERSION}`) | ||
| db.exec('COMMIT') | ||
| } catch (error) { | ||
| db.exec('ROLLBACK') | ||
| throw error | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Preserve the original migration error
If SQLite has already ended the transaction after PRAGMA user_version = ... or COMMIT fails, SyncDatabase.exec delegates ROLLBACK to DatabaseSync.exec, which throws cannot rollback - no transaction is active. Expose DatabaseSync.isTransaction through SyncDatabase, roll back only when active, and rethrow the original error.
| } catch (error) { | ||
| input.db.exec('ROLLBACK') | ||
| throw error | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Guard ROLLBACK in both epoch transaction catches. Node’s SQLite driver may automatically roll back after COMMIT errors such as SQLITE_FULL or SQLITE_IOERR. The unconditional ROLLBACK in publishNewEpoch and replaceJournalEpoch can then throw a no-active-transaction error and replace the original error. Expose DatabaseSync.isTransaction through SyncDatabase and roll back only when it is true.
| private requireDatabase(): OpenJournalDatabase { | ||
| if (!this.database) { | ||
| throw new AgentSessionJournalError( | ||
| 'journal_closed', | ||
| `agent-session journal for ${this.identity.sessionId} is not open` | ||
| ) | ||
| } | ||
| return this.database | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Find readSince call sites and their relationship to journal close.
set -euo pipefail
rg -n -C 6 '\breadSince\s*\(' src/main
rg -n -C 4 'isReleased' src/mainRepository: stablyai/orca
Length of output: 10229
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- journal-store.ts ---'
sed -n '1,380p' src/main/native-chat/agent-session-journal/journal-store.ts
printf '%s\n' '--- journal-store-close.ts ---'
sed -n '1,180p' src/main/native-chat/agent-session-journal/journal-store-close.ts
printf '%s\n' '--- journal-store-collaborators.ts ---'
sed -n '1,110p' src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
printf '%s\n' '--- read helper bindings ---'
rg -n -C 8 'function readJournalRowsAfterCursor|const readJournalRowsAfterCursor|readJournalRowsAfterCursor|class JournalLifecycleAdmission|interface OpenJournalDatabase|type OpenJournalDatabase' src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 38710
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings
Length of output: 12465
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- journal-cursor.ts ---'
sed -n '1,220p' src/main/native-chat/agent-session-journal/journal-cursor.ts
printf '%s\n' '--- journal-store close-related tests ---'
rg -n -C 10 'close\(|journal_closed|readSince' src/main/native-chat/agent-session-journal/journal-store.test.ts src/main/native-chat/agent-session-journal/*close*.test.ts 2>/dev/null || true
printf '%s\n' '--- lifecycle admission database usage ---'
sed -n '1,180p' src/main/native-chat/agent-session-journal/journal-lifecycle-admission.ts
printf '%s\n' '--- database wrapper close contract ---'
rg -n -C 12 'class Database|close\(\)|isOpen|connection is not open|not open' src/main/sqlite src/main/native-chat/agent-session-journal/journal-database.ts
printf '%s\n' '--- relevant diff summary ---'
git diff --stat -- src/main/native-chat/agent-session-journal/journal-store.ts
git diff -- src/main/native-chat/agent-session-journal/journal-store.ts | sed -n '1,180p'Repository: stablyai/orca
Length of output: 50369
Gate requireDatabase() on JournalConnectionCloser.isReleased.
After close() succeeds, database remains non-null while readSince() can call readJournalRowsAfterCursor without the write queue. A valid read after close can therefore use the released handle and expose a raw driver error instead of journal_closed. Add a regression test for readSince() after close().
There was a problem hiding this comment.
ℹ️ No critical issues — one minor nit inline and one rollout note below.
Reviewed changes
- Session journal moved onto SQLite — the append-only
log.jsonl/ foldedsnapshot.json/ byte-quarantine substrate is replaced by onejournal.dbper session (journal_rows+journal_sessions), opened throughsrc/main/sqlite/sync-database.ts. Rows stay JSON inrow_json, so the row schema, upcast chain, and reducer are untouched. - Physical quota re-derived as page arithmetic —
journalTxnPhysicalCost/journalReclaimBandBytes/ a deferred-checkpointwalBytesterm replace the old JSON-length charge, with a sweep test pinning the fixed-page constant. - Compaction deleted; blob pruning is the new shed —
journal-compaction.ts,journal-corruption-quarantine.ts, and the publiccompact()/compactionBoundary/autoCompactsurface are removed;replaceEpochItemsreclaims pages, andpruneJournalBlobsprotects a live-state ∪ candidate-row digest union. - Handle ownership + a five-part
close()contract —JournalConnectionCloser/JournalWriteQueuewith a tracked-close test harness, and a failure-complete host teardown.
The SQLite accounting is load-bearing here, and it is the one thing I scrutinized hardest: the walBytes term is not a double-count — it reserves the deferred copy (a busy checkpoint leaves the WAL on disk while its frames will still grow the DB at the next successful checkpoint, so the peak is db + 2·wal). The uncontended path zeroes it. That, plus auto_vacuum-before-WAL ordering and the stepped incremental_vacuum, is asserted with genuine negative controls, not just green paths. Solid.
ℹ️ Abandoned legacy files still count against the new quota
The migration deliberately has no importer, but the old substrate's files are not just ignored — journalDirectoryBytes recursively counts every file in the session directory, so a session upgraded from the old path keeps its log.jsonl, snapshot.json, and any quarantine-* bytes charged against the new maxSessionBytes with no code path that removes them (the epoch discard only frees DB pages, and pruneJournalBlobs only touches blobs/). Orphaned blobs do eventually get pruned; the log/snapshot/quarantine files do not.
Technical details
# Abandoned legacy journal files consume quota with no cleanup path
## Affected sites
- `journal-physical-quota.ts:9` — `journalDirectoryBytes` counts every file, including legacy `log.jsonl` / `snapshot.json` / `quarantine-*`.
- No importer and no delete of these files anywhere in the diff.
## Required outcome
- Decide whether abandoned files should be (a) charged-and-cleaned, (b) excluded from the count, or (c) documented as permanent budget loss for upgraded sessions.
## Open questions for the human
- Is `experimentalStructuredNativeChat` ever enabled in the field today? If not, this is theoretical and a comment may be enough.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…g valid rows, and keep rejected closes retryable Six review findings on the SQLite journal migration. 1. A successful COMMIT is now the point of no return. The ordinary append, the epoch roll and the epoch replacement each adopt the committed row or epoch BEFORE any post-commit filesystem work; checkpoint, reclaim, blob prune and directory measurement run through `runJournalPostCommit`, which is best-effort by design and falls back to the transaction's own charge as a conservative footprint. Previously a post-COMMIT scan failure rejected a durable append and the next one reused its sequence, and a failed epoch housekeeping step left the store writing into a prefix already deleted. 2. Corruption repair preserves instead of destroying. A rejected suffix is copied into a new `journal_quarantine` table and removed from the live epoch in ONE transaction per chunk, charged against the session bound before a byte is written; a journal that cannot afford the copy refuses to open rather than falling back to deletion. The repair state is exposed as `journal.repair` and the rows are readable through `recoverQuarantinedRows()`, so Orca-owned submission, receipt and lifecycle identity survives a gap or a malformed row. 3. The physical charge covers the B-tree key payload. `session_id` and `epoch` are stored in both tables and both primary-key indexes and appear nowhere in `row_json`, so the journal boundary now bounds them and `journalTxnPhysicalCost` charges those bounds plus the projection upsert. The charge sweep runs the exact production transaction at maximum admitted key sizes. 4. A rejected `close()` no longer orphans its handle. Callers hand the journal to `agentSessionJournalCloseRetries` instead of swallowing the rejection, the attach map replacement is ABORTED when the previous journal will not close, host teardown retries what the registry holds, and a failed runtime teardown is retained so the next stop is a real retry. 5. `journalWalBytes()` returns zero only for ENOENT and propagates every other stat error, so admission and reclamation fail closed. 6. The WAL contention test closes the writer before removing its temp root and asserts the directory is removable once handles close. Regression coverage: post-commit divergence (4), corruption repair (5), key bounds (5), WAL stat (8), close retry (5), plus a runtime stop-retry case. Each fix was ablated on this head and the matching tests go red.
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 28d89f39-93c1-4d31-ad21-0a56643d8a3f
📒 Files selected for processing (32)
src/main/native-chat/agent-session-journal/journal-close-retry.tssrc/main/native-chat/agent-session-journal/journal-corruption-repair.test.tssrc/main/native-chat/agent-session-journal/journal-database-schema.tssrc/main/native-chat/agent-session-journal/journal-database-space.test.tssrc/main/native-chat/agent-session-journal/journal-database-space.tssrc/main/native-chat/agent-session-journal/journal-database.test.tssrc/main/native-chat/agent-session-journal/journal-epoch-controller.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.test.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.tssrc/main/native-chat/agent-session-journal/journal-epoch-rollover.tssrc/main/native-chat/agent-session-journal/journal-key-bounds.test.tssrc/main/native-chat/agent-session-journal/journal-key-bounds.tssrc/main/native-chat/agent-session-journal/journal-post-commit-divergence.test.tssrc/main/native-chat/agent-session-journal/journal-post-commit.tssrc/main/native-chat/agent-session-journal/journal-row-table.tssrc/main/native-chat/agent-session-journal/journal-row-writer.test.tssrc/main/native-chat/agent-session-journal/journal-row-writer.tssrc/main/native-chat/agent-session-journal/journal-store-collaborators.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-journal/journal-store.tssrc/main/native-chat/agent-session-journal/journal-suffix-quarantine.tssrc/main/native-chat/agent-session-journal/journal-wal-bytes.test.tssrc/main/native-chat/agent-session-journal/journal-wal-contention.test.tssrc/main/native-chat/agent-session-wire/agent-session-journal-recovery.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach.tssrc/main/native-chat/agent-session-wire/structured-agent-session-close-retry.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.tssrc/main/runtime/structured-agent-session-runtime.test.tssrc/main/runtime/structured-agent-session-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/main/native-chat/agent-session-journal/journal-row-writer.test.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.ts
- src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| await journal.close() | ||
| await rm(root, { recursive: true, force: true }) | ||
| await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Release the held reader before removing the directory.
The separate reader connection remains open until afterEach. On Windows, rm() at Line 140 can fail after journal.close() because that reader still holds SQLite files. Release it before the removal assertion.
Proposed fix
+ await releaseReader()
await journal.close()
await rm(root, { recursive: true, force: true })📝 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.
| await journal.close() | |
| await rm(root, { recursive: true, force: true }) | |
| await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' }) | |
| await releaseReader() | |
| await journal.close() | |
| await rm(root, { recursive: true, force: true }) | |
| await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' }) |
…ine append-only, and charge it in bytes Three ways the corruption quarantine still lost rows it was written to keep. Replay validated contiguity from the first row that HAPPENED to remain, so an epoch missing only its sequence-1 row declared the leftovers contiguous and set no `truncateFrom`. The load was still corrupt, so recovery imported provider history and `replaceEpochItems` deleted every live row — including Orca-minted submission, receipt and lifecycle identity that no transcript can reconstruct, and that nothing had quarantined. Replay now anchors at sequence 1, so a missing epoch row rejects the whole surviving range before any replacement runs. `journal_quarantine` was keyed on `(session_id, epoch, seq)` and copied with `INSERT OR REPLACE`. A repair frees the sequences it removed and the live epoch reuses them, so a second repair in the same epoch silently deleted what the first preserved. The table is now keyed on a surrogate `quarantine_id`, the copy is a plain append, and `(epoch, seq)` is metadata; existing v1 databases are rekeyed in the migration that already bumps `user_version`. The admission charge read `length(row_json)`, which counts CHARACTERS for a TEXT value where `journalTxnPhysicalCost` expects physical UTF-8 bytes. A multibyte suffix was charged at up to a third of what it writes, which defeats the pre-write physical bound — over a megabyte on a maximum-size lifecycle batch.
There was a problem hiding this comment.
Important
One must-address charge bug in the new quarantine path: the copy is charged from length(row_json), which counts characters, not bytes, so multi-byte content undercharges the physical bound.
Reviewed changes
- Made a COMMIT final —
runJournalPostCommitmoves checkpoint/reclaim/prune/measure after the store adopts the committed state, so a post-commit scan failure can no longer strand the store on a deleted epoch or reuse a sequence (journal-epoch-rollover.ts,journal-epoch-replacement.ts,journal-row-writer.ts). - Replaced suffix deletion with quarantine — a rejected suffix is copied into a new
journal_quarantinetable (charged up front, one transaction per chunk) and only then removed fromjournal_rows; rows stay recoverable viarecoverQuarantinedRowsinstead of being destroyed. - Added a process-wide close-retry registry — rejected journal closes are retained and retried by teardown rather than dropping the SQLite handle (
journal-close-retry.ts,structured-agent-session-host-teardown.ts,structured-agent-session-runtime.ts). - Bounded the SQLite keys —
session_id(512 B) andepoch(128 B) are asserted at open/mint, and their per-row + projection page cost is folded intojournalTxnPhysicalCost. - Made
journalWalBytesfail closed — non-ENOENTstat errors now propagate instead of silently reading as an empty WAL.
The post-commit ordering and the close-retry contract are sound, with genuine negative controls (journal-post-commit-divergence.test.ts, journal-close-retry.ts). The one load-bearing arithmetic defect is below.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 299bb7e5-c214-4092-b6d7-19c1cf6ed877
📒 Files selected for processing (8)
src/main/native-chat/agent-session-journal/journal-corruption-repair.test.tssrc/main/native-chat/agent-session-journal/journal-database-schema.tssrc/main/native-chat/agent-session-journal/journal-database.test.tssrc/main/native-chat/agent-session-journal/journal-database.tssrc/main/native-chat/agent-session-journal/journal-open.tssrc/main/native-chat/agent-session-journal/journal-row-table.tssrc/main/native-chat/agent-session-journal/journal-suffix-quarantine.tssrc/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/native-chat/agent-session-journal/journal-database.test.ts
- src/main/native-chat/agent-session-journal/journal-suffix-quarantine.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| const gap = findSequenceGap( | ||
| tailRows.map((row) => row.seq), | ||
| oldest | ||
| rows.map((row) => row.seq), |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Validate the sequence stored in journal_rows.
Line 90 trusts parsed.row.seq instead of the SQLite row sequence. If database rows have sequences [1, 3] but the valid JSON at sequence 3 contains seq: 2, replay sees a contiguous [1, 2] range. It then applies the mismatched row and does not quarantine the physical sequence-3 row.
Reject a parsed row when its embedded sequence differs from entry.seq. Use the database sequence as the quarantine boundary.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval withheld for one prior finding that is still open.
Reviewed changes
- Charged the quarantine copy in bytes —
SELECT_SUFFIX_LENGTHSnow useslength(CAST(row_json AS BLOB)), so multi-byte suffixes are charged by physical size, with a multibyte regression test. - Rekeyed
journal_quarantineonto a surrogate — schema bumped to v2 with aquarantine_idsurrogate key plus a v1→v2 rekey migration, so a later repair reusing freed sequences no longer overwrites an earlier repair's preserved rows; the copy is a plain append now. - Anchored replay at sequence 1 —
replayJournalvalidates contiguity fromFIRST_JOURNAL_SEQUENCErather than the first surviving row, so a missing epoch row quarantines the whole surviving range instead of declaring it contiguous.
The prior charge bug is fully addressed, and the two additional fixes are correct — the migration handles both v1 states, and the replay anchoring is sound given compaction is gone.
ℹ️ Prior finding still open — assertLifecycle is dead code
The earlier review's note at journal-write-guards.ts:94 is unchanged: assertLifecycle is byte-identical to assert (both are wouldExceedSize + assertRate) and its only remaining references are its own test in journal-row-writer.test.ts. It is not called anywhere in the production path, so it reads as part of the write path while being a duplicate guard. Delete it (and its test assertions) before this merges.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…he v1 quarantine migration doubling the file Replay validated numeric contiguity from sequence 1 but never that sequence 1 IS the epoch row. When the anchor was missing the repair set aside every surviving row, and if provider-history import then failed — a transcript that is temporarily gone is enough — the journal reopened as a clean, row-less epoch: an ordinary append took sequence 1, replay accepted it, read-restore published it as history, and automatic recovery never ran again while the user's real messages sat in quarantine. Replay now rejects an unanchored prefix, the open publishes an `unreconcilable_prefix` anchor for an epoch its repair emptied, and that anchor keeps reporting corrupt — so provider history is retried on every attach — until the timeline is rebuilt or the session writes content of its own. A repair also discloses rows it set aside when no line was unreadable at all, which is the case that removes the most. The v1 quarantine rekey copied every legacy row into the new table inside one transaction and dropped the old one. A quarantine holds whole rejected rows: a single 8 MiB row nearly doubled the database past the physical bound the open had already checked, the dropped pages only reached the freelist, and the next open refused the session it had just migrated. The v1 table is renamed and frozen instead, and reads take both generations. Table creation also moves inside the migration transaction, so a crash can no longer leave a v2-shaped database still reporting version 0 for an older build to write into.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: df430cd9-15d9-4bf7-b410-d8841d288c98
📒 Files selected for processing (13)
src/main/native-chat/agent-session-journal/journal-corruption-repair.test.tssrc/main/native-chat/agent-session-journal/journal-database-schema.tssrc/main/native-chat/agent-session-journal/journal-database.test.tssrc/main/native-chat/agent-session-journal/journal-database.tssrc/main/native-chat/agent-session-journal/journal-open.tssrc/main/native-chat/agent-session-journal/journal-repair-disclosure.tssrc/main/native-chat/agent-session-journal/journal-row-table.tssrc/main/native-chat/agent-session-journal/journal-store-collaborators.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-journal/journal-store.tssrc/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| function repairText(input: { malformedRows: number; quarantinedRows: number }): string { | ||
| const preserved = | ||
| input.quarantinedRows > 0 | ||
| ? `${input.quarantinedRows} row${input.quarantinedRows === 1 ? '' : 's'} after it were set aside and remain recoverable` |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Correct the preserved-row description.
When a malformed row and one following row are quarantined, quarantinedRows is 2. Line 42 tells the user that two rows after the malformed row were set aside. The malformed row itself is also preserved and recoverable. Describe the total quarantined rows instead.
…g the repair marker A transcript that exists but decodes to zero messages was imported as a success: the import published an empty `legacy_import` replacement that deleted the `unreconcilable_prefix` anchor and its disclosure, so the next probe read the session as clean and every later attach skipped provider recovery while the user's rows sat in quarantine for good. The import now leaves the epoch untouched when nothing decodes, reporting `replaced: false`, and recovery treats that like a transcript it could not read — the marker stands and a later attach with real history rebuilds the timeline.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is still withheld for one open prior finding —
assertLifecycledead code — which this commit does not touch.
Reviewed changes
- Anchored replay at the epoch row —
replayJournalnow treats a non-epoch row at sequence 1 (or a missing/empty epoch) ascorruptvia a newunanchoredterm, not just a sequence gap, so a repaired journal can no longer silently adopt an ordinary row as its anchor (journal-open.ts). - Kept the repair epoch asking for history —
awaitsProviderHistorymarks anunreconcilable_prefixepochcorruptwhile it holds nothing but its anchor and the disclosure row, so provider-history recovery keeps retrying until the session writes content of its own. - Republished an anchor after a total repair —
openJournalStoreStatemints a freshunreconcilable_prefixepoch when the replayed epoch folds tolastSequence === 0, so an ordinary append can never take sequence 1. - Froze the v1 quarantine instead of copying it — the migration renames the sequence-keyed table to
journal_quarantine_v1and reads the union, avoiding the copy that nearly doubled the file; table creation and theuser_versionbump now share one transaction. - Widened the repair disclosure — it now fires on quarantined rows (gaps set aside valid rows), not only malformed rows, and moved into
journal-repair-disclosure.tswith a stable item id.
The replay-anchoring change is the risky one and it holds up: the unanchored term only trips when the epoch row is absent or non-epoch (a healthy epoch always folds seq 1 as the epoch row, so lastSequence is never 0 otherwise), and the awaitsProviderHistory predicate stops the moment any non-disclosure row lands. The migration freeze is strictly better than the copy it replaces — the frozen table keeps the same bytes it already held rather than doubling them. The negative controls (crash-before-version-bump leaves no tables, both quarantine generations survive a rekey, the 4 MiB legacy row migrates without breaching the bound) are genuine.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The standing blocker is still the previously-flagged
assertLifecycledead code, which none of these commits touch.
Reviewed changes
- Stopped an empty transcript from rolling the epoch —
importLegacyTranscriptIntoJournalnow returnsreplaced: falsewhen the provider transcript decodes to zero messages, leaving the epoch (and its repair anchor/disclosure) untouched instead of publishing an empty replacement epoch. - Kept the repair marker asking —
rehydratetreats a non-replaced import the same as an unreadable one: it reports an error withimported: 0, so thecorruptprobe still returns true on the next attach and recovery is retried.
This is the right fix and the shape is clean: the replaced flag is required on the sole ok: true variant, so !result.ok || !result.replaced narrows correctly and no caller can forget to check it. The negative control is genuine — it seeds a repairable session, opens against an empty transcript, and asserts the epoch still carries its unreconcilable_prefix anchor and disclosure, that loadJournal still reports corrupt: true, and that a later transcript with content still rebuilds the timeline.
One observation worth noting, not a blocker: the two non-recovery callers (structured-agent-session-host-handoff.ts and structured-tui-transcript-catchup.ts) check only imported.ok before emitting reset('epoch_changed'). With replaced: false they now force a subscriber reset for an epoch that did not change. That is a strict improvement over the previous behavior — which rolled a fresh empty epoch and wiped the timeline on an empty transcript — so nothing to fix, but the reset is now a no-op reload rather than a genuine epoch change.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Re-validated in the running app after the four fix rounds — 7/7 PASSHead The feature is off by default, so it was turned on through the real Settings UI —
1 — send, stream, render
3 — cancel mid-streamInterrupted at 6 — payload bounds and blob spillA tool call producing 60,000 padded lines (~2.6 MB). The citing row is 17,364 bytes of JSON — 4 — hard kill and reattach
Re-proven a second time after a further clean quit and cold restart, rebuilt from the database 5 — one database per session
The fix-round behaviours, exercised directlyCorruption repair preserves rejected rows. A 25-row session was crashed, row 14's body was A repair that empties an epoch republishes an anchor and recovers from provider history. The A corrupt journal is not silently accepted as readable. Before that attach the corrupted Handle ownership. With one session attached, exactly one journal's Notes
|
Review and validation recordThis landed through a plan-first process. Recording it here so a reviewer can see what was checked rather than re-deriving it. Plan. Written up front and put through six independent verification rounds before any code was written. Rounds resolved, in order: whether the hand-rolled machinery was genuinely deleted rather than ported; connection and blob ownership; SQLite allocation semantics (page/WAL growth invalidated the original quota arithmetic); the per-transaction physical charge; busy-checkpoint and Code review. Four rounds, eleven findings, converging 6 → 3 → 2 → 1, with each round's fixes independently confirmed by the next reviewer before it looked for new ground. The findings worth knowing about:
Every fix carries regression coverage that was ablated: each new test was proven to fail against the pre-fix code, with the red counts recorded per fix. Live validation. The full seven-path suite ran twice in a real dev instance driven over CDP, passing 7/7 both times, most recently on the fixed head. That included two hard Two accepted decisionsSessions created before this change stop loading. This is intended and was explicitly chosen: there is no importer for the previous One known unrelated defect. After a mid-turn |
…ill and rate limit Match what comparable implementations do: the journal is an unbounded append-only SQLite log with no side tables and no admission control. Corruption: the rejected suffix is DELETED rather than copied into a quarantine table. The load still reports `corrupt` and recovery still rebuilds the epoch from provider history, so the observable outcome is unchanged — only the preservation half is gone. The schema is back to one version with two tables; no v1 database exists outside unmerged commits of this branch, so the rekey migration and the two-generation read path go with it. Sequence-1 epoch anchoring and the empty-provider-transcript retry are kept: both are about the corrupt signal being correct. Size: no `maxSessionBytes`, so no page-cost arithmetic, reclaim band, incremental vacuum, lifecycle byte reservations or `journal_bound_exceeded`. `auto_vacuum` and `wal_autocheckpoint = 0` existed only to make a transaction's physical cost predictable for that charge; with the charge gone SQLite's default checkpointing is what the journal wants, and the explicit pre-close checkpoint is redundant with the one `db.close()` performs. WAL, `synchronous = FULL` and `busy_timeout` stay. Payloads: an oversized body is truncated at the existing inline cap with the existing marker and the remainder is discarded, bounded at the translation layer that already calls these helpers. The truncation point and message do not change; the content-addressed blob directory and all digest tracking do. Rate: no `maxAppendsPerWindow` and no `journal_rate_exceeded`. `JournalPayloadLimits` is now just the inline cap.
There was a problem hiding this comment.
Important
The simplification itself is clean and consistent — typecheck passes, the journal (156), codex (186), and agent-session-wire (255) suites are green, and grep confirms no dangling references to any deleted module. The blockers are that the PR description still documents machinery this commit deleted, and two load-bearing protections (a durable size bound and full tool-output retention) are gone with no replacement and no acknowledgement in the description.
Reviewed changes
- Removed the physical byte bound and its page arithmetic —
journal-database-space.ts,auto_vacuum,wal_autocheckpoint, the checkpoint/reclaim loop, and themaxSessionBytes/maxAppendsPerWindow/appendWindowMslimits are all gone;JournalRowWriter.enqueueis now a singleinsert + upsert + COMMITtransaction with no quota or rate gate. - Removed the byte-quarantine — a rejected suffix is deleted rather than preserved (
deleteJournalRowSuffix), thejournal_quarantinetable and the v1→v2 migration are dropped, andJOURNAL_DB_SCHEMA_VERSIONreturns to 1. - Removed the blob store and the
blobschannel —journal-blob-store.tsis deleted;boundPayloadnow discards overflow instead of spilling it, andappendItem/tryAppendItem/appendCodexLifecycleItemdrop theirblobsargument across the codex translation and the sink. - Deleted the lifecycle / rate-limit machinery —
JournalAppendBudget,JournalLifecycleAdmission,JournalLifecycleCapacity, and the key bounds (journal-key-bounds.ts) are removed.
⚠️ The PR description describes machinery this commit deleted
The body's "physical quota is repriced" section (page arithmetic, JOURNAL_TXN_FIXED_PAGES = 24, auto_vacuum = INCREMENTAL, wal_autocheckpoint = 0, the charge sweep), the byte-quarantine ("handle ownership", the journal_quarantine table), the blob spill, and the rate limit are all removed by b795704. The description still claims "the 256 MiB per-session bound is unchanged" and walks through four load-bearing behaviours that no longer exist. A reviewer merging on the strength of the body would be approving a design that is not in the code. The description needs to be rewritten to the much smaller scope — one SQLite database per session, an append-only journal_rows table, an inline 16 KiB payload head, and deletion-on-corruption with provider-history recovery.
Technical details
# PR description is stale
## Affected sites
- PR body — still documents `maxSessionBytes`, `auto_vacuum`, `wal_autocheckpoint`,
the quota sweep, `JOURNAL_MIN_SESSION_BYTES`, byte-quarantine, blob spill, and the
rate limit; all deleted by `b795704`.
## Required outcome
- Rewrite the description to describe the journal that actually ships: two tables
(`journal_rows` + `journal_sessions`), schema version 1, WAL/FULL/foreign_keys,
no disk bound, no rate limit, no quarantine, overflow truncated to `inlineHeadBytes`.⚠️ Durable journal growth is now unbounded
Removing maxSessionBytes, the rate limit, compaction, and auto_vacuum together means a long-lived or looping session grows journal.db (and its WAL) without limit. deleteAllJournalRows takes SQLite's truncate optimization but leaves freed pages on the freelist, so epoch rollovers no longer shrink the file, and rollEpoch is only ever triggered by corruption/fork — never by size. The deleted comment at the top of journal-payload-bounds.ts ("a looping agent must not be able to fill the host disk") shows this was a deliberate prior guarantee that is now dropped with no replacement. Worth an explicit confirmation that unbounded durable growth is an intended tradeoff here (and, if it is, a line in the description saying so).
Technical details
# No durable size bound
## Affected sites
- `journal-row-writer.ts` — enqueue does insert + upsert + COMMIT with no size/rate check.
- `journal-database.ts` — no `auto_vacuum`, so freed pages are never returned to the filesystem.
- `journal-payload-bounds.ts` — `JournalPayloadLimits` is now only `{ inlineHeadBytes }`.
## Required outcome
- Confirm the removal of the durable bound is intended and document it, or restore a
bound (page-cost charge or a simple directory-size gate) for the append path.ℹ️ Oversized tool output is now truncated, not spilled
With journal-blob-store.ts gone, boundPayload keeps only the 16 KiB inline head and discards the remainder; the digest and byteLength it still records describe bytes nothing can read back. Previously a 40 MB tool result was retained whole and recoverable after reconnect; the durable reconnect ceiling for a single tool result is now 16 KiB. This is inherent to "drop blob spill" and is a reasonable simplification, but it is a user-visible behaviour change worth stating plainly in the description alongside the other two.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Fresh visual proof at
|
| rows | epoch | transcript landmarks | |
|---|---|---|---|
| before kill | 76 | 02432ab2… |
2 / 1 / 1 / 1 / 1 |
| after restart | 76 | 02432ab2… (same) |
2 / 1 / 1 / 1 / 1 |
PRAGMA integrity_check on the killed database returns ok, with the whole tail still in the write-ahead log. The chat tab is restored, nothing is duplicated, nothing is lost — and the reattached session still accepts new turns and appends them to the same transcript:
5. One database per session, and nothing else — PASS
Every file under the journal root after the whole run:
journal.db
journal.db-shm
journal.db-wal
A search of the entire profile for log.jsonl, snapshot.json, or any blobs/ directory returns nothing. The database carries exactly two tables — journal_rows and journal_sessions — with no quarantine table.
6. A large output is truncated with a visible marker, and the row stays small — PASS
This is the behaviour that changed since the last run: there is no blob file any more, so the remainder is simply discarded and the cut is announced in the text itself.
A 28,892-byte reply is clipped to a 16 KiB head and the marker is rendered on screen:
[Orca: output truncated — 28892 bytes total, digest 89242da93c7b]
The stored row is 16,746 bytes — head plus marker, remainder gone.
The same holds for a large tool result. A shell command producing 348,894 bytes stores head at exactly 16,384 bytes with truncated: true, the original byteLength, and the digest; the row is 20,416 bytes.
One honest gap, and it is not from this change: a tool result also carries a byte-count marker, but the transcript's own tool-detail display clamp cuts the rendered text at 4,000 characters, so that particular marker never reaches the screen. That clamp is untouched here — the three files involved are byte-identical to main. The journal-level truncation is correct in both cases; only the tool-result marker's visibility is affected, and it was already like that before this PR.
Also confirmed: the store is unbounded. Nothing was refused for space at any point.
7. No journal errors, unhandled rejections or handle leaks — PASS
Across both app generations: zero journal or SQLite errors, zero unhandled rejections, zero uncaught exceptions, and no journal entries in the structured main-process trace.
Handle ownership measured directly, since a retained connection is the one new lifecycle obligation here:
| open descriptors under the journal root | |
|---|---|
| one session | 5 |
| second session opened | 9 |
| second session closed | 5 |
The closed session's descriptors are gone entirely and only the live session's remain — the connection is released, not leaked.
One startup warning does appear — a listener-count warning for the app window — but it is emitted before any journal exists, and this change adds no window listeners. Unrelated. A recoverable render error in the status bar's ports segment also fires on startup; it is likewise outside this change, which touches no renderer file at all.
Overall: PASS (7/7). Sessions created before this change are intentionally not migrated and were not exercised, as designed.
…ulti-block tool input A repair that keeps its prefix had nothing durable to show for the suffix it deleted: a sequence gap costs no malformed row, so no disclosure is appended, and the surviving rows keep their epoch anchor. The next probe read a contiguous anchored prefix, called it clean, and the deleted stretch of timeline was never asked for again — silent loss, with the deletion already committed. The deletion now writes a `journal_repairs` marker in the SAME transaction, and replay keeps reporting corrupt while it stands. It retires under exactly the rule the emptied-epoch anchor takes: a fresh epoch carries the rebuild, or the session writes content of its own past the sequence the repair left free. The repair's own disclosure is not that content. Legacy import bounded a tool call's input only when it was the message's sole block; the multi-block path returned `tool-call` unchanged, so a mixed message from Claude, Grok or an omp execution cell persisted the whole input despite `inlineHeadBytes`. `boundBlock` now routes it through `boundToolInput`. Also drops canonical comments describing quarantine, snapshot files, blob storage and blob compaction — none of which exist any more.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is still withheld for the three standing findings from the prior review (stale PR description, unbounded durable growth, truncated tool output) — none of which this commit touches.
Reviewed changes
- Added a durable partial-repair marker — a new
journal_repairstable (schema bumped to v2) records the first sequence a repair left free when it keeps a prefix, so a sequence gap with no malformed row and no disclosure still replays ascorruptinstead of a clean contiguous prefix (journal-repair-marker.ts,journal-open.ts,journal-database-schema.ts). - Retired the marker on every epoch transition —
replaceJournalEpochandpublishNewEpochclear it inside the same transaction, and the marker is epoch-scoped, so a superseded epoch's marker never leaks onto the live one. - Bounded multi-block tool input in legacy import —
boundBlocknow routestool-callblocks throughboundToolInput, closing the gap where a Claude/Grok/omp message carrying a tool call alongside narration imported unbounded (journal-legacy-import.ts).
The partial-repair mechanism is the risky part and it holds up. contentFrom is derived as lastSequence + 1, and the awaitsRebuild predicate exempts the disclosure row it appends, so a repair's own disclosure cannot retire its own marker. The retirement rule mirrors the emptied-epoch anchor: a fresh epoch (from provider-history rebuild) or a session write at contentFrom ends the retry. The negative controls are genuine — a pure sequence gap has no disclosure to pin the corruption on, and the test proves the next probe still reports corrupt until the suffix is rebuilt. Journal directory plus recovery suites (172 tests) and pnpm tc:node are green.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
loadJournal runs on a sync-database connection and returns JournalLoad | null, so both wire call sites were awaiting a non-Promise. The type-aware code-quality gate flags it; the native gate does not.
Fresh visual proof at
|
| before | after the repair | |
|---|---|---|
| rows | 34 (1–19, 21–35) |
19 (1–19) |
journal_repairs rows |
0 | 1 |
journal_repairs: session=codex_d7cb21dc… epoch=37a5e392… content_from=20
The rejected suffix is gone and the marker naming the first free sequence was written in the same transaction.
The second probe still reports corrupt. The surviving rows are a contiguous, anchored prefix — no gap, no malformed row — so the only thing keeping it corrupt is the standing marker:
{ "corrupt": true, "truncateFrom": <absent>, "lastSequence": 19, "malformedRows": 0 }
Ablation, on a byte copy of that same database with only the marker row deleted:
{ "corrupt": false, "lastSequence": 19, "malformedRows": 0 }
That is the old outcome in one line: a contiguous anchored prefix, reported clean, with two turns already deleted and nothing left asking for them. The marker is the whole difference.
It survives a full app shutdown. Quit the app, relaunch: the on-disk journal still replays corrupt: true, so the retry is owed on a later attach rather than settled.
Then the session recovers. Restored full provider history and attached again. The recovery rebuilt the timeline in place:
| value | |
|---|---|
| new epoch | da6db4f5…, anchored at seq 1, reason legacy_import |
journal_repairs |
empty — retired by the fresh epoch |
| rows | 9 (anchor + 4 user + 4 assistant) |
All four turns are back, including the two that were inside the deleted suffix, served through the same agentSession.history call the transcript pages with:
seq 2 user Reply with exactly: ECHO-ONE
seq 3 assistant ECHO-ONE
seq 4 user Reply with exactly: FOXTROT-TWO
seq 5 assistant FOXTROT-TWO
seq 6 user Reply with exactly: GOLF-THREE ← was deleted
seq 7 assistant GOLF-THREE ← was deleted
seq 8 user Reply with exactly: HOTEL-FOUR ← was deleted
seq 9 assistant HOTEL-FOUR ← was deleted
Rendered, in Session History — first prompt ECHO-ONE, last agent line HOTEL-FOUR, 8 messages:
Both arms of the contract therefore hold: while provider history had nothing to give, the marker stood and the retry stayed owed; once it did, the epoch was republished and the marker retired.
3. A large output is still truncated, the marker is visible, the row stays small — PASS
A 28,892-byte reply is clipped to a 16 KiB head with the cut announced in the text itself, rendered on screen:
[Orca: output truncated — 28892 bytes total, digest 89242da93c7b]
Stored row: 16,746 bytes.
Same for a tool result: a shell command producing 348,894 bytes stores head at exactly 16,384 bytes with truncated: true, the original byteLength and the digest — the row is 20,380 bytes, about 6% of the raw output.
The same honest gap as last time, and still not from this change: the transcript's tool-detail display clamp cuts rendered tool text at 4,000 characters, so a tool result's marker never reaches the screen. Those files are byte-identical to main. The journal-level truncation is correct in both cases.
The multi-block half of the second fix — a tool call's input bounded when it sits alongside narration rather than alone in the message — is exercised by the legacy-import suite rather than by a live Codex turn, which emits the sole-block shape. 14 test files, 161 tests pass in the journal directory at this head.
4. One database per session, and nothing else — PASS
Every file under the journal root after the whole run:
agent-session-journal/<workspace>/<session>/journal.db
agent-session-journal/<workspace>/<session>/journal.db-shm (while open)
agent-session-journal/<workspace>/<session>/journal.db-wal (while open)
A search of the entire profile for log.jsonl, snapshot.json, or any blobs/ directory returns nothing. PRAGMA user_version reads 2, and the database carries exactly three tables — journal_rows, journal_sessions, journal_repairs.
5. No journal errors, unhandled rejections or handle-leak warnings — PASS
Across three app generations: zero journal or SQLite errors, zero unhandled rejections, and no journal entries in the structured main-process trace. No journal_bound_exceeded, journal_closed, journal_read_only or journal_stale_fence anywhere in the logs.
Handle ownership measured directly, since the retained connection is the one new lifecycle obligation here: after every clean close — closing the chat tab, and quitting the app — journal.db-wal and journal.db-shm are gone, leaving journal.db alone. The connection is released, not leaked.
Two startup conditions do appear, both outside this change: a listener-count warning for the app window, emitted deterministically at the same point of every launch before any journal exists; and a recoverable render error in the status bar's ports segment. This PR adds no window listeners and touches no renderer file at all.
Overall: PASS (5/5).
Two things worth stating plainly rather than leaving implied:
- A session whose journal is corrupt is deliberately not published as a restorable tab at startup — read-restore refuses it so recovery is retried on a later attach. That is pre-existing and by design, but it means the repair has to be reached through an attach, which is what the hold above is. The recovered session's own tab was not re-published because I had closed it before corrupting the journal, so it was no longer in the tab inventory; its recovered transcript is shown through Session History and the history RPC instead.
- Sessions created before this change are intentionally not migrated and were not exercised, as designed.
#18652 moved the session journal onto SQLite with no importer, so a chat whose history is a `log.jsonl` founds a fresh empty journal beside it and is indistinguishable from one created seconds ago — the epoch reason it records even says `session_created`. No importer here either: the history is not replayed, it is explained. One `status` row says the format is unreadable, names the transcript still on disk, and says how to continue — the session attaches on the record's own provider handle, so the agent still holds the conversation the transcript no longer shows. The row carries the same stable identity the repair disclosure uses, so a reopen upserts it rather than adding another. Read restore has to stop dropping these sessions or the message has nowhere to appear: an unpublished chat is also what prunes its tab out of the saved workspace, so the tab disappears before anything can explain itself. Absence of a database is not absence of history. Nothing is read from the remnant beyond its existence, and nothing moves, rewrites or deletes it.
Second review pass, on the first pass's own fix. Re-offering the notice when the epoch holds nothing reads `loaded.state`, which is the PRE-repair load — so a journal this same open just emptied looks identical to one that lost its append. The repair's `unreconcilable_prefix` epoch is the durable marker that history was deleted and never rebuilt, and `awaitsRebuild` retires it the moment any row that is not the repair's own disclosure appears. Appending here therefore stopped the session ever asking the provider for that history again, while the journal still held none — and handed the user two contradictory explanations in one transcript. Reachability was not limited to the affected users: every session predating #18652 has a `log.jsonl` beside it and nothing deletes it, so any later corruption in any of those directories hit this. Guarded on `!loaded.corrupt`, which preserves the crash-window case exactly — a committed `session_created` epoch whose append was lost loads `corrupt: false`. The regression test needed the right fixture to bite: a malformed row costs a repair disclosure, which fills `items` and hides the branch. Deleting the epoch anchor leaves everything unanchored, so the repair publishes an empty epoch and appends nothing — the one state where this branch and a repair meet. Verified red without the guard. Also from the pass: the status text now goes through `boundJournalStatusText` like every other status body, and a latched (newer-schema) journal is pinned to write nothing, since it loads empty and reaches the same branch where an append would throw and make the session unopenable rather than read-only.
…stablyai#18652) * refactor(agent-session-journal): move the session journal onto SQLite The agent-session journal kept its state in three hand-rolled file formats: an append-only `log.jsonl` with torn-tail repair, a `snapshot.json` holding folded state plus a retained tail, and byte-quarantine files for anything unreadable. This replaces all of it with one SQLite database per session — `journal.db` beside the existing `blobs/` store — using the in-house adapter and the open/pragma/migrate/harden pattern the orchestration database already follows. Two tables: `journal_rows` (the append-only log, keyed by `(session_id, epoch, seq)`) and `journal_sessions` (the derived projection, upserted in the SAME transaction as every insert). Rows stay JSON in one column, so the row schema, the version upcast chain, and the reducer survive byte for byte — `journal-reducer.test.ts` and four other suites pass unchanged and are the regression proof. Deleted: `journal-log-file.ts`, `journal-compaction.ts`, `journal-corruption-quarantine.ts`, and the public `compact()` / `compactionBoundary` / `autoCompact` members, none of which had a non-test caller. Existing `log.jsonl` / `snapshot.json` journals are deliberately abandoned. No importer: a session created on the old path stops working, which is acceptable because the feature is off by default. ## The physical quota is repriced, because SQLite does not charge like a file The 256 MiB per-session bound is unchanged, but the arithmetic under it could not survive: SQLite grows the database in pages and the WAL in frames, and the checkpoint that copies the WAL forward holds the same pages in both files at once, so a transaction's peak is about twice its content. Admission now charges the candidate transaction's own measured page cost, validated against a sweep that runs as a regression test (`journal-database-space.test.ts`) rather than derived from reasoning about the allocator. Four things are load-bearing rather than tuning, each measured: - `auto_vacuum = INCREMENTAL` must be set BEFORE `journal_mode = WAL`. Set it after and it is ignored with no error, reclamation silently becomes a no-op, and the file never shrinks again. Both halves are asserted. - `wal_autocheckpoint = 0` plus an explicit `wal_checkpoint(TRUNCATE)` at the end of every write path, so the one moment the same pages live in two files is a moment the charge accounts for. - Reclamation runs in bounded chunks. A single unbounded `incremental_vacuum` took a 252 MB directory to 504 MB — the reclamation added to defend the bound would have breached it. `PRAGMA incremental_vacuum(N)` also frees exactly one page unless it is stepped to completion, which no size assertion catches, so the freed page count is asserted directly. - A blocked checkpoint leaves the WAL on disk together with the database growth it already copied, so admission charges that deferred copy explicitly. The term is zero whenever the last checkpoint succeeded, so the uncontended path admits and refuses an identical set. The epoch discard is `DELETE FROM journal_rows` with no WHERE clause, which takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL bytes where the `WHERE session_id = ?` form rewrote every emptied leaf at up to 99%. One database per session is what makes the unqualified form correct. An open, empty journal costs 57,344 bytes before a single row exists, so a configured quota below `JOURNAL_MIN_SESSION_BYTES` now fails loudly at open with the existing `journal_bound_exceeded` instead of as a run of identical append failures. No production caller configures one; the affected surface is test fixtures, rescaled to the smallest value that restores what each case proves. ## One deliberate behaviour change Compaction was the only mechanism that shed bytes inside an epoch, and the write path called it precisely so an append at the bound was not refused. The SQLite-shaped replacement — a bounded prefix delete — cannot be used: with the snapshot gone the surviving rows ARE the state, so dropping the oldest of them loses the oldest transcript silently at the next reopen. So no row is ever shed inside an epoch, and a session whose row bytes alone reach the bound now refuses every append where it previously compacted and continued. A loud typed refusal beats silent data loss. What still sheds is unreferenced BLOB bytes — the dominant and unbounded byte source — on the same write-path hook. The escape from the hard stop is the fold that already exists, `replaceEpochItems`, which now actually returns bytes to the filesystem instead of leaving them on the freelist. The prune's protected set is a union of live reducer digests AND the candidate row's own digests, including those cited only by a nested lifecycle-batch mutation. Content addressing never rewrites a digest already on disk, so protecting live state alone deletes the blob the append is about to cite — a dangling reference that surfaces one reopen later as an empty expansion on an item the user can see. `journal-store-blob-budget.test.ts` pins it, and it goes red when the set is narrowed back. ## Handle ownership A file handle used to be opened and closed per append; a SQLite handle is held for the session's lifetime. Every path that can open a connection now has one owner: the open function owns its raw connection until it returns, the store owns its retained one and releases it in a new `close()`, and every other connection is closed by the call that opened it. The attach, recovery, eviction, map-overwrite and host-teardown paths close what they drop, and host teardown is failure-complete — the sink-barrier flush throws by design, so a trailing close statement would be skipped on exactly the path that leaks. `close()` has a stated contract: admission at enqueue and permanent, the close step on the same queue past that gate, one shared in-flight attempt, fulfilment terminal, and the release last and deliberately unguarded so a retry re-enters it. Guarding the release would skip it on retry, guaranteeing a permanent leak in exactly the case where it did not release. `journal_closed` joins the error union for a write after `close()`; no file outside the directory references any of these codes. * fix(agent-session-journal): make a COMMIT final, stop repairs deleting valid rows, and keep rejected closes retryable Six review findings on the SQLite journal migration. 1. A successful COMMIT is now the point of no return. The ordinary append, the epoch roll and the epoch replacement each adopt the committed row or epoch BEFORE any post-commit filesystem work; checkpoint, reclaim, blob prune and directory measurement run through `runJournalPostCommit`, which is best-effort by design and falls back to the transaction's own charge as a conservative footprint. Previously a post-COMMIT scan failure rejected a durable append and the next one reused its sequence, and a failed epoch housekeeping step left the store writing into a prefix already deleted. 2. Corruption repair preserves instead of destroying. A rejected suffix is copied into a new `journal_quarantine` table and removed from the live epoch in ONE transaction per chunk, charged against the session bound before a byte is written; a journal that cannot afford the copy refuses to open rather than falling back to deletion. The repair state is exposed as `journal.repair` and the rows are readable through `recoverQuarantinedRows()`, so Orca-owned submission, receipt and lifecycle identity survives a gap or a malformed row. 3. The physical charge covers the B-tree key payload. `session_id` and `epoch` are stored in both tables and both primary-key indexes and appear nowhere in `row_json`, so the journal boundary now bounds them and `journalTxnPhysicalCost` charges those bounds plus the projection upsert. The charge sweep runs the exact production transaction at maximum admitted key sizes. 4. A rejected `close()` no longer orphans its handle. Callers hand the journal to `agentSessionJournalCloseRetries` instead of swallowing the rejection, the attach map replacement is ABORTED when the previous journal will not close, host teardown retries what the registry holds, and a failed runtime teardown is retained so the next stop is a real retry. 5. `journalWalBytes()` returns zero only for ENOENT and propagates every other stat error, so admission and reclamation fail closed. 6. The WAL contention test closes the writer before removing its temp root and asserts the directory is removable once handles close. Regression coverage: post-commit divergence (4), corruption repair (5), key bounds (5), WAL stat (8), close retry (5), plus a runtime stop-retry case. Each fix was ablated on this head and the matching tests go red. * fix(agent-session-journal): anchor replay at sequence 1, make quarantine append-only, and charge it in bytes Three ways the corruption quarantine still lost rows it was written to keep. Replay validated contiguity from the first row that HAPPENED to remain, so an epoch missing only its sequence-1 row declared the leftovers contiguous and set no `truncateFrom`. The load was still corrupt, so recovery imported provider history and `replaceEpochItems` deleted every live row — including Orca-minted submission, receipt and lifecycle identity that no transcript can reconstruct, and that nothing had quarantined. Replay now anchors at sequence 1, so a missing epoch row rejects the whole surviving range before any replacement runs. `journal_quarantine` was keyed on `(session_id, epoch, seq)` and copied with `INSERT OR REPLACE`. A repair frees the sequences it removed and the live epoch reuses them, so a second repair in the same epoch silently deleted what the first preserved. The table is now keyed on a surrogate `quarantine_id`, the copy is a plain append, and `(epoch, seq)` is metadata; existing v1 databases are rekeyed in the migration that already bumps `user_version`. The admission charge read `length(row_json)`, which counts CHARACTERS for a TEXT value where `journalTxnPhysicalCost` expects physical UTF-8 bytes. A multibyte suffix was charged at up to a third of what it writes, which defeats the pre-write physical bound — over a megabyte on a maximum-size lifecycle batch. * fix(agent-session-journal): keep a repaired epoch anchored and stop the v1 quarantine migration doubling the file Replay validated numeric contiguity from sequence 1 but never that sequence 1 IS the epoch row. When the anchor was missing the repair set aside every surviving row, and if provider-history import then failed — a transcript that is temporarily gone is enough — the journal reopened as a clean, row-less epoch: an ordinary append took sequence 1, replay accepted it, read-restore published it as history, and automatic recovery never ran again while the user's real messages sat in quarantine. Replay now rejects an unanchored prefix, the open publishes an `unreconcilable_prefix` anchor for an epoch its repair emptied, and that anchor keeps reporting corrupt — so provider history is retried on every attach — until the timeline is rebuilt or the session writes content of its own. A repair also discloses rows it set aside when no line was unreadable at all, which is the case that removes the most. The v1 quarantine rekey copied every legacy row into the new table inside one transaction and dropped the old one. A quarantine holds whole rejected rows: a single 8 MiB row nearly doubled the database past the physical bound the open had already checked, the dropped pages only reached the freelist, and the next open refused the session it had just migrated. The v1 table is renamed and frozen instead, and reads take both generations. Table creation also moves inside the migration transaction, so a crash can no longer leave a v2-shaped database still reporting version 0 for an older build to write into. * fix(agent-session-journal): stop an empty provider transcript retiring the repair marker A transcript that exists but decodes to zero messages was imported as a success: the import published an empty `legacy_import` replacement that deleted the `unreconcilable_prefix` anchor and its disclosure, so the next probe read the session as clean and every later attach skipped provider recovery while the user's rows sat in quarantine for good. The import now leaves the epoch untouched when nothing decodes, reporting `replaced: false`, and recovery treats that like a transcript it could not read — the marker stands and a later attach with real history rebuilds the timeline. * style(agent-session-journal): merge the duplicate journal-database-space import * refactor(agent-session-journal): drop quarantine, byte bound, blob spill and rate limit Match what comparable implementations do: the journal is an unbounded append-only SQLite log with no side tables and no admission control. Corruption: the rejected suffix is DELETED rather than copied into a quarantine table. The load still reports `corrupt` and recovery still rebuilds the epoch from provider history, so the observable outcome is unchanged — only the preservation half is gone. The schema is back to one version with two tables; no v1 database exists outside unmerged commits of this branch, so the rekey migration and the two-generation read path go with it. Sequence-1 epoch anchoring and the empty-provider-transcript retry are kept: both are about the corrupt signal being correct. Size: no `maxSessionBytes`, so no page-cost arithmetic, reclaim band, incremental vacuum, lifecycle byte reservations or `journal_bound_exceeded`. `auto_vacuum` and `wal_autocheckpoint = 0` existed only to make a transaction's physical cost predictable for that charge; with the charge gone SQLite's default checkpointing is what the journal wants, and the explicit pre-close checkpoint is redundant with the one `db.close()` performs. WAL, `synchronous = FULL` and `busy_timeout` stay. Payloads: an oversized body is truncated at the existing inline cap with the existing marker and the remainder is discarded, bounded at the translation layer that already calls these helpers. The truncation point and message do not change; the content-addressed blob directory and all digest tracking do. Rate: no `maxAppendsPerWindow` and no `journal_rate_exceeded`. `JournalPayloadLimits` is now just the inline cap. * fix(agent-session-journal): mark a partial repair pending and bound multi-block tool input A repair that keeps its prefix had nothing durable to show for the suffix it deleted: a sequence gap costs no malformed row, so no disclosure is appended, and the surviving rows keep their epoch anchor. The next probe read a contiguous anchored prefix, called it clean, and the deleted stretch of timeline was never asked for again — silent loss, with the deletion already committed. The deletion now writes a `journal_repairs` marker in the SAME transaction, and replay keeps reporting corrupt while it stands. It retires under exactly the rule the emptied-epoch anchor takes: a fresh epoch carries the rebuild, or the session writes content of its own past the sequence the repair left free. The repair's own disclosure is not that content. Legacy import bounded a tool call's input only when it was the message's sole block; the multi-block path returned `tool-call` unchanged, so a mixed message from Claude, Grok or an omp execution cell persisted the whole input despite `inlineHeadBytes`. `boundBlock` now routes it through `boundToolInput`. Also drops canonical comments describing quarantine, snapshot files, blob storage and blob compaction — none of which exist any more. * fix(agent-session-wire): stop awaiting the synchronous journal probe loadJournal runs on a sync-database connection and returns JournalLoad | null, so both wire call sites were awaiting a non-Promise. The type-aware code-quality gate flags it; the native gate does not. --------- Co-authored-by: Merge Sim <sim@local>



















What this changes
src/main/native-chat/agent-session-journal/kept one session's durable state in three hand-rolled file formats: an append-onlylog.jsonlwith torn-tail repair, asnapshot.jsonholding folded state plus a retained tail, and byte-quarantine files for anything unreadable. This replaces all of it with one SQLite database per session —journal.dbbeside the existingblobs/directory — throughsrc/main/sqlite/sync-database.tsand the open/pragma/migrate/harden patternsrc/main/runtime/orchestration/db/already uses.Two tables.
journal_rowsis the append-only log keyed by(session_id, epoch, seq);journal_sessionsis the derived projection, upserted in the same transaction as every row insert. Rows stay JSON in one column, sojournal-row-schema.ts, thevupcast chain andjournal-reducer.tssurvive byte for byte.Deleted:
journal-log-file.ts(365 lines),journal-compaction.ts,journal-corruption-quarantine.ts, and the publiccompact()/compactionBoundary/autoCompactmembers — none had a non-test caller.No importer. Existing
log.jsonl/snapshot.jsonjournals are deliberately abandoned: a session created on the old path stops working.experimentalStructuredNativeChatis off by default, so the blast radius is small by construction.Nothing crosses the remote wire. This directory has zero
src/relay/and zero renderer importers — no RPC params, no stream opcodes, no change to what the host publishes.node:sqliteis a Node builtin, so there is noelectron-builderentry, no native rebuild, and no glibc floor to hold.The physical quota is repriced, because SQLite does not charge like a file
The 256 MiB per-session bound is unchanged — still physical bytes under the session directory, still enforced by the same typed
journal_bound_exceeded. The arithmetic under it could not survive the swap.SQLite grows the database in pages and the WAL in frames, and the checkpoint that copies the WAL forward holds the same pages in both files at once, so a transaction's peak is about twice its content, not equal to it. Meanwhile a transaction that reuses already-allocated pages grows the directory by zero, and the old arithmetic charged its full JSON length anyway. Admission now charges the candidate transaction's own page cost, computed from the rows it will insert, and that formula is validated by a sweep kept as a regression test rather than by reasoning about the allocator.
Four behaviours are load-bearing rather than tuning, each measured:
auto_vacuum = INCREMENTALset beforejournal_mode = WAL2, and a WAL-first open reads back0.wal_autocheckpoint = 0plus an explicitwal_checkpoint(TRUNCATE)ending every write pathincremental_vacuumtook a 252 MB directory to 504 MB — the reclamation added to defend the bound would have breached it.PRAGMA incremental_vacuum(N)also frees exactly one page unless stepped to completion, which leaves every size assertion green while recovering almost nothing, so the freed page count is asserted directly.The epoch discard is
DELETE FROM journal_rowswith no WHERE clause, which takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL bytes across three row-size mixes, where theWHERE session_id = ?form rewrote every emptied leaf at up to 99%. One database per session is what makes the unqualified form correct.Lifecycle reservations move onto the same currency, so a token granted for a terminal write actually covers its page cost rather than its JSON length.
A new floor. An open, empty journal costs 57,344 bytes before a single row exists. A configured
maxSessionBytesbelowJOURNAL_MIN_SESSION_BYTESnow fails at open with the existingjournal_bound_exceeded, naming the floor, instead of being discovered as a run of identical append failures. No production caller configures one — every non-test use takesDEFAULT_JOURNAL_PAYLOAD_LIMITS— so the affected surface is test fixtures, each rescaled to the smallest value that restores the relationship its case proves.One deliberate behaviour change
Compaction was not only substrate. It was the one mechanism that shed bytes inside an epoch, and
journal-row-writer.tscalled it precisely so an append at the bound was not refused.The SQLite-shaped replacement — a bounded prefix
DELETE— cannot be used. Compaction folded shed rows intosnapshot.jsonbefore truncating, so the conversation they carried survived; with the snapshot gone the surviving rows are the state, and dropping the oldest of them loses the oldest transcript silently at the next reopen. Keeping the fold would mean persisting rendered state again, which is the machinery this change exists to delete.So: no row is ever shed inside an epoch, and a session whose row bytes alone reach the bound now refuses every append with
journal_bound_exceededwhere it previously compacted and continued. Trading a loud typed refusal for silent transcript loss is the worse of the two.What still sheds is unreferenced blob bytes — the dominant and unbounded byte source, since a row's inline payload is capped at 16 KiB while the remainder of a 40 MB tool result is a whole file. The escape from the hard stop is the fold that already exists,
replaceEpochItems, which now actually returns bytes to the filesystem instead of leaving them on the freelist.The prune's protected set is a union, and that is a regression test
pruneJournalBlobsremoves every file outside the set it is handed, and the write path never rewrites an existing digest. Protecting only live reducer state therefore has a concrete failure: a superseded row carries digestD, its file is still on disk,Dis absent from live state because a higher revision won, and this append reusesD— which happens whenever an identical bounded payload recurs across revisions or across the geometric streaming checkpoints. The prune deletesD, the transaction inserts a row citing it, and the next reopen renders an item whose blob is gone.The set is live digests ∪ every digest the candidate row carries — its
blobsargument and its own body, including those cited only by a nestedlifecycle-batchmutation, because a row can cite a digest that is not in that argument at all.journal-store-blob-budget.test.tspins it and goes red when the set is narrowed back.Handle ownership
A file handle used to be opened and closed per append. A SQLite handle is held for the session's lifetime, which is the one genuinely new lifecycle obligation here — and on Windows an open handle blocks the
renameandunlinkthat recovery, workspace cleanup and every temp-root test perform, while on POSIX every such leak is silent.Every path that can open a connection now has exactly one owner. The open function owns its raw connection until it returns (a
transferredflag plus afinally). The store owns its retained connection and releases it in a newclose(), andopen()closes it on any throw after it exists. Every other connection is closed by the call that opened it — the standaloneloadJournalprobe self-closes, and the attach, recovery, eviction, map-overwrite and host-teardown paths close what they drop. Two callback types became() => Promise<void>and are now awaited, because "close before delete" means nothing when the delete returns while the close is still queued.Host teardown is restructured to be failure-complete: the sink-barrier flush throws by design, so a trailing "close every journal" statement would be skipped on exactly the path that leaks. Each phase's failure is captured, every journal is closed with
allSettled, only entries whose close fulfilled are removed from the map, and anAggregateErrorcarries the originals out.close()has a stated contract with five parts:close()is admitted and runs to completion; anything offered afterwards is refused before it joins the queue, so no write is ever chained behind a close.DatabaseSync.close()raisesERR_INVALID_STATE, so re-entering after success is the bug, not the fix.db.close()that threw released the handle first, and guarding the step would skip it on retry — guaranteeing a permanent leak in exactly the case where it did not release.journal_closedjoins the error union for a write afterclose(). Grep confirms zero files outside the directory reference any of these codes, so widening it is additive.Migration and version refusal
Two independent version axes, both fail closed.
PRAGMA user_version, read first, on a connection that has set no persistent pragma and run no DDL, becauseCREATE TABLE IF NOT EXISTSand both header-writing pragmas would all violate the "no write, no delete" promise a future-schema file is owed. A latched open closes that connection and reopens{ readonly: true, fileMustExist: true }.vfield and theparseJournalRowupcast chain, unchanged. A same-user_versiondatabase can still hold a row this build cannot read.assertJournalWritable/journal_read_onlyare untouched; only the trigger moves, and it now fires before the first read rather than mid-load. Byte-copy quarantine is deleted rather than ported: with one database per session the file is the preserved bytes, and nothing writes to a latched one. Production recovery stays exactly where it lives, in the wire layer — a future-schema journal is rehydrated into the-recovered-v<N>sibling and never merged back.The
(session_id, epoch, seq)primary key also makes a duplicate sequence a constraint failure instead of a silent double-write. The lease fence already prevented two writers; the failure mode is just louder.Tests
210 tests pass in the journal directory, 8,347 across the journal, wire, codex and runtime suites.
Five in-directory suites pass completely unchanged and are the primary regression proof: the 464-line reducer suite, item identity, cursor resume, row schema, and lifecycle capacity — 76 tests, no edits.
Behaviour assertions elsewhere are preserved. The twelve edited external files get a shared tracked-close teardown helper; tracking every opened instance rather than a variable is the point, since one suite reassigns its module-level journal to a second store mid-suite. Five of those also needed fixture surgery — raw
log.jsonlwrites become row inserts, and a hole punched in a log becomes a deleted mid-sequence row, which is the same logical holefindSequenceGapalready detects.New suites, each pinning something a green run alone would not prove:
One thing to look at
The measured page charge needed a larger fixed-page allowance than the design assumed. Running the sweep against a 256 MB database showed a transaction can dirty more existing pages than newly allocated ones — the WAL carries the modified interior chains of all four b-trees this schema has (
journal_rowsandjournal_sessionsare each a table plus the implicit unique index their composite primary key creates), plus page 1 and the pointer map. The worst measured requirement was 13 pages; the constant is 24, and the sweep is what keeps it honest. Without the correction the sweep failed by ~4 KB on a 6-row transaction, which is a small breach of a bound whose entire job is to cap disk.