Repository navigation
perf(mobile): avoid unchanged worktree catalog payloads - #11735
Conversation
Sol review loop #1 — CHANGES REQUESTED → FIXED
Loop #2 will re-review the updated head. |
Sol review loop #2 — CLEANTwo independent Sol reviewers re-reviewed updated head Verified risks:
Reviewer validation included 31 host cache/RPC tests, 9 mobile client tests, extra default-limit/recency/eviction/concurrency repros, node/mobile typechecks, changed-file lint, and Final loop verdict: CLEAN. |
Greptile SummaryThis PR adds a content-addressed ETag mechanism to
Confidence Score: 5/5Safe to merge. The change is purely additive on the wire — old callers receive byte-identical responses and new callers fall back to full payloads whenever anything is ambiguous. The content-addressed design is sound: IDs are derived from serialized catalog content, so concurrent clients, differing limit values, and server restarts all converge correctly without coordination. The client token advances only after the existing stale-client/host and modal guards, preventing dropped or superseded responses from corrupting state. Every key invariant is covered by dedicated tests and no correctness issues were found in the code paths introduced by this PR. Files Needing Attention: No files require special attention. The two core files —
|
| Filename | Overview |
|---|---|
| src/main/runtime/rpc/worktree-catalog-snapshot.ts | Core server-side snapshot logic: computes a 32-char base64url SHA-256 over the serialized catalog, with a single-slot deep-equality memo in front. Content-addressed design is sound — IDs match only when catalogs are byte-identical, making concurrent clients and restarts safe without bookkeeping. Module-level memo is safe under Node.js's single-threaded event loop. |
| mobile/src/worktree/worktree-catalog-snapshot-client.ts | Client-side snapshot token management: discriminates full vs. unchanged vs. invalid responses by presence of worktrees array (not the unchanged field), advances the token only on admit(), and handles stale client/host responses without invalidating the current token. Invariant that snapshotId non-null implies confirmedWorktrees non-null is maintained correctly throughout all code paths. |
| mobile/app/h/[hostId]/index.tsx | HostScreen delegates worktree fetching to WorktreeCatalogSnapshotClient via a useRef (correctly, to avoid React discarding the token on memo eviction). Existing stale-client and modal guards still fire before admit(), so the token only advances for current, modal-safe responses. Unchanged polls still reassert confirmed rows through the same state-update path as full polls. |
| src/main/runtime/rpc/methods/worktree.ts | Adds the snapshot opt-in gate: callers without afterSnapshotId receive the byte-exact legacy response; callers with the field go through resolveWorktreeCatalogSnapshot. Clean backward-compat boundary. |
| src/main/runtime/rpc/methods/worktree-schemas.ts | Adds afterSnapshotId as z.string().min(1).max(128).nullable().optional() to WorktreePsParams. Schema bounds match the 32-char server-generated IDs and the client-side validSnapshotId guard. |
| src/shared/runtime-types.ts | Adds RuntimeWorktreePsSnapshotResult, RuntimeWorktreePsUnchangedResult, and their union RuntimeWorktreePsConditionalResult. Clean type-level modelling of the two new response shapes. |
| src/main/runtime/rpc/worktree-catalog-snapshot.test.ts | Comprehensive server-side tests covering: exact-match unchanged, changed-catalog new ID, concurrent-caller independence, superseded-snapshot repair, memo-state isolation, mutation isolation, and schema-bound ID length. |
| mobile/src/worktree/worktree-catalog-snapshot-client.test.ts | Client-side tests covering: confirmed-rows reassertion on unchanged, token-advance timing, transport-failure preservation, mismatched-unchanged clear, client/host-change reset, and superseded-response drop without token invalidation. |
| src/main/runtime/rpc/methods/worktree-catalog-snapshot-method.test.ts | Integration-level tests through RpcDispatcher: verifies legacy callers get no snapshotId, round-trip produces a compact unchanged response, and getWorktreePs runs twice (safety poll preserved). |
| mobile/app/index.tsx | Minor refactor: replaces inline magic literal 10000 with the exported WORKTREE_PS_FULL_LIMIT constant from the new client module for consistency. |
Sequence Diagram
sequenceDiagram
participant HS as HostScreen
participant SC as WorktreeCatalogSnapshotClient
participant Host as Host (worktree.ps)
Note over HS,Host: Initial poll (no snapshot yet)
HS->>SC: fetch(client, hostId)
SC->>Host: "worktree.ps { afterSnapshotId: null }"
Host-->>SC: "{ worktrees: [...], snapshotId: X }"
SC-->>HS: PendingWorktreeCatalog
HS->>SC: admit(pending)
SC-->>HS: confirmedWorktrees
HS->>HS: setWorktrees / setCachedWorktrees
Note over HS,Host: Subsequent poll - catalog unchanged
HS->>SC: fetch(client, hostId)
SC->>Host: "worktree.ps { afterSnapshotId: X }"
Host-->>SC: "{ unchanged: true, snapshotId: X } ~192 bytes"
SC-->>HS: PendingWorktreeCatalog
HS->>SC: admit(pending)
SC-->>HS: confirmedWorktrees (reasserted)
HS->>HS: areWorktreeListsEqual - reuse existing array
Note over HS,Host: Poll - catalog changed
HS->>SC: fetch(client, hostId)
SC->>Host: "worktree.ps { afterSnapshotId: X }"
Host-->>SC: "{ worktrees: [...], snapshotId: Y } full payload"
SC-->>HS: PendingWorktreeCatalog
HS->>SC: admit(pending)
SC-->>HS: new confirmedWorktrees
HS->>HS: setWorktrees / setCachedWorktrees
Note over HS,Host: Stale response
HS->>SC: admit(staleFromOldClient)
SC-->>HS: null (token unchanged)
Reviews (3): Last reviewed commit: "fix(runtime): isolate catalog snapshot m..." | Re-trigger Greptile
…hots Client — the `changed` gate meant an unchanged poll skipped setWorktrees / setLastKnownWorktrees / setCachedWorktrees, so optimistic local edits (togglePin, handleDeleteWorktree's failure re-add) and the #8498 cache guard were no longer repaired while the host catalog was stable. The gate bought nothing: setCachedWorktrees is an in-memory Map write and areWorktreeListsEqual already ran every poll, so the steady state still short-circuits on array identity. All wire savings are unaffected. admit() now just returns the confirmed rows and HostScreen applies them exactly as it did pre-PR. Also on the client: - a stale response from a superseded client/host no longer clears the token the current client/host just established - discriminate on `worktrees` rather than on `'unchanged' in response`, so a future catalog field named `unchanged` can't reclassify a full response - useRef over useMemo for the snapshot client; React may discard memoized values - hoist WORKTREE_PS_FULL_LIMIT so the truncates-at-200 rationale travels with it Host — replace the per-limit snapshot cache with a content-addressed id (ETag semantics). Ownership lives in the id, so concurrent clients, differing limits, and runtime restarts are correct by construction; this drops the LRU, the eviction policy, the per-runtime WeakMap, and the retention of up to 8 full catalogs. The remaining cache is a pure memo: because ids derive from content, dropping or thrashing it costs CPU and nothing else. Keeping the memo also keeps the measured steady-state cost — hashing every poll instead measured 2.24ms vs 0.75ms for the compare on a 310KB catalog. Verified: mobile 2784 passed / 3 skipped, src/main/runtime/rpc 1064 passed, node + mobile typechecks, oxlint, oxfmt, max-lines ratchet.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe runtime adds content-addressed worktree catalog snapshots and conditional 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
Review + live QA — CLEAN at
|
|
Supplemental Android validation on the exact pushed PR head:
|
* perf(mobile): avoid unchanged worktree catalog payloads * fix(mobile): isolate catalog snapshots by limit * review: reassert host truth on unchanged polls; content-address snapshots Client — the `changed` gate meant an unchanged poll skipped setWorktrees / setLastKnownWorktrees / setCachedWorktrees, so optimistic local edits (togglePin, handleDeleteWorktree's failure re-add) and the stablyai#8498 cache guard were no longer repaired while the host catalog was stable. The gate bought nothing: setCachedWorktrees is an in-memory Map write and areWorktreeListsEqual already ran every poll, so the steady state still short-circuits on array identity. All wire savings are unaffected. admit() now just returns the confirmed rows and HostScreen applies them exactly as it did pre-PR. Also on the client: - a stale response from a superseded client/host no longer clears the token the current client/host just established - discriminate on `worktrees` rather than on `'unchanged' in response`, so a future catalog field named `unchanged` can't reclassify a full response - useRef over useMemo for the snapshot client; React may discard memoized values - hoist WORKTREE_PS_FULL_LIMIT so the truncates-at-200 rationale travels with it Host — replace the per-limit snapshot cache with a content-addressed id (ETag semantics). Ownership lives in the id, so concurrent clients, differing limits, and runtime restarts are correct by construction; this drops the LRU, the eviction policy, the per-runtime WeakMap, and the retention of up to 8 full catalogs. The remaining cache is a pure memo: because ids derive from content, dropping or thrashing it costs CPU and nothing else. Keeping the memo also keeps the measured steady-state cost — hashing every poll instead measured 2.24ms vs 0.75ms for the compare on a 310KB catalog. Verified: mobile 2784 passed / 3 skipped, src/main/runtime/rpc 1064 passed, node + mobile typechecks, oxlint, oxfmt, max-lines ratchet. * fix(runtime): isolate catalog snapshot memo --------- Co-authored-by: Brennan Benson <[email protected]>



ELI5
Every three seconds, the mobile app asks the host, “What worktrees do you have right now?” Previously, the host mailed back the entire catalog even when nothing changed—477 KB on the measured host.
With this change, the host still rebuilds and checks the complete catalog for safety. It labels that catalog with a fingerprint of its contents. If the phone already holds that exact fingerprint, the host replies with a ~192-byte “same as X” receipt and the phone reuses the catalog it already confirmed. If the fingerprint is unknown, either side is old, or anything changed, the host sends the complete catalog again.
Because the label is derived from the contents rather than from bookkeeping, any number of phones, any request size, and any host restart all line up automatically—the labels can only match when the catalogs are identical.
Summary
worktree.psMeasured impact
Measured against a live 288-worktree host:
That avoids roughly 477,231 bytes per unchanged poll (99.96%). At the existing three-second cadence, this is about 9.11 MiB/minute or 546 MiB/hour per active client before transport overhead.
The savings are redundant serialization/transfer, relay encryption/decryption work, mobile JSON parsing/allocation, cache writes, and downstream list work. This deliberately still builds the complete host catalog and preserves the safety poll—catalog construction is unchanged.
Host CPU. The steady-state path is an exact deep comparison against the last catalog, measured at about 0.418 ms/poll on this catalog versus about 0.581 ms/poll for JSON serialization alone. Hashing is reached only when that comparison fails, i.e. only on polls that were going to send a full payload anyway. Hashing unconditionally instead was measured at roughly 3x the compare on a synthetic catalog of similar size, which is why the memo in front of it stays.
Design
snapshotIdis a truncated sha256 over the serialized catalog—HTTPETagsemantics. Snapshot ownership therefore lives entirely in the ID rather than in server-side bookkeeping:limitvalues need no isolation, because a limit that changes the response also changes its fingerprint, and one that does not is genuinely the same catalog.A single-slot memo sits in front of the hash so the common case stays a deep compare. The memo is a pure CPU optimization and is deliberately outside the correctness argument: because IDs derive from content, dropping or thrashing that slot can change performance and nothing else.
On the client, an unchanged response still yields the confirmed rows, and
HostScreenreapplies them exactly as it does for a full response. Every poll therefore continues to reassert host truth over optimistic local edits (pin toggles, delete rollbacks) and continues to overwrite the home-written worktree cache (#8498). This costs nothing in the steady state: the cache write is an in-memoryMap.set, andareWorktreeListsEqualalready ran on every poll and still short-circuits to the existing array on an identical catalog, keeping SectionList/sort rebuilds off the tap path.Proof of no regression
getWorktreePsran twice. No code insidegetWorktreePschanged.issues a new snapshot id for changed content;repairs a caller holding a superseded snapshot with a full response.keeps concurrent callers independent without server-held stateinterleaves two catalogs and asserts both callers still getunchanged.derives ids from content alone, so memo state cannot change the answerdisplaces the memo and asserts the ID is unchanged.returns unchanged only when the caller owns the exact current snapshotasserts the full current result carrying the current ID.produces ids within the request schema bound.afterSnapshotIdand asserts nosnapshotIdis added.treats an old-host full response as authoritative and clears the token.returns the confirmed rows on unchanged responses so callers can reassert them;HostScreenapplies them through the same path as a full response.admit, after the existing current-client/current-host/modal guards;does not advance the token until the caller admits a response.drops a superseded host response without invalidating the current token;resets snapshot ownership when the client or host changes.preserves the last admitted token across transport failures;clears snapshot ownership after a mismatched unchanged response; malformed-payload cases force a full repair.unchangedcatalog field cannot reclassify a full responseclassifies by rows, so a future 'unchanged' catalog field cannot hide a full response.worktree.psresult as opaque data and does not alter catalog construction, provider access, paths, Git commands, or polling.Validation performed locally:
src/main/runtime/rpctests passed (1 skipped)Safety and compatibility
snapshotIdFollow-ups (deliberately not in this PR)
afterSnapshotIdcurrently carries three states (undefined= legacy caller,null= opted in holding nothing, string = holding an ID). The repo already has the idiomatic mechanism for this—status.getcapabilities read viastartRuntimeCapabilityProbe—andTERMINAL_QUERY_REPLY_INPUT_RUNTIME_CAPABILITYexists for the identical hazard of an old host silently stripping an unknown field. Advertisingworktree.catalog-snapshot.v1would reduce the field tostring | undefined.worktree.psconcern. MovingafterSnapshotIdontoRpcRequestandsnapshotId/notModifiedonto_meta, gated by a flag ondefineMethod, would let other polled methods (ui.get, repo metadata, terminal lists) opt in without their own result unions or client wrappers.Review loops
3e6a62d): restored unconditional reassertion of the confirmed catalog on the client, stopped superseded responses from clearing the current token, and replaced the per-limit LRU from Loop Linux support #1 with content-addressed IDs—which removes the cross-limit thrashing class outright rather than bounding it.