feat(storage): add lossless compression for cold runtime history #6115
P2: apps/desktop/src/main/__tests__/main-startup-lifetime.test.ts ("mounts the handoff overlay inside the locale providers") searches this file for <RuntimeHostHandoffOverlay. After this rename it fails, and that is the current CI test failure. Please update the assertion, including the doesNotMatch against app.tsx.
P2: callers of waitForRuntimeHostReady get this separate upgrade budget, but verifyRuntimeHostManagedServiceReady (packages/cli/src/runtime-host-service-manager.ts) does not. It runs its own 45 s loop and treats upgrading_storage as a failure. If a managed-service update/start/configure lands on a legacy database whose conversion runs past about 45 s, the CLI retires the Host in the middle of the VACUUM. By then the schema is already v3/21, so the previous package cannot open the root either. Each retry reruns the full conversion and hits the same timeout.
P3: this comment says the initial durable value is disabled, but COLD_STORAGE_DEFAULT_WRITER_ENABLED is 1. This option is also not wired to any setting or CLI command, so users have no product-level way to opt out of compression or of the startup conversion.
P3: rows skipped here because they are already checked_policy stay in the runtime_cold_candidates partial index. The session-level EXISTS keeps finding them, so every pass after the 60 s idle rescans all of them at one 64-row batch per second. Records that fail to encode are not recorded anywhere, so they are retried, and reported via onError, on every pass.
P3: #failure is never cleared. One worker exit, such as an OOM, makes every later transcript page read throw until the Host restarts, because withSessionRead and #enqueue reject immediately and there is no in-process fallback. Consider respawning the worker or falling back to the in-process reader.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.
First full review of 1751c399..0c34ac45 (3 commits; the merge base is the current tip of main). I found no prior review findings to carry forward. The diff is about 2,400 lines of product code, 1,780 lines of tests and 950 lines of scripts/perf harness across 65 files.
Summary. The codec looks lossless as written. Each record keeps its original UTF-8 JSON text inside a zstd frame. That frame is verified on read with a length check, a sha256 and a projection check, and encode refuses to publish unless the round trip reproduces the exact input string. I ran the codec in isolation against BOMs, emoji, U+2028, escaped lone surrogates, pretty-printed and reordered keys, __proto__, duplicate keys, oversized integers and \/ escapes, and every one restored byte for byte. Values that JSON cannot round-trip (-0, 1e400) fail closed and keep their raw bytes. Publication is a compare-and-swap UPDATE ... WHERE payload_json = ? inside a write transaction. That transaction rechecks the activity version, the cooling age and the policy epoch, so a crash or a concurrent append cannot leave a half-written or stale row. Readers on WAL snapshots decode either representation to the same bytes. I found no remaining SQL json_extract on fields that compression removes; every control field that SQL reads stays in the projection. Two P2 findings block merge. A larger P3 point is that the rollout runs ahead of decisions maintainers have not made yet.
P2: CI test fails because of this PR. apps/desktop main-startup-lifetime.test.ts ("mounts the handoff overlay inside the locale providers") searches app-shell.tsx for <RuntimeHostHandoffOverlay. This PR renames that element to <RuntimeHostLifecycleOverlay. CI on main at the merge base (1751c399) is green. Update the source-text assertion, including its doesNotMatch against app.tsx. The package job was still pending when I checked.
P2: CLI-managed Host services cannot get through a long storage conversion. waitForRuntimeHostReady gains a separate 30-minute budget for upgrading_storage. verifyRuntimeHostManagedServiceReady (packages/cli/src/runtime-host-service-manager.ts, around line 1301) has its own 45 s loop and counts any state other than ready as a failure. maka host update, start and configure use that check. If NONE→INCREMENTAL VACUUM plus integrity_check takes longer than about 45 s, the CLI retires the replacement Host, which aborts the conversion. #6000 measured roughly 55 s for a production-shaped 1 GB database and 64 s for 3 GiB on Windows. The schema has already moved to v3/21 by that point, so an older package cannot open the root either. The marker stays running, not failed, so each later CLI start reruns the full VACUUM and hits the same timeout. I traced this from the code and did not reproduce it. A fix could treat upgrading_storage as progress in that loop and give it the upgrade budget.
P3: the rollout runs ahead of maintainer decisions.
COLD_STORAGE_DEFAULT_WRITER_ENABLED = 1 turns it on. The PR body raises this question; the comment at execution-composition.ts:333 still says the initial value is disabled.coldStorageWriterEnabled is not wired to any setting, env var or CLI command. The only off switch is a repo-checkout script, so users cannot opt out of compression or of the startup conversion.P3: scope. Splitting this along its independent axes would make each part reviewable and keep a regression in one from reverting the others:
1. Reader-only codec support, with the writer off.
2. The compression lane.
3. Startup NONE→INCREMENTAL conversion plus the Desktop upgrade UI and the epoch bump. This part needs the #6000 decision.
4. Moving foreground transcript reads into a worker thread with its own read-only connection. This is a separate architectural change, and #6000 already flagged a second connection as a departure from the single-owner model.
P3: overlap with open #6083. Both PRs add a maintenance lane named runtime page reclamation that runs incremental_vacuum on runtime.sqlite. storage-maintenance.ts and execution-composition.ts merge with no textual conflict, so merging both would run two such lanes; only the test file conflicts. Agree with #6083 on which one owns this before either lands. The conversion itself fits #6044: new databases are already INCREMENTAL, and FULL databases switch without a rebuild.
P3: robustness and cost.
checked_policy rows ("not worth compressing") stay in the runtime_cold_candidates partial index. Every pass after the 60 s idle rescans them in batches of 64 at one batch per second, so the lane rarely settles while such rows exist. Records that fail encoding are not recorded at all, so they are retried, and reported through onError, on every pass.TranscriptStorageWorker.#fail is permanent. A single worker exit, such as an OOM, makes every later transcript page read fail until the Host restarts, and there is no in-process fallback. A queue of more than 32 reads is rejected outright.integrity_check, or SQLITE_CORRUPT during VACUUM, now blocks Host startup with no repair path. Databases with latent damage that worked before will stop starting.runtime_events, session_messages, core_agent_run_events and the partial snapshot/segment tables now also upserts session_content_activity. That includes every streaming segment insert and update, which puts an extra write on the hot path.Migration and downgrade. Runtime schema goes 20→21, operational schema 2→3, and the epoch 222→223. Once a root starts on this build, an older build refuses it; restoreBatch restores payload bytes but not the schema. Backup restore already requires the current schema. Restore also resets the writer to the default (enabled) and drops an explicit disable carried in the backup.
Protocol epoch. host-status.ts adds the upgrading_storage state and storageUpgradePhase, and the epoch moves 222 → 223. I confirmed main is at 222. Older peers reject the unknown lifecycle state, so the bump is justified. Open #5980 also declares 223, so one of the two will need to renumber (P3).
CI and mergeability. GitHub reports the PR as mergeable, blocked only on review. test fails (P2 above), package was still pending, and the other checks pass.
P3: open #6083 adds a lane with the same name that runs incremental_vacuum on runtime.sqlite. These files merge with no textual conflict, so landing both would run two reclamation lanes. Please agree with #6083 on which one owns this.
<!-- maka-lifecycle:stale-warning -->
This pull request has had no new commits for 30 days and has been marked stale. It will be closed in 7 days unless a new commit is pushed.
Comments do not reset this timer: only a new commit does. If the pull request is intentionally long-lived, a maintainer can apply the pinned label.
<!-- maka-lifecycle:stale-close -->
This pull request has been closed because it received no new commits during the 7-day grace period. This is not a judgement on the merit of the change; it only keeps the review queue aligned with work that is actively in flight.
The branch and review history are preserved. Push a new commit and reopen the pull request whenever the work is ready to continue.
Astro-Han
testikun
Summary
Long-lived Sessions retain large plaintext RuntimeEvent bodies even after writes stop. Compress completed text, thinking, tool calls and tool responses losslessly after seven days without an actual local content write, preserving exact JSON bytes, provider metadata, signatures, tool evidence and indexed control fields. Reads keep the stored representation compressed; continuing a Session appends ordinary records and restarts its cooling period.
Fixes #6109
Verification
Local macOS validation: root build, Desktop main/preload/renderer/Storybook typechecks, affected-file format/lint, ASF headers, protocol epoch guard and diff checks pass. Complete Storage, Host, Host assistant, Desktop and CLI regression run: 9,480 passed, 23 conditionally skipped, 0 failed. The latest Desktop wiring also passes the strict renderer architecture check, generated UI inventory check, main/renderer builds, 32 targeted tests and the real-client upgrade/quit/restart experiment. An existing two-second Host polling test timed out under the first parallel run; it passed alone and in the complete suite with bounded concurrency, without weakening its assertions or extending its deadline.
| Experiment | Result |
| --- | --- |
| Complete historical SQLite copy, all source tables retained | 1,148,002,304 B after conversion → 512,114,688 B after compression/reclamation (55.39%); all 185,930 event bodies retain their exact bytes |
| Replayed event corpus, 3,000 warm paging samples per phase | p95 21.23 ms raw → 19.11 ms compressed → 20.36 ms after reclamation |
| Decode-cache ablation | p95 22.9 ms without cache vs 19.8 ms with a bounded immutable-string cache; identical page content |
| SQLite auxiliary threads, one trial each | 0 / 2 / 8 threads: 8.19 / 8.30 / 8.33 seconds; no speedup observed, default remains 0 |
| Real Electron client | Upgrade progress stays responsive; normal quit and restart preserve the full event digest and reach Host readiness |
| Failure and packaging checks | Process death during conversion permits recovery/retry; ASAR read, codec and conversion workers preserve pages, landmarks and recall candidates |
Source databases were read-only; benchmarks aged disposable copies explicitly. OS file caches were not purged, so first reads are not cold-disk measurements. The complete-copy run uses only 30 repeated pages for correctness; the paging p95 comparison above comes from the separate 3,000-sample replay run.
Migration and rollout
Runtime schema 20 → 21, operational schema 2 → 3, and Host compatibility epoch 222 → 223. Older binaries reject the newer schema/epoch; restoring payload bytes does not downgrade the whole database schema.
Legacy NONE conversion may need approximately twice the current database file size plus 64 MiB of free space. It runs with WAL and synchronous=FULL before ordinary business writers open. Busy/low-space/failed attempts defer safely; actual corruption blocks startup. SQLite recovery protects interruption, but the implementation does not promise percentage-based resume or simulated power-loss coverage.
Compression defaults to enabled after cooling, preserving an existing explicit disable. The issue initially suggested a disabled rollout while validation/review was pending; please review the enabled default and automatic startup conversion before merging.
Review notes
AI use
Tool(s) and scope: OpenAI Codex authored implementation, tests, benchmark scripts and this PR description at @testikun's request. The commits include Generated-by trailers.
Checklist
Does this PR entail a change in behavior?