Skip to content

perf(storage): bound retained database and worker data - #864

Merged
nixuuu merged 3 commits into
devfrom
perf/optimize-database-storage
Nov 16, 2026
Merged

nixuuu merged 3 commits into
devfrom
perf/optimize-database-storage

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Change

Streaming events currently create unnecessary notice invalidations and retain duplicate text, sync revisions, and unused files indefinitely. This change reduces write amplification and adds bounded, resumable cleanup for both existing and newly written data.

  • Filter notice replication triggers to actual notices, including kind transitions and deletion tombstones.
  • Batch adjacent delta projection writes and store exact duplicate raw text as lossless references to the same event payload. SQL compaction preserves numeric precision and reconstructs provider metadata; bounded maintenance also compacts eligible historical events.
  • Retain a contiguous 10,000-record sync replay suffix with a one-hour grace period and active-reader protection. Clean obsolete epochs/content while preserving current lazy content and rebuilding expired readers safely.
  • Permanently clean manually deleted thread history after 31 days, independently of optional archive retention. Preserve fork dependencies, active work, owner boundaries, deduplication state, and shared attachment references.
  • Collect abandoned unbound uploads after 30 days and unreferenced non-exempt blobs after seven days. Protect composer, bot, and rewind drafts, including conservatively handled legacy drafts.
  • Add capability-gated worker cleanup after completed database purge, with durable grants, admission/restart safety, managed-path restrictions, and import/session protections. Gateway and worker must both be updated for local file cleanup; workspace files remain intact.
  • Preserve exact Codex image bytes before compacting new inline raw data, protect pending journal references, and keep three update releases plus current/rollback/staged versions.
  • Add read-only storage inspect and explicit storage reclaim --offline --table .... Ordinary maintenance frees PostgreSQL space for reuse; physical disk reclamation is never automatic.
  • Fix a Claude startup race found by the live restart/fork test: idle cleanup now waits for first-turn admission.

Migrations 0153–0157 are additive. Historical journal rows receive a fresh one-hour protection period. Existing inline image history remains until thread purge, and legacy retention-exempt blobs remain protected. Cleanup starts automatically with the gateway and proceeds in bounded transactions.

Fixes: #27

Verification

Selective local verification passed during implementation:

  • Fresh PostgreSQL 17 migrations/schema: 23 tests.
  • Notice replication/schema: 27 tests, plus real worker↔gateway sequence regression.
  • Ingest, lossless transcript storage, event storage, and recovery/schema: 46 tests. Coverage includes exact numeric raw reconstruction, fork/restart integrity, and three projection writes for start/delta-run/completion.
  • Replication retention: four tests, including 12,512 → 10,000 journal records and removal of 16 MiB orphan content; existing range/window/remote/lock/compatibility coverage also passed.
  • Deleted/archive retention, attachment/blob GC, and worker cleanup: focused PostgreSQL, filesystem, durable journal, admission, and real WorkerLink tests passed. Storage CLI: five tests. Update-cache retention tests passed.
  • Live Codex + Claude through CLIProxyAPI on a fresh schema: two tests, 68 assertions. Full 320-line output, exact image/raw reconstruction, cold restart, resume, fork, and owner scope passed. Codex raw saved 25,801 bytes (34.3% of raw JSON in that fixture); this is not a whole-database reduction. Claude raw remained unchanged. Physical relation files did not shrink.
  • Worker, gateway, integration, DB, and updater scoped typechecks; edited-file lint/format; proto generation; diff checks passed.

Copy audit (§8): PASS. Delete confirmation previously mentioned immediate deletion and brief Undo; it now states the 31-day history cleanup and preserves the workspace-file warning. Settings explain the fixed recovery window. Browser inspection passed in light/dark themes at desktop and phone widths with short, typical, and 200-character names. Native mobile was not run.

Rebased onto current dev; only two documentation status paragraphs required conflict resolution, preserving both descriptions. Full repository checks/builds and generated-code verification are left to required CI. No production data or files were modified, and offline reclamation was not run.

CI follow-up: resolved lint spacing and size limits by extracting command replay policy and Welcome construction. Scoped lint/format and gateway/worker typechecks pass; WorkerLink and worker cleanup regression tests pass (22 tests, 67 assertions; clean check:tmp).

Retention test synchronization: wait for the initial turn to be durably completed before using its history; initial idle can precede worker admission. Deleted-retention suite passes (five tests, 23 assertions; clean check:tmp). On the preceding revision all CI checks except that test shard and its aggregate gate passed.

Compact duplicate event text without losing provider metadata, bound sync replay and update caches, and clean expired thread history and unreferenced storage with durable worker cleanup.

Fixes: #27
@nixuuu
nixuuu enabled auto-merge (squash) November 16, 2026 08:36
@nixuuu
nixuuu merged commit 468fa37 into dev Nov 16, 2026
16 checks passed
@nixuuu
nixuuu deleted the perf/optimize-database-storage branch November 16, 2026 08:59
nixuuu added a commit that referenced this pull request Nov 17, 2026
## Change

A disconnected thread could repeatedly fail to resume with
`Unknown/watch_failed` while **Load from scratch** restored it. A
snapshot from another reader can leave several pending revisions of the
same large item in the replay range. Saving those revisions in a single
upsert violated PostgreSQL's one-update-per-row rule and rolled back
every resume attempt.

Keep the latest revision per entity when saving current content
pointers, including inline replacements and removals, and prevent older
revisions from overwriting newer pointers. Replay still delivers every
sequence record. After two transient retries, repeated untyped gateway
failures now try a fresh window, then a smaller window, before stopping
with recovery actions. Visible messages remain available during
recovery; ordinary transport drops retain automatic retries.

The regression reproduces the original failure over WorkerLink and gRPC,
then verifies replay catches up without replacing the snapshot. A
separate gRPC-to-SSE regression verifies automatic recovery with a fresh
window. Updated the transcript and UI API documentation.

## Verification

- `check:tmp`: 27 passing tests across thread sequence content replay,
replication retention, watch failures, and watch liveness; no temporary
files left behind.
- Domain and integration package typechecks passed.
- Edited-file lint and formatting passed; `git diff --check` passed.
- Full repository checks and builds remain with CI.
- Copy audit: not applicable; no user-facing text changed.

Fixes: #864
Fixes: #871
nixuuu added a commit that referenced this pull request Nov 20, 2026
## Changes

- Expire old, unpublished events in the contiguous replication prefix
while honoring active leases and the 10,000-record replay window.
Expired clients can recover from source history.
- Deduplicate exact transcript payloads, including tool JSON and diffs.
Preserve full-content replay and reuse the existing content reference
when a large preview needs further trimming.
- Sweep the worker's preview cache hourly and at startup. Keep files
referenced by pending journal events or in-flight writes.
- Cap Electron's HTTP disk cache at 64 MiB. Fix a packaged Desktop
regression where an origin captured by the bundled adapter caused valid
forms to return HTTP 403 in Local or Remote mode. Foreign origins still
receive HTTP 403.
- Recover Codex turns from native archived and Zstandard-compressed
rollouts. Automatic compression remains deferred while import and CLI
rollback support are incomplete.

The PostgreSQL 17 fixture with 600 items used 21.74 MiB across the three
measured relations, down from 26.08 MiB (16.6%). An isolated Electron
run retained 60 MiB after receiving 152 MiB of cacheable data. Both
measurements are from test fixtures.

## Verification

- Ran 460 non-live integration and focused test files on isolated
databases. The first run had 2,880 passes, 12 skips and 13 failures. All
13 failing cases passed on focused reruns after fixture isolation and
link-readiness fixes or when rerun without the parallel load.
- Reran 34 tests for first and subsequent prompts, file and image
delivery to Codex, Claude and Grok stand-ins, linked attachment reads,
and client continuity.
- In a real browser against the test stack, created a thread with a
prompt, TXT and PNG, verified the worker received both files, and
reopened the conversation. Also verified a follow-up with an attachment
and opened the text and image previews.
- Built the Linux x64 Desktop bundle. All five packaged-runtime tests
and the Electron shell smoke passed.
- Targeted typechecks, lint and formatting passed. GitHub CI will run
the repository-wide gates for this revision.

The mobile Connect transport and history tests ran in the integration
suite. The changed form-origin handling and HTTP disk cache are
Electron-specific. Native iOS and Android UI and live provider calls
were outside this local run. No user-facing copy changed.

Refs: #864
Refs: #1051
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant