Repository navigation
perf(persistence): build the state file once per save instead of seven times - #18161
Conversation
…n times Every debounced save stringified the full persisted state, then ran two `String.replace` passes per secret sentinel — one for the on-disk payload, one for the guard hash. Each replace returns a rope the next one has to flatten before it can search, so three sentinels cost seven flattened copies of a 4.65 MB state (a two-byte V8 string, ~8.9 MB each), and the state was then UTF-8 encoded twice more: once inside `sha1.update(string)` and again inside `handle.writeFile(payload, 'utf-8')`. `applySecretSentinelSubstitutions` walks the state once with a single alternation regex, encodes each literal run to a Buffer exactly once, and feeds those same buffers to both the payload and the hash. Measured on the author's 4.65 MB store with three live secret slots: 48.8 MB -> 17.9 MB allocated per save, 26.6 MB -> 0 of large_object_space churn, and 22.1 -> 15.1 ms (min) / 32.3 -> 16.9 ms (median) for build+hash+encode. Bytes on disk and the guard hash are proven identical to the previous loop. Separately, non-local host session partitions carried stale replicas of the `browserUrlHistory` global — 589,807 bytes, 12.7% of the file — that neither the split (which writes globals only to 'local') nor the merge (which reads them only from 'local' unless local has none) can ever reach. The load path now drops them when the local slice already holds the field. Only the two history globals are dropped: the rest are read out of every partition by the worktree ownership sweep or the mobile/runtime projections.
|
Warning Review limit reachedNext included review available in 10 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (14)
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.
Important
Fix 2 is predicated on "the split never writes these globals to host partitions" — but the renderer split does write them there on every full-snapshot write, so the load-time prune is re-inflated at shutdown and the 12.7% disk reduction does not survive a graceful quit.
Reviewed changes
- One-pass sentinel substitution —
applySecretSentinelSubstitutionswalks the serialized state once, UTF-8-encodes each literal run exactly once, and reuses those buffers for both the on-disk payload and the sha1 guard hash;buildStateToSave()now returns aBuffer. - Buffer write path —
writeToDiskAsync(handle.writeFile) andwriteFileDurableSyncaccept the pre-encoded bytes instead of re-encoding the whole state on the main thread. - Load-time prune of redundant host-partition globals —
parseWorkspaceSessionsByHostIddropsbrowserUrlHistory/workspaceDocHistoryfrom non-local partitions when the local slice owns the field, gated by a two-condition ratchet test. - Module move —
workspace-session-host-field-ownership.tsrelocated tosrc/shared/so the main-process ratchet can import it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| * Global fields belong to the 'local' slice: the split writes them only there and the merge reads | ||
| * them only from there. A copy inside a non-local partition is legacy residue no read can reach — | ||
| * stale `browserUrlHistory` replicas alone were 589 KB, 12.7% of a 4.65 MB store, rewritten on | ||
| * every save and reparsed on every launch. |
There was a problem hiding this comment.
This premise is incorrect, which undermines the durability of the whole fix. splitWorkspaceSessionByHost (src/renderer/src/lib/workspace-session-host-split.ts) clones every global field onto each non-local host slice via ensureSlice's { ...template } — so browserUrlHistory and workspaceDocHistory are written to host partitions on every full-state split. The shutdown checkpoint (buildWorkspaceSessionHostSnapshots in use-app-session-persistence.ts) and lifecycle persistWorkspaceSessionByHost both use that full split, so the residue dropped here is re-inflated on the next full write.
| export const HOST_PARTITION_REDUNDANT_GLOBAL_FIELDS = [ | ||
| 'browserUrlHistory', | ||
| 'workspaceDocHistory' | ||
| ] as const satisfies readonly (keyof WorkspaceSessionState)[] |
There was a problem hiding this comment.
The two-gate ratchet test guards which fields may be dropped, but nothing guards against the split re-writing them. Since the split's ensureSlice clone is the mechanism that creates these copies in the first place, dropping them only at load is a band-aid: the same 589 KB is re-written into the file by the quit checkpoint on every graceful shutdown. The durable fix is to stop cloning these two pure-history globals (they are not the "active pointers" the clone comment justifies) into non-local slices — either exclude them from the template in ensureSlice, or delete them from non-local slices before nonLocalHostSessionEntries returns them.
#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 #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.
1149 commits of upstream drift, 11 conflicts. Resolved by taking upstream wholesale wherever it had restructured a file and re-applying this branch's delta into the new shape, rather than hand-merging hunks: - keybindings.ts was split into keybindings/. The action id moves to keybindings/types.ts and the definition to definitions-core-4.ts (the overflow file; core-3 was already at its line budget). - Terminal.tsx's editor shortcut handling moved to terminal-workspace-editor-shortcuts.ts, so the direction handler moves with it. - The settings defaults moved from constants.ts to default-global-settings.ts. - workspace-session-host-field-ownership.ts moved to src/shared (stablyai#18161). - remove-worktree-store-cleanup.ts replaced the manual clone-and-delete loop with omitByFileId, so the field is registered there instead. - editor-panel-render-model.ts was rewritten and kept the original inlineMarkdownContent name this branch had renamed; canShowTextDirectionToggle is re-derived from it. Kept both sides where upstream and this branch each added an adjacent item: the Show Whitespace menu entry and setting, and their en.json keys. Three new upstream exhaustiveness gates now classify the field: WORKSPACE_SESSION_FIELD_DISPOSITION, session-worktree-ownership, and workspace-session-schema-field-coverage. buildEditorSessionData is extracted again to keep workspace-session.ts under max-lines. Verified on the merged tree: pnpm tc, pnpm lint (exit 0, all localization gates), 214 direction-related unit tests, and the RTL e2e all pass.
…n times (stablyai#18161) Every debounced save stringified the full persisted state, then ran two `String.replace` passes per secret sentinel — one for the on-disk payload, one for the guard hash. Each replace returns a rope the next one has to flatten before it can search, so three sentinels cost seven flattened copies of a 4.65 MB state (a two-byte V8 string, ~8.9 MB each), and the state was then UTF-8 encoded twice more: once inside `sha1.update(string)` and again inside `handle.writeFile(payload, 'utf-8')`. `applySecretSentinelSubstitutions` walks the state once with a single alternation regex, encodes each literal run to a Buffer exactly once, and feeds those same buffers to both the payload and the hash. Measured on the author's 4.65 MB store with three live secret slots: 48.8 MB -> 17.9 MB allocated per save, 26.6 MB -> 0 of large_object_space churn, and 22.1 -> 15.1 ms (min) / 32.3 -> 16.9 ms (median) for build+hash+encode. Bytes on disk and the guard hash are proven identical to the previous loop. Separately, non-local host session partitions carried stale replicas of the `browserUrlHistory` global — 589,807 bytes, 12.7% of the file — that neither the split (which writes globals only to 'local') nor the merge (which reads them only from 'local' unless local has none) can ever reach. The load path now drops them when the local slice already holds the field. Only the two history globals are dropped: the rest are read out of every partition by the worktree ownership sweep or the mobile/runtime projections.
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.

ELI5
Every few seconds Orca writes out a ~4.6 MB description of your session — every tab, every worktree, every setting. To do that it was making seven separate full-size copies of that text in memory, using one and throwing six away, and then re-typing the whole thing into bytes twice more. This PR builds it once.
Separately, about an eighth of that file was a copy of your browser address-bar history, duplicated into every remote-host section — copies that nothing ever reads back. Those are dropped at load.
Nothing about the app behaves differently. The bytes written to disk are byte-for-byte the same, and a test proves it against the old code.
Fix 1 — one pass instead of seven copies and three encodes
state-serialization-secret-handling.tsdid:Correction to the brief's mechanism (the count is right, the reason isn't).
String.replacedoes not immediately copy — V8 returns aConsStringrope, which is why a single replace on a 4.65 MB string measures at 0.1 ms. The cost is deferred: the nextreplacemust flatten the rope before it can search, andhash.update/Buffer.fromflatten the final one. Step-decomposed on the real store:JSON.stringifyString.replacesha1.update(hashInput)(flattens)Buffer.from(payload)for the write (flattens)So it is exactly 7 full-state allocations as claimed — 1 stringify + 4 intermediate flattens + 2 final flattens — just via rope flattening rather than eager copying. It's also more than the brief's 31 MB: the store's JSON is a two-byte V8 string (~8.87 MB per copy, not 4.43 MB), so 7 copies is ~62 MB of allocation.
The replacement (
secret-sentinel-substitution.ts) walksserializedonce with one alternationRegExp,Buffer.froms each literal run exactly once, and hands those same buffers to both the payload concat andhash.update. That is better than the brief asked for: the hash is overhashInput(normalized values), not overpayload(ciphertext), so "hash the payload Buffer" isn't available — but reusing the shared literal segments gets the same win, and hashing Buffers instead of strings is the measured 3× (5.2 ms → 1.6 ms)."Each sentinel appears exactly once" — verified. Each is
orca-secret-slot-${randomUUID()}, minted insideencryptToSentinelafter the user's state is assembled, and assigned to exactly one property. Nothing aliases it. The alternation is/ganyway, so a hypothetical repeat is substituted everywhere rather than leaving a raw sentinel on disk where a secret should be (the old first-match-only stringreplacewould have). Escaping is preserved verbatim: the search key is stillJSON.stringify(sentinel).slice(1, -1), now additionally passed through the existingescapeRegexfromshared/string-utils.tsbefore it becomes a pattern.Two smaller call-site changes:
handle.writeFile(payload)andwriteFileDurableSync(..., payload: string | Uint8Array)take the Buffer directly instead of re-encoding a string on the main thread.Measurements — Fix 1
Real 4.65 MB store, 3 live secret slots, Node 22, macOS arm64. Repeated
gc()-separated runs; stable across 3 invocations.(The step table above sums to 62.1 MB of allocation; the 44.37 MB figure is the steady-state
heapUseddelta across a whole cycle, where a scavenge reclaims ~2 of the intermediate copies mid-call. Both are measured; the second is what the process actually experiences.)Fix 2 — dead
browserUrlHistoryreplicas, narrowed from the briefConfirmed on the live store: 589,807 bytes of global-field residue removable, 12.7% of the file, matching the brief's 589,522.
Two corrections to the brief:
browserUrlHistorycopy, not 10 — thessh:partition has none. Of the 9: 3 byte-identical to the root copy, 6 drifted (brief said 3 / 7).profile-project-session-state.ts:89-91is wrong. Lines 89-91 areterminalPtyIncarnationsByPaneKey. The residue is preserved by the bare...basespread at line 46 ofmergeWorkspaceSessions.The important correction: dropping every
GLOBAL_WORKSPACE_SESSION_FIELDSentry is NOT a zero-behavior-change edit, and I did not do it. Two independent main-side gates disqualify five of the eight:activeWorktreeIdandactiveWorkspaceKeyare classified'direct'inWORKSPACE_SESSION_WORKTREE_REFERENCE_KIND, and bothcollectPersistedSessionWorktreeOwners(session-worktree-ownership.ts:227-237) and the deregistered-repo residue sweep (deregistered-repo-residue.ts:86-95, which readssession.activeWorktreeId/session.activeWorkspaceKeyexplicitly) walk every partition. Dropping either un-owns a worktree, and an un-owned worktree gets its metadata pruned — that is data loss, exactly the class of bug this PR must not introduce.activeTabId,activeConnectionIdsAtShutdownandactiveRepoIdhave live main-side readers on a partition:isPersistedTerminalLeafActivefalls back tosession.activeTabIdfor the mobile terminal projection, andorca-runtime-attach-window.ts:64-95unionssession.activeConnectionIdsAtShutdownfromstore.getWorkspaceSession(hostId)for SSH auto-reconnect.So the prune is scoped to the two pure-history globals —
browserUrlHistoryandworkspaceDocHistory— which are'global'in the ownership table and'none'in the reference-kind table. That is 589,807 of the 593,758 total residue bytes: 99.3% of the win, none of the risk. A ratchet test re-checks both gates for every field in the list, so the list cannot grow into an unsafe field silently.The drop runs before the defaults spread, so a field the type requires comes back at its default rather than going missing, and it only fires when the local slice already holds the field — exactly the condition under which
mergeWorkspaceSessionsFromHosts' fallback-to-another-slice branch cannot fire (pinned by two new tests inworkspace-session-host-split.test.ts).workspace-session-host-field-ownership.tsmovessrc/renderer/src/lib/→src/shared/so the main-process ratchet can import it (tsconfig.node.jsoncorrectly refuses a main → renderer import). Pure data module, no behavior change; 2 import lines updated.Measurements — Fix 2
JSON.stringifyof the state, minI could not reproduce the brief's 157 ms parse. On this machine (Node 22, macOS arm64, outside Electron) the same file decodes+parses in 7.7 ms warm and 12.9–21.7 ms in a cold process. I'm reporting what I measured rather than the briefed figure. The relative shrink is real either way, and the
JSON.stringifywin (12.9 → 5.0 ms) is the larger and more reproducible one, since it lands on every save rather than once at launch.Optional no-op-save skip: NOT done, deliberately
The brief allowed caching serialization on
writeGeneration. I could not prove every mutation path bumps it, so per the brief's own instruction I did not add it. Concretely: there are 48 directstate.<field> = ...assignments acrosssrc/main/persistenceandsrc/main/runtimeagainst 86scheduleSavecall sites, plus in-place nested mutation (state.worktreeMeta[key] = ...,delete state.worktreeMeta[key], and thesrc/main/orca-profiles/helpers that mutate a state object reached by reference). A generation-keyed cache cannot observe an in-place nested mutation that skippedscheduleSave, and a stale cache there is silent data loss, not a perf regression. The currentlastWrittenStateHashguard still skips the disk write; it just pays the (now 48% cheaper) serialization to compute the hash.Out of scope, as instructed
linked*: nullvs absent is the risk).worktreeMetaByIdentitydedup: −953 KB available, schema change, separate design pass. (Measured here:worktreeMeta835,444 B +worktreeMetaByIdentity773,324 B.)gcStaleWorktreeMeta,session-write-subscriber.ts, startup migration passes: untouched.Tests
New, all failing without the corresponding fix:
secret-sentinel-substitution.test.ts— six cases, each comparing againstpreviousImplementation, a verbatim copy of the loop this PR deletes:A+/=$&$1$+ backtick +\x "quoted" |.*?[](){}^(regex-special and JSON-escapable), plus adjacent near-miss decoys;é,中文,😀) placed on both sides of every segment boundary;safeStorage-degraded\0prefix;String.prototype.replace,Buffer.fromandHash.prototype.updateand asserts the old path does3 × 2 = 6full-state replaces and ≈2× full-state encoded chars, while the new path does 0 replaces and ≈1× encoded chars.workspace-session-partitions.test.ts— dropped only when local has the field; retained when local does not (workspaceDocHistory, which is absent from the defaults so the case is reachable); untouched when no local slice is supplied;activeWorktreeId/activeTabId/ host-owned fields explicitly left alone; plus the two-gate ratchet on the drop list.state-write-round-trip.test.ts— drives the realStore: three encrypted secret slots, a local session and a remote partition with non-ASCII history,flush(), reads the file back, asserts it holds ciphertext and no leakedorca-secret-slot-sentinel, reloads, then asserts deep equality of settings / UI / both session partitions across a second round trip and that a third flush produces byte-identical file contents.Fail-first verified by reverting the three Fix-2 files (unique patch path, not the shared
/tmp/mywip.patch): 3 of 6 partition tests fail. The allocation-count test fails if the substitution is reverted to the loop (it would report 6 replaces, not 0).Verification
pnpm tc— clean (run once, at the end)npx oxlint <changed files>— clean;oxfmtappliednpx vitest run --config config/vitest.config.ts src/main/persistence src/renderer/src/lib— 569 files, 5613 tests passed, 1 skippedNegative user-facing trade-offs
None.
secret-sentinel-substitution.test.tscomparespayload.equals(...)and the sha1 against the deleted implementation across regex-special, JSON-escapable and multi-byte fixtures. The guard hash is unchanged, so the no-op-write skip keeps behaving exactly as it did. The only intentional divergence is a case that cannot occur today: a repeated sentinel is now fully substituted instead of leaving a raw UUID on disk where a secret belongs — strictly safer.browserUrlHistoryreturns from the defaults spread as[], so no consumer sees an unexpectedundefined.