Skip to content

perf(persistence): stop rewriting redundant bytes in the profile store - #18317

Merged
nwparker merged 1 commit into
mainfrom
perf/persisted-state-redundancy
Sep 3, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/persisted-state-redundancy

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​294 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​288
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​225 $\color{#cf222e}{\Huge{\mathbf{−}}}$​74 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​151

ELI5

Orca writes its whole orca-data.json from scratch every time anything changes (1 s debounce, 5 s max wait) and reads the whole thing back at launch. On a heavy install that file is 4.2 MB. A big slice of those bytes said nothing: metadata rows spelled out "linkedGitLabMR":null twelve times over for ~1,200 workspaces, and three of ten per-host session partitions carried a byte-identical photocopy of the browser history that only the local partition is ever read for.

This deletes those bytes on write and reconstructs them on read, so nothing in memory changes — the app just stops paying to write and re-read the same nulls a hundred times a session.

What was happening

A — the renderer split was re-injecting global session fields into every non-local partition. This is a write-side regression that undid #18161's load-side fix.

splitWorkspaceSessionByHost built one template holding all GLOBAL_WORKSPACE_SESSION_FIELDS and handed that same template to ensureSlice for every host, not just local. setHostWorkspaceSession stored it verbatim.

mergeWorkspaceSessionsFromHosts reads globals from local first and only falls back to another slice when local lacks them — which cannot happen, because the template always fills local. So every non-local copy was bytes no read could reach.

#18161 added a load-time drop in parseWorkspaceSessionsByHostId that removed the replicas on the way in. But the very next full snapshot write put them straight back, because the split still seeded them. On the reporting install that was 3 of 10 partitions each holding a byte-identical 66,178 B replica of local's browserUrlHistory (verified ===), 198,534 B / 4.7% of the file, re-serialized on every save, re-parsed on every launch, and structured-cloned over IPC once per host on every persistWorkspaceSessionByHost and quit snapshot. It grows linearly with the number of runtime hosts ever used.

Fixed in three places so the drop cannot be undone again: the split gives non-local slices a template without HOST_PARTITION_REDUNDANT_GLOBAL_FIELDS, setHostWorkspaceSession strips them from any payload that still carries them, and the serializer sweeps the partition map as a backstop (the load path re-seeds each partition's [] default, which was itself being written back per host).

C — ~11,450 "field":null pairs across the two metadata maps.

mergeWorktreeMetaForWrite materializes all ten linked* slots plus isPinned/isArchived on every row at creation, even when null. Measured on the real file: 266,977 B in worktreeMeta + 266,810 B in worktreeMetaByIdentity = 533,787 B, 12.6% of the whole file, per save and per launch parse.

The serializer now omits any slot still equal to its default; normalizeWorktreeLinkedItemMetadata — which already walks every row of both maps at load — re-fills them. The default table (WORKTREE_META_PERSISTED_DEFAULTS) is now the single source createDefaultWorktreeMeta spreads, so the omit set and the fill set cannot drift. Only genuinely constant defaults are in it: instanceId and sortOrder are minted per row and stay written.

B — normalizedUrl duplicating url in browserUrlHistory — dropped, deliberately.

19,641 B of browserUrlHistory's 66,569 B are normalizedUrl values byte-identical to url, and the load path already recomputes normalizedUrl from url unconditionally (browserHistoryEntriesSchema → normalizeBrowserHistoryEntries), so omitting it would be lossless for this build. It fails the downgrade half of the hard constraint: the entry schema is salvagingArray(browserHistoryEntrySchema) with normalizedUrl: z.string() required, so an older build silently drops every history entry that omits the field and then rewrites the file without them — real, unrecoverable user data loss, and there is no coercion layer to save it the way mergeWorktree saves C. 0.46% of the file is not worth that. Not shipped.

Measurement

Realistic fixture built to the reported install's shape: 10 hosts (local + 9 runtime, 3 carrying the history replica), 1,200 worktreeMeta rows, 1,191 worktreeMetaByIdentity rows, 200 browser history entries. Driven through the real Store; "before" is the same loaded state re-expanded to the old on-disk shape, so the delta is the redundancy alone and not fixture noise.

Serialized bytes per save

before after delta
total 1,445,276 643,238 −802,038 (−55.5%)
worktreeMeta 607,256 285,446 −321,810 (−53.0%)
worktreeMetaByIdentity 606,259 286,870 −319,389 (−52.7%)
workspaceSessionsByHostId 164,433 3,594 −160,839 (−97.8%)

Bytes structured-cloned per persistWorkspaceSessionByHost, 9 non-local hosts: 164,250 → 3,411 (−97.9%).

Launch JSON.parse, median of 25: 2.00 ms → 1.37 ms (−31%), plus the same proportion off the readFileSync and off every writeFile + fsync on the save path.

Projected onto the reporting user's 4,243,739-byte file using its own per-field measurements: 533,787 B (C) + ~198,948 B (A) ≈ 733 KB, 17.3% removed from every save and every launch parse. The fixture removes 268 B/row from metadata versus the 224 B/row measured on the real file, so the projection uses the real number and is conservative.

Negative user-facing trade-offs

None found. The specific claims:

Round trip. load(save(state)) deep-equals the pre-save state for every field touched, asserted directly in persisted-state-redundancy.test.ts over the full fixture: getAllWorktreeMeta(), the local session, and all nine host sessions. The load-side fill lands in the same change as the omission, so null never becomes undefined for a consumer doing === null. A second flush is byte-identical, so a quiet app does not churn the file.

Forward compatibility. A file written by the OLD serializer and a file written by the NEW one load to identical in-memory state — its own test. Absence and the default carry the same meaning, and no non-default value is ever omitted.

Downgrade. A file this build writes, read by an older build with no fill:

  • A: the older build's parseWorkspaceSessionsByHostId already drops these fields at load (perf(persistence): build the state file once per save instead of seven times #18161) and re-seeds each partition's default from its own defaults spread. It never reads them off a non-local partition — that is the gate workspace-session-partitions.test.ts enforces per field. Nothing to lose.
  • C: every projection from WorktreeMeta into the Worktree the app actually reads already coerces each omitted slot, in code that is on main today and unchanged here — mergeWorktree (meta?.linkedIssue ?? null, isArchived ?? false, isPinned ?? false), getLinkedWorkItemMetadata (?? null for all seven optional linked fields), folder-workspace-model, runtime-folder-workspace, runtime-worktree-ps-summaries. Every raw-meta reader in main goes through ?.field ?? null, a truthiness check, or a isLinkedIssueNumber-style type guard. An older build therefore builds the same Worktree objects. Then it rewrites the file with the fields still absent (JSON.stringify drops undefined), and re-upgrading re-fills them — no data lost either direction.
  • B fails this test, which is exactly why it is not in this PR.

Not touched, deliberately:

  • SAVE_DEBOUNCE_MS / SAVE_MAX_WAIT_MS are unchanged — raising them trades crash-window state loss for bytes.
  • Backup rotation is already hourly-gated at 4 renames + 1 copyFile; left alone.

Risk & verification

pnpm tc clean. pnpm run check:code-quality:changed clean (0 new findings across 12 files).

Every test in the touched areas runs green, plus the whole of src/main/persistence, src/renderer/src/lib, and the session schema suites: 582 files / 5,726 tests passing. (persistence-async-write-syscalls.test.ts timed out once at 30 s under full-suite parallelism and passes in 27.6 s standalone — pre-existing headroom, unrelated.)

New tests, each verified to fail without its fix:

  • workspace-session-host-split.test.ts → never replicates a local-owned global onto a non-local slice: no non-local slice carries any HOST_PARTITION_REDUNDANT_GLOBAL_FIELDS after a split, and the merge still returns local's value. Fails on main.
  • persisted-state-redundancy.test.ts → round-trips a legacy-shaped file to identical in-memory state and a smaller file: full-size fixture; asserts the refill ran, that only rows holding a real value keep a slot, that no partition on disk carries a redundant global, an apples-to-apples size drop, deep equality across load(save(…)), and byte-stability of the next flush. Fails without either the serializer omission or the load-side fill.
  • persisted-state-redundancy.test.ts → loads an old-serializer file and a new-serializer file to the same state. Fails without the load-side fill.

Existing workspace-session-partitions.test.ts still re-checks both safety gates for every field in HOST_PARTITION_REDUNDANT_GLOBAL_FIELDS (must be 'global', must be 'none' in WORKSPACE_SESSION_WORKTREE_REFERENCE_KIND); the constant just moved to src/shared/ so the renderer split can share it.

Separately-scoped follow-up, not done here: 1,191 of the 1,193 worktreeMeta rows are byte-identical duplicates of worktreeMetaByIdentity rows, another ~20% of the file. Dropping the legacy map is a persisted-schema change with a downgrade hazard that this PR's constraints do not permit: an older build reads only worktreeMeta and would show zero workspace metadata. It needs its own migration and a deprecation window.

Two kinds of byte in orca-data.json were provably redundant. Both are paid on
every debounced save (full re-serialize) and every launch (full re-parse).

1. The renderer's host split handed one global-field template to EVERY host, so
   local's browserUrlHistory/workspaceDocHistory were copied verbatim into each
   non-local partition. That is a write-side regression undoing #18161's
   load-time drop: the load path removed the replicas, the next full snapshot
   write put them back. Non-local slices now get a template without the fields
   the merge only ever reads off 'local', and both the host write and the
   serializer strip the residue.

2. mergeWorktreeMetaForWrite materializes all ten linked* slots plus
   isArchived/isPinned on every metadata row, so a 1,200-workspace store carried
   ~534 KB of "field":null pairs across worktreeMeta and worktreeMetaByIdentity.
   The serializer omits slots still at their default and
   normalizeWorktreeLinkedItemMetadata re-fills them at load, so in-memory state
   is unchanged.

Measured on a fixture sized like the reporting install (10 hosts, 1,200 metadata
rows, 200 history entries): 1,445,276 -> 643,238 bytes per save (-55.5%),
164,250 -> 3,411 bytes structured-cloned per persistWorkspaceSessionByHost
across 9 non-local hosts, launch JSON.parse 2.00 ms -> 1.37 ms.
@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3bb6ab40-89fd-4948-a727-35bd312f7f6a

📥 Commits

Reviewing files that changed from the base of the PR and between 40d9927 and c3a4f0f.

📒 Files selected for processing (12)
  • src/main/persistence/loading-store/persisted-state-redundancy.test.ts
  • src/main/persistence/loading-store/session-host-partitions.ts
  • src/main/persistence/loading-store/state-serialization-secret-handling.ts
  • src/main/persistence/loading-store/workspace-session-partitions.test.ts
  • src/main/persistence/loading-store/workspace-session-partitions.ts
  • src/main/persistence/loading-store/worktree-meta-write-normalization.ts
  • src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts
  • src/main/persistence/tracking-repos/worktree-metadata-normalization.ts
  • src/renderer/src/lib/workspace-session-host-split.test.ts
  • src/renderer/src/lib/workspace-session-host-split.ts
  • src/shared/workspace-session-host-field-ownership.ts
  • src/shared/worktree/meta-persisted-defaults.ts

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


📝 Walkthrough

Walkthrough

The change reduces persisted state redundancy. Worktree metadata fields with fixed defaults are omitted during serialization and restored during loading. Host partitions no longer store local-owned global session fields when the local slice already contains them. Renderer partition templates and main-process persistence use the shared filtering helpers. Tests cover compact output, round-tripping, size reduction, write stability, and host-slice merging.

Merge Risk: ⚪ Minimal · up to c3a4f

The persistence compaction preserves the required local and partitioned session data paths, with no unresolved merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed scope, rationale, measurements, compatibility analysis, and test results, but it omits required template content, including a Linked Issue, explicit Visual Proof with… Add the required Linked Issue reference, add Visual Proof with N/A and a brief reason if no visual change exists, and complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary persistence optimization: removing redundant bytes from the profile store.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides detailed scope, rationale, measurements, compatibility analysis, and test results, but it omits required template content, including a Linked Issue, explicit Visual Proof with N/A and a reason, and the required checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Worktree metadata default omission (part C) — the serializer drops any WorktreeMeta slot equal to its fixed default (linked*: null, isArchived/isPinned: false) and normalizeWorktreeLinkedItemMetadata re-fills them at load, with WORKTREE_META_PERSISTED_DEFAULTS as the single source both sides spread.
  • Session-partition redundant globals (part A) — non-local host partitions stop carrying local-owned browserUrlHistory/workspaceDocHistory, enforced at three layers (renderer split template, setHostWorkspaceSession, serializer backstop) via helpers moved into src/shared/.
  • Tests — new persisted-state-redundancy.test.ts and split/partition test cases pin the round-trip equality, the safety gates, and the byte-stability of a quiet flush.

The omission/fill symmetry holds (omit only when value equals default, fill only when undefined), forward safety is guaranteed because the fill runs over both metadata maps before any consumer reads them, and the downgrade path stays lossless since mergeWorktree/getLinkedWorkItemMetadata coerce every omitted slot with ?? null/?? false. The partition strip only fires when local already holds the field, so the merge's fallback remains live — including the workspaceDocHistory-optional case. The deliberate normalizedUrl exclusion and the separate duplicate-map follow-up are both correctly reasoned.

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

@nwparker
nwparker merged commit df42028 into main Sep 3, 2026
29 checks passed
@nwparker
nwparker deleted the perf/persisted-state-redundancy branch September 3, 2026 06:19
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#18317)

Two kinds of byte in orca-data.json were provably redundant. Both are paid on
every debounced save (full re-serialize) and every launch (full re-parse).

1. The renderer's host split handed one global-field template to EVERY host, so
   local's browserUrlHistory/workspaceDocHistory were copied verbatim into each
   non-local partition. That is a write-side regression undoing stablyai#18161's
   load-time drop: the load path removed the replicas, the next full snapshot
   write put them back. Non-local slices now get a template without the fields
   the merge only ever reads off 'local', and both the host write and the
   serializer strip the residue.

2. mergeWorktreeMetaForWrite materializes all ten linked* slots plus
   isArchived/isPinned on every metadata row, so a 1,200-workspace store carried
   ~534 KB of "field":null pairs across worktreeMeta and worktreeMetaByIdentity.
   The serializer omits slots still at their default and
   normalizeWorktreeLinkedItemMetadata re-fills them at load, so in-memory state
   is unchanged.

Measured on a fixture sized like the reporting install (10 hosts, 1,200 metadata
rows, 200 history entries): 1,445,276 -> 643,238 bytes per save (-55.5%),
164,250 -> 3,411 bytes structured-cloned per persistWorkspaceSessionByHost
across 9 non-local hosts, launch JSON.parse 2.00 ms -> 1.37 ms.
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