Skip to content

refactor(mobile): own the request/cache lifecycle in GenerationScopedRequestOwner, piloted on the legacy file inventory (step 5) - #20914

Merged
Jinwoo-H merged 6 commits into
mainfrom
step5-lifecycle
Sep 16, 2026
Merged

Jinwoo-H merged 6 commits into
mainfrom
step5-lifecycle

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​516 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​512
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​315 $\color{#cf222e}{\Huge{\mathbf{−}}}$​46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​269

Step 5 pilot of the mobile RPC contract foundation: request/cache lifecycle moves out of hand-rolled generation refs into one owned object, piloted on the legacy file inventory. No wire change, zero goldens moved.

Diff composition (head 3108e92b2e, vs 0869d997c8)

Part Files Added Deleted What it is
Owner + compile fence 2 +247 0 generation-scoped-request-owner.ts, generation-scoped-lease-compile-fence.ts (8 @ts-expect-error assertions in a non-test file, verified in tsc --listFiles)
Owner tests 1 +424 0 lifecycle-owner.test.ts: five named schedules + six boundary tests + a loader-write source fence with a probe
Pilot migration 1 +40 -38 use-mobile-native-chat-file-search.ts
RpcClient + stream health 2 +8 -3 optional read-only getGeneration (the logical authority epoch migrateTo advances; StableLogicalRpcClient already exposed it); mobile-session-tabs-stream-health.ts drops its hand-rolled duplicate declaration and an unexplained cast
Mutant re-anchor 1 +9 -5 race now targets the owner's generation compare, the only place it exists
Goldens 0 0 0

What

GenerationScopedRequestOwner: private cache, in-flight map, generation token. read/load take a scope (authority epoch, workspace identity, params) and build the key themselves; a scope the owner has not seen retires everything before it answers. Publication only through commit(lease, value); the lease brand is module-private so no caller can mint one; a lease whose generation moved is refused. reset bumps even on A→B→A. Soundness in two halves: commit refuses a moved generation, and a commit that beat the owner's notice is unreachable because the next read syncs first.

Pilot: the hook's generationRef / legacyPathsRef / legacyLoadRef, their reset lines, the captured-generation compare in the reply handler, the conditional .finally, and the post-await re-read are deleted; one useRef owner, a three-line inventoryScope(), and read → load → commit replace them.

Evidence

  • Zero goldens. The pilot commit touches 4 files, none under mobile/rpc-foundation/. All 9 legacy-inventory goldens reproduce byte for byte (b1's A→B→A schedule, interruptions: timeout / disconnect / cutover, lifecycle: reset / unmount / blur). Recording suite 18 files / 752 passed (lead-reproduced).
  • Five schedules, each an explicit promise resolution order: key-reset-cleanup (reset drops both maps, advances once, second load does not join a retired request); blur (reset with scope unchanged retires the lease); cutover (authority change retires scope and in-flight identity); reconnect-mid-request (two owners, same workspace: the one omitting the session epoch commits, the one carrying it is refused, the per-owner decision made concrete); stale-inflight-cleanup (A→B→A same key, different generation, first visit's reply refused).
  • Mutations, applied/run/reverted. Delete the generation compare in commit → blur, cutover, reconnect-mid-request, stale-inflight-cleanup and the b1 golden fail (key-reset-cleanup survives, correctly). Pilot ignores the commit verdict → survives everything: the display is independently fenced by the query sequence counter, so the verdict is defence in depth at this site. Pilot publishes through a plain ref, owner kept for single-flight only → b1 golden catches it. The mutant covers "owner loses the compare"; the golden covers "site stops using the owner".

Findings

  1. The plan's negotiated capability epoch does not exist on mobile: negotiation is one-way and discards its result. Not invented; the owner's scope accepts any epoch and the pilot's capability latch still invalidates on host and workspace identity.
  2. The owner has no dispose(). A React effect cleanup cannot own one: the pilot's cleanup runs on every dep change (worktreeId is a dep) and the owner lives in a ref that outlives it, so a workspace select would dispose it permanently; swapping in a disposing owner fails 7 tests across 3 files. reset() is the teardown call: it drops the cache and refuses stale commits without changing what reaches the wire (lifecycle-inventory-lifecycle pins files.list sent after unmount).
  3. authenticationGeneration has no product reader; not exposed on DirectRpcClient. The reconnect-mid-request schedule proves the owner handles it via a fake.
  4. The query cache in the same hook is a display cache (one write site inside applyPaths, reached from three call sites, all derived values), not a request lifecycle; left as-is.

Ticket owed, not fixed here

use-mobile-native-chat-file-search.ts:92: the query-cache eviction loop breaks on if (!oldest), and normalizedQuery can be '', so once the empty query is the oldest key the loop exits and the cache grows past FILE_SEARCH_QUERY_CACHE_LIMIT. The guard should test the iterator's done. Pre-existing.

Next sites (not done here)

use-mobile-source-control-loaders.ts: branch-compare leg fits as-is; status leg needs a lease surviving two commits (loading, ready) plus a mount latch. use-mobile-session-terminal-list.ts + mobile-terminal-inventory-request.ts: allowEmptyLoaded ||= merges a flag into an in-flight request and the reply writes several stores; does not fit as-is.

Gates

ORCA_BACKGROUND_LAUNCH=1: mobile typecheck 0; mobile test 594 files / 5527 passed / 6 skipped; pnpm tc 0; check:code-quality:changed 0 new across 6 files; check:react-doctor:changed 0; audit:anti-slop 0; oxfmt --check . from mobile/ clean; oxlint on 6 files 0. Lead re-ran owner tests + recording suite and mobile typecheck.

Review round 1 (2026-09-16)

Ship after deletions. All eight verification items confirmed with evidence (lease unmintable: five tsc-rejected attempts and a live fence; four of five schedules fail on their invariant; the loader-write fence's probe fires and its presence precondition bites; race dies against the re-anchored owner compare; only StableLogicalRpcClient implements getGeneration, and production always hands the hook one). Applied as b06b0f4cff + 3108e92b2e (5 files, +36/−79, zero goldens): dispose() and its guards deleted (see finding 2); capacity and the FIFO eviction loop deleted (dead in production); two unreferenced exports and the test-only generation getter dropped; the duplicate GenerationClient declaration and its cast in mobile-session-tabs-stream-health.ts replaced by the widened RpcClient; key-reset-cleanup now leaves a second load pending across the reset so deleting inFlight.clear() from retire() fails it (it was vacuous on that half); inventoryScope is a const computed once per attempt; read's doc states that it retires an unseen scope and must not run from render. Lead-reproduced at 3108e92b2e: owner + stream-health + recording suites 19 files / 767 passed; typecheck 0.

Review round 2 (2026-09-16, fresh reviewer)

Ship after two test-side fixes; the code was found sound and the contract holds (0 files under mobile/rpc-foundation/, recording suite 741 passed, the race mutant dies, structural lease minting rejected by tsc, the compile fence load-bearing, five schedules deterministic over five shuffled runs, each owner mechanism kills its named schedule, behaviour equal to main at the pilot plus the deliberate unmount-generation bump). Applied as 65d5909409 + 89711d6f55 (+141/−41, 0 goldens, pilot hook source byte-identical):

  • Epoch in scope was ungated. Replacing client.getGeneration?.() ?? 0 with 0 left 711 tests green. New pilot schedule: a second query under the same epoch is answered from the held inventory (files.list count stays 1), the epoch advances, and the third query issues a second files.list and displays a path only the new authority returned. Mutant now fails expected 1 to be 2 (lead-reproduced).
  • Settle identity guard was untested. Making the in-flight delete unconditional left all schedules green; a stale request settling after reset() then cleared the live entry so a third load for the same key started a duplicate request. New schedule stale-settlement-cleanup asserts started and promise identity; mutant fails expected 3 to be 2 (lead-reproduced).
  • Header now says committed is not a freshness oracle for the value already in hand; the pilot's display is fenced by the sequence counter, equal to main.
  • RequestScope members exclude symbol and bigint at the type level (two fence assertions); the runtime symbol throw is deleted and the previously unguarded bigint path (V8's serialize error two frames down) is now a compile error.
  • The in-flight map holds the promise itself; InFlightRequest and the throwaway Promise.resolve(null) are gone, load is get ?? start.
  • Gate-driven: scopeMember inlined into scopeKey (anti-slop bans an object-typed parameter); the pilot test's five as unknown as RpcClient fakes collapse into one fakeClient helper with a single SAFETY cast.

Reviewer also confirmed getGeneration is implemented only by StableLogicalRpcClient, which openHostLogicalClient returns on every platform, so the ?? 0 fallback is unreachable in production; and named mobile-session-tabs-stream-health.ts (in-flight map + settle identity compare at :246) as the owner's second caller.

…estOwner (step 5)

Hooks guard stale replies with hand-rolled generation counters, `isCurrent`
callbacks and latest-wins refs, so the guard is a callback a caller may forget.

The owner keeps the cache, the in-flight identity and the generation token
private. `read` and `load` are handed the scope and build the key themselves, so
a scope the owner has not seen retires everything it held before it answers, and
two workspaces cannot share a key. Publication goes only through
`commit(lease, value)`: the lease brand is module-private, so no caller can mint
one, and a lease whose generation moved is refused. `reset` bumps even when the
scope came back to where it started, as in A to B to A.

Three epochs may sit in a scope and they are not the same thing: the logical
authority epoch, the physical authenticated session and the negotiated
capability epoch. Which of them retires a given owner's data is that owner's
decision, expressed by what its callers put in the scope.

`lifecycle-owner.test.ts` carries one named schedule each for
key-reset-cleanup, blur, cutover, reconnect-mid-request and
stale-inflight-cleanup, each written as an explicit resolution order. It also
fences loader bodies: a `load` callback that writes state it did not declare is
rejected by the same kind of source scan that fences raw casts. Compile-time
assertions live in a non-test file because mobile's tsconfig excludes tests.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…r (step 5)

The native-chat file search kept three hand-rolled guards for one request: a
generation counter bumped by an effect, a committed-paths ref, and an in-flight
ref whose `finally` cleared itself conditionally. The stale-reply check lived in
the reply handler, where a caller could forget it.

The owner replaces all three. `read` and `load` are handed the scope, so the
guard runs before either can answer, and the reply is published only through
`commit(lease, value)`. What retires the inventory is named at the call site:
this host, this workspace, this logical authority epoch. A reconnect to the same
host leaves the files on disk alone, so the physical authenticated-session epoch
is deliberately not in the scope.

`RpcClient` gains one optional read-only signal, `getGeneration`, so a holder of
a bare client can scope cached work to the logical authority epoch that
`StableLogicalRpcClient.migrateTo` advances. Nothing else about either client
widens.

No golden moves: all nine legacy-inventory recordings reproduce byte for byte,
including the A-to-B-to-A and cutover schedules. The `race` mutant is re-anchored
on the owner's generation compare, which is now the only place that compare
exists, and it still dies against b1.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

@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 — the full two-commit diff for step 5 of the mobile RPC contract foundation.

  • GenerationScopedRequestOwner — new transport module owning one request family's cache, in-flight single-flight map and generation token. read/load build their own key from a caller-supplied scope, retire on an unobserved scope, and can only publish through commit(lease, value) with a module-private lease brand.
  • Compile fence — generation-scoped-lease-compile-fence.ts encodes the lease/scope/parameter/loader claims as @ts-expect-error assertions checked by tsc, following the existing rpc-operation-compile-fence.ts pattern.
  • Pilot migration — use-mobile-native-chat-file-search.ts drops generationRef/legacyPathsRef/legacyLoadRef and the hand-rolled generation compare in favour of one owner (cleanup uses reset(), so the unmount-before-1 wire stays unchanged).
  • RpcClient.getGeneration — optional read-only logical authority epoch, letting the pilot scope the inventory to a cutover without every implementation growing a counter.
  • Mutant re-anchor — the race recording mutation now targets the owner's generation compare; anchor count verified unique.
  • Owner tests — five explicit schedules, boundary/eviction/coalescing tests, and a source-scan loader-write fence with probes.

I traced the pilot against the deleted ref logic (stale replies do not cache or apply, overlapping queries still coalesce, rejected inventory reads are retried) and walked the race mutant through the b1 A→B→A schedule: deleting the generation compare lets the stale reply commit under the returned-to-A key and poison the next read, which the golden catches. oxlint is clean on all six changed files. The mobile vitest suite could not be executed locally — mobile dependencies are not installed in this environment — so the test claim rests on static tracing plus the PR's recorded run, not on a run here.

ℹ️ The owner's contract is one scope at a time

enter retires the entire owner — cache and in-flight map together — whenever the incoming scope key differs from the last observed one (generation-scoped-request-owner.ts:182-198). That is exactly what makes the A→B→A and cutover schedules safe, but it also means an owner can never hold two scopes concurrently: a caller that alternates scopes loses both the cache and any shared in-flight request on every flip. The pilot and the announced next sites all read one worktree at a time, so this is fine today; it is simply the property later migrators are most likely to assume away.

Technical details
# Single active scope per owner

## Affected sites
- `mobile/src/transport/generation-scoped-request-owner.ts:182-198` — `enter` compares a single `observedScope`; `retire` clears both `values` and `inFlight`.

## Required outcome
- No change requested for this PR. The single-active-scope behavior is intentional and documented in the class header; the ask is only that it be an explicit part of the foundation's contract before the next sites are migrated, so a caller that does hold two scopes is not built on it by accident.

## Open questions for the human
- Should the foundation eventually support N concurrent scopes (e.g. per-scope keys with a bounded LRU), or is one-owner-one-scope intended to be permanent?

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

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 237cd98c-7044-4881-b474-163575272f2d

📥 Commits

Reviewing files that changed from the base of the PR and between 3108e92 and 89711d6.

📒 Files selected for processing (4)
  • mobile/src/session/use-mobile-native-chat-file-search.test.ts
  • mobile/src/transport/generation-scoped-lease-compile-fence.ts
  • mobile/src/transport/generation-scoped-request-owner.ts
  • mobile/src/transport/lifecycle-owner.test.ts

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


📝 Walkthrough

Walkthrough

The change adds GenerationScopedRequestOwner for scoped caching, request coalescing, lease validation, and generation retirement. The chat file search hook uses it for workspace inventory requests and commits only current results. RpcClient exposes an optional logical generation. New tests cover lifecycle behavior, ownership boundaries, inventory reloads, and compile-time API invariants. The mutation anchor now targets the owner’s generation guard.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 89711

The generation-scoped inventory changes preserve scope retirement, stale-result rejection, and in-flight cleanup behavior without an identified merge-blocking risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed change, rationale, testing, evidence, review findings, and scope information. However, it omits required template content, including the Linked Issue with a Fixes #… Add the missing template sections. Include a linked issue using Fixes #...; provide before-and-after visual proof or write N/A with a reason; complete AI Disclosure; complete the Agent skill upstream boundary section; address the Notes …
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the main change: moving request and cache lifecycle ownership to GenerationScopedRequestOwner for the legacy mobile file inventory. It is specific and related to the chang…
Full details: Description check

Explanation

The description provides detailed change, rationale, testing, evidence, review findings, and scope information. However, it omits required template content, including the Linked Issue with a Fixes # reference, explicit Visual Proof or N/A reason, AI Disclosure, Agent skill upstream boundary, Notes, and the Checklist.

Resolution

Add the missing template sections. Include a linked issue using Fixes #...; provide before-and-after visual proof or write N/A with a reason; complete AI Disclosure; complete the Agent skill upstream boundary section; address the Notes items; and check or explain each Checklist item.

  • 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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 60c491bf-8421-48d2-9462-672d65529c85

📥 Commits

Reviewing files that changed from the base of the PR and between a9232e8 and ea51e70.

📒 Files selected for processing (6)
  • mobile/src/session/use-mobile-native-chat-file-search.ts
  • mobile/src/test-support/rpc-recording/mutants/operation-mutations.ts
  • mobile/src/transport/generation-scoped-lease-compile-fence.ts
  • mobile/src/transport/generation-scoped-request-owner.ts
  • mobile/src/transport/lifecycle-owner.test.ts
  • mobile/src/transport/rpc-client.ts

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

Comment on lines +109 to +125
if (held) {
applyPaths(rankSuggestions(held, normalizedQuery, FILE_SEARCH_RESULT_LIMIT))
return
}
const legacyPaths = legacyPathsRef.current
if (legacyPaths) {
applyPaths(rankSuggestions(legacyPaths, normalizedQuery, FILE_SEARCH_RESULT_LIMIT))
// Why: older hosts expose only the full inventory RPC; queries that
// overlap its slow local/SSH read must share one request.
const loaded = await inventory.load(inventoryScope(), WHOLE_WORKSPACE, async () => {
const response = await nativeChatFileInventoryRead.request(client, {
worktree: `id:${worktreeId}`
})
const accepted = nativeChatFileInventoryRead.interpret(response)
return accepted.accepted ? extractPaths(accepted.value) : null
})
if (!loaded || inventory.commit(loaded.lease, loaded.value) !== 'committed') {
return
}
applyPaths(rankSuggestions(loaded.value, normalizedQuery, FILE_SEARCH_RESULT_LIMIT))

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Revalidate the inventory scope before committing. MobileEndpointSupervisor and MobileRelaySessionEstablisher can call StableLogicalRpcClient.migrateTo while nativeChatFileInventoryRead is pending. sendRequest still resolves a correlated response after cutover, but GenerationScopedRequestOwner.commit checks only its unchanged internal generation. The migration does not reset inventory or increment sequenceRef, so the old lease can commit and applyPaths can display results from the previous logical authority. Revalidate the current scope at settlement or retire the owner during migration.

…tep 5 review)

Review round 1 on #20914 found three pieces of surface with no product
reader and one vacuous assertion.

`dispose()` is gone with the `disposed` field, the three guards that read
it and the `'disposed'` verdict arm. A React effect cleanup cannot use it:
the pilot's cleanup runs on every dep change and the owner outlives it in
a ref, so a workspace select would dispose it permanently. Swapping
`reset()` for `dispose()` there fails 7 tests across 3 files.

`capacity` and its eviction loop are gone too. No caller varied it, so the
loop never ran in production, its `if (oldest.done) break` was
unreachable, and it evicted in insertion order while its name said
capacity.

`RequestCommitVerdict` and `RequestParameters` lose their `export` (no
importer), as does the `generation` getter and the expect-error assertion
that pinned it (test-only reader; `reset` advancing is proven by the
verdict a lease from the previous generation gets). `LoadedRequest` keeps
its export: it names the value of the public `load` promise, which a
helper over that result has to write down.

`key-reset-cleanup` now leaves a second request pending across the
`reset()` and asserts the post-reset load starts its own, which is the
half `inFlight.clear()` actually owns. Proof: deleting that line from
`retire()` failed this schedule and `stale-inflight-cleanup`; before the
change it failed only the latter.

`read`'s doc now says it retires an unseen scope before answering and
must not be called from render.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…mpt once (step 5 review)

Two call-site findings from review round 1 on #20914.

`mobile-session-tabs-stream-health.ts` hand-rolled
`RpcClient & { getGeneration?: () => number }` and cast through it with no
SAFETY rationale. `RpcClient` declares the member now, so both go and the
read is `this.options.client.getGeneration?.() ?? 0`.

The file-search pilot built its scope from a function it called twice in
one attempt, so a `migrateTo` landing between the cache read and the load
would have put one attempt in two scopes. It is a `const` computed once
per attempt.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

@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 — the two round-1 commits since the prior pullfrog review (b06b0f4cff, 3108e92b2e), applied on top of the already-reviewed pilot.

  • Slimmed GenerationScopedRequestOwner to what callers use — dispose() with its disposed latch and the three guards that read it, capacity with its eviction loop, the generation getter, and the 'disposed' verdict arm are deleted; RequestCommitVerdict and RequestParameters drop their exports. None of these had an importer.
  • Read the pilot scope once per attempt — inventoryScope is a const built once, so a migrateTo landing between the cache read and the load can no longer split one attempt across two scopes.
  • Dropped the hand-rolled client cast — mobile-session-tabs-stream-health.ts reads this.options.client.getGeneration?.() directly now that RpcClient declares the optional member.
  • Made key-reset-cleanup non-vacuous — a second request stays pending across reset() and asserts the post-reset load starts its own request, so deleting inFlight.clear() from retire() fails it; the dispose and eviction tests go with the code they exercised.
  • Retired the stale type-level assertion — the compile fence drops fenceGenerationIsReadOnly alongside the getter it pinned.

I re-walked read/load/commit/retire against the deleted guards, the pilot's read → load → commit flow (including the rejected/null retry path through settle), and each updated schedule; the removals are behavior-preserving for every current caller, and the race mutant still applies exactly once for b1 because only the file-inventory adapter loads a file that transitively imports the owner. I could not run the mobile suite here (mobile dependencies are absent in this environment), so the verdict rests on static tracing plus the PR's recorded run.

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 53d87b7a-6d7d-430d-b731-d6067809215c

📥 Commits

Reviewing files that changed from the base of the PR and between ea51e70 and 3108e92.

📒 Files selected for processing (5)
  • mobile/src/session/mobile-session-tabs-stream-health.ts
  • mobile/src/session/use-mobile-native-chat-file-search.ts
  • mobile/src/transport/generation-scoped-lease-compile-fence.ts
  • mobile/src/transport/generation-scoped-request-owner.ts
  • mobile/src/transport/lifecycle-owner.test.ts
💤 Files with no reviewable changes (1)
  • mobile/src/transport/generation-scoped-lease-compile-fence.ts

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

// reconnect to the same host leaves the files on disk alone, so the physical session
// epoch is deliberately not in it. Read once, so a cutover between the two calls below
// cannot put one attempt in two scopes.
const inventoryScope: RequestScope = [client, worktreeId, client.getGeneration?.() ?? 0]

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Revalidate the logical generation before committing the inventory.

StableLogicalRpcClient.sendRequest propagates fulfilled responses without checking the generation, and migrateTo advances the generation before closing the previous session. An old files.list response can therefore reach nativeChatFileInventoryRead.request, inventory.commit, and applyPaths after cutover. GenerationScopedRequestOwner does not observe the new scope unless another owner operation enters it, so the old lease can still commit. If the generation changed after the await, discard the result or retry with a fresh scope before inventory.commit.

…review)

Review round 2 on #20914, owner side.

`RequestScope`'s element type now excludes symbol and bigint, so both are
compile errors with an assertion each in the fence. The runtime symbol
throw is gone with the untested branch it guarded, and the bigint case it
never covered (it reached `JSON.stringify` and threw V8's serialize
message from two frames down) cannot be written.

`InFlightRequest<Value>` existed only so its own `then` callbacks could
name the entry they belonged to, which forced a throwaway
`Promise.resolve(null)` that the next statement overwrote. The map holds
the request promise itself and `settle` compares promise identity.

`scopeMember` is inlined into `scopeKey`'s map callback: with symbol gone
the member type is the scope's element type, which spells `object`, and
anti-slop bans that in a parameter position. Inferred in a callback it is
the same type with no annotation to ban.

Header: `committed` says the generation still holds, not that the value
already in the caller's hand is fresh. The pilot displays `loaded.value`
directly and is fenced by the sequence counter it had on main.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…t identity (step 5 review)

Review round 2 on #20914 found two invariants no test held.

The pilot's scope: replacing `client.getGeneration?.() ?? 0` with `0` left
all 711 tests green. The new schedule pairs a control with the claim. A
second query under the same epoch is answered from the inventory already
held, and a query after the epoch advances issues a second `files.list`
and displays what the new authority's host returned. Same client object,
same workspace, so the epoch is the only thing that can retire it. Proof:
with the literal `0`, `files.list` count is 1 where 2 is asserted.

`settle`'s identity guard: making the delete unconditional left all ten
schedules green. `stale-settlement-cleanup` puts a request in flight,
resets, starts a live request on the same key, then settles the retired
one last, whose cleanup names the slot the live request now holds. A third
load must join rather than start. Proof: unconditional delete gives
`started` 3 against 2.

The fake clients go through one `fakeClient` helper, which is what lets
the new case name the two members the hook reaches without a fifth
`as unknown as RpcClient` (four deleted, one fenced assertion left with
its rationale).

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
@Jinwoo-H
Jinwoo-H merged commit 615b137 into main Sep 16, 2026
21 of 22 checks passed
@Jinwoo-H
Jinwoo-H deleted the step5-lifecycle branch September 16, 2026 01:31
@joinwell52-AI

Copy link
Copy Markdown

@Jinwoo-H The split between request ownership and display freshness was useful for our agent-runtime research. We ran the complete owner module at 89711d6 with eight controlled schedules, then repeated them with only the generation comparison removed. This was a deliberate ablation, not a historical Orca version or a mobile UI test.

The original rejected the old A reply after A→B→A; the ablation allowed the old value to be read. We also observed the distinction described in your header: a commit can beat notice of a scope change, yet the next read of the new scope makes that cached value unreachable. The stale-settlement case preserved the newer in-flight promise without starting a duplicate load.

That helped us separate three responsibilities: declaring the scope, owning the pending request, and deciding what may reach the display. I saw the existing settlement-scope review discussion and am not presenting this as a new pilot defect.

Your note about the next status loader needing both loading and ready publications raises a further question: should those publications share one attempt lease, or have distinct publication leases while retaining the same display-sequence check? We have not tested that extension; it seems a useful place to make the lifetime contract explicit before migrating a multi-publication caller.

Controlled schedules, ablation and saved observations

ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…RequestOwner, piloted on the legacy file inventory (step 5) (stablyai#20914)

* feat(mobile): own the request/cache lifecycle in GenerationScopedRequestOwner (step 5)

Hooks guard stale replies with hand-rolled generation counters, `isCurrent`
callbacks and latest-wins refs, so the guard is a callback a caller may forget.

The owner keeps the cache, the in-flight identity and the generation token
private. `read` and `load` are handed the scope and build the key themselves, so
a scope the owner has not seen retires everything it held before it answers, and
two workspaces cannot share a key. Publication goes only through
`commit(lease, value)`: the lease brand is module-private, so no caller can mint
one, and a lease whose generation moved is refused. `reset` bumps even when the
scope came back to where it started, as in A to B to A.

Three epochs may sit in a scope and they are not the same thing: the logical
authority epoch, the physical authenticated session and the negotiated
capability epoch. Which of them retires a given owner's data is that owner's
decision, expressed by what its callers put in the scope.

`lifecycle-owner.test.ts` carries one named schedule each for
key-reset-cleanup, blur, cutover, reconnect-mid-request and
stale-inflight-cleanup, each written as an explicit resolution order. It also
fences loader bodies: a `load` callback that writes state it did not declare is
rejected by the same kind of source scan that fences raw casts. Compile-time
assertions live in a non-test file because mobile's tsconfig excludes tests.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): put the legacy file inventory on the lifecycle owner (step 5)

The native-chat file search kept three hand-rolled guards for one request: a
generation counter bumped by an effect, a committed-paths ref, and an in-flight
ref whose `finally` cleared itself conditionally. The stale-reply check lived in
the reply handler, where a caller could forget it.

The owner replaces all three. `read` and `load` are handed the scope, so the
guard runs before either can answer, and the reply is published only through
`commit(lease, value)`. What retires the inventory is named at the call site:
this host, this workspace, this logical authority epoch. A reconnect to the same
host leaves the files on disk alone, so the physical authenticated-session epoch
is deliberately not in the scope.

`RpcClient` gains one optional read-only signal, `getGeneration`, so a holder of
a bare client can scope cached work to the logical authority epoch that
`StableLogicalRpcClient.migrateTo` advances. Nothing else about either client
widens.

No golden moves: all nine legacy-inventory recordings reproduce byte for byte,
including the A-to-B-to-A and cutover schedules. The `race` mutant is re-anchored
on the owner's generation compare, which is now the only place that compare
exists, and it still dies against b1.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): cut the lifecycle owner down to what callers use (step 5 review)

Review round 1 on stablyai#20914 found three pieces of surface with no product
reader and one vacuous assertion.

`dispose()` is gone with the `disposed` field, the three guards that read
it and the `'disposed'` verdict arm. A React effect cleanup cannot use it:
the pilot's cleanup runs on every dep change and the owner outlives it in
a ref, so a workspace select would dispose it permanently. Swapping
`reset()` for `dispose()` there fails 7 tests across 3 files.

`capacity` and its eviction loop are gone too. No caller varied it, so the
loop never ran in production, its `if (oldest.done) break` was
unreachable, and it evicted in insertion order while its name said
capacity.

`RequestCommitVerdict` and `RequestParameters` lose their `export` (no
importer), as does the `generation` getter and the expect-error assertion
that pinned it (test-only reader; `reset` advancing is proven by the
verdict a lease from the previous generation gets). `LoadedRequest` keeps
its export: it names the value of the public `load` promise, which a
helper over that result has to write down.

`key-reset-cleanup` now leaves a second request pending across the
`reset()` and asserts the post-reset load starts its own, which is the
half `inFlight.clear()` actually owns. Proof: deleting that line from
`retire()` failed this schedule and `stale-inflight-cleanup`; before the
change it failed only the latter.

`read`'s doc now says it retires an unseen scope before answering and
must not be called from render.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): read getGeneration off RpcClient and scope one attempt once (step 5 review)

Two call-site findings from review round 1 on stablyai#20914.

`mobile-session-tabs-stream-health.ts` hand-rolled
`RpcClient & { getGeneration?: () => number }` and cast through it with no
SAFETY rationale. `RpcClient` declares the member now, so both go and the
read is `this.options.client.getGeneration?.() ?? 0`.

The file-search pilot built its scope from a function it called twice in
one attempt, so a `migrateTo` landing between the cache read and the load
would have put one attempt in two scopes. It is a `const` computed once
per attempt.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): type the scope, drop the in-flight wrapper (step 5 review)

Review round 2 on stablyai#20914, owner side.

`RequestScope`'s element type now excludes symbol and bigint, so both are
compile errors with an assertion each in the fence. The runtime symbol
throw is gone with the untested branch it guarded, and the bigint case it
never covered (it reached `JSON.stringify` and threw V8's serialize
message from two frames down) cannot be written.

`InFlightRequest<Value>` existed only so its own `then` callbacks could
name the entry they belonged to, which forced a throwaway
`Promise.resolve(null)` that the next statement overwrote. The map holds
the request promise itself and `settle` compares promise identity.

`scopeMember` is inlined into `scopeKey`'s map callback: with symbol gone
the member type is the scope's element type, which spells `object`, and
anti-slop bans that in a parameter position. Inferred in a callback it is
the same type with no annotation to ban.

Header: `committed` says the generation still holds, not that the value
already in the caller's hand is fresh. The pilot displays `loaded.value`
directly and is fenced by the sequence counter it had on main.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): gate the epoch in the pilot scope and the in-flight slot identity (step 5 review)

Review round 2 on stablyai#20914 found two invariants no test held.

The pilot's scope: replacing `client.getGeneration?.() ?? 0` with `0` left
all 711 tests green. The new schedule pairs a control with the claim. A
second query under the same epoch is answered from the inventory already
held, and a query after the epoch advances issues a second `files.list`
and displays what the new authority's host returned. Same client object,
same workspace, so the epoch is the only thing that can retire it. Proof:
with the literal `0`, `files.list` count is 1 where 2 is asserted.

`settle`'s identity guard: making the delete unconditional left all ten
schedules green. `stale-settlement-cleanup` puts a request in flight,
resets, starts a live request on the same key, then settles the retired
one last, whose cleanup names the slot the live request now holds. A third
load must join rather than start. Proof: unconditional delete gives
`started` 3 against 2.

The fake clients go through one `fakeClient` helper, which is what lets
the new case name the two members the hook reaches without a fifth
`as unknown as RpcClient` (four deleted, one fenced assertion left with
its rationale).

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
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.

2 participants