Skip to content

fix(pi): preserve runtime model choices before the first message - #32254

Closed
brennanb2025 wants to merge 9 commits into
mainfrom
brennanb2025/pi-rpc-inventory
Closed

brennanb2025 wants to merge 9 commits into
mainfrom
brennanb2025/pi-rpc-inventory

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​692 $\color{#cf222e}{\Huge{\mathbf{−}}}$​115 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​577
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​244 $\color{#cf222e}{\Huge{\mathbf{−}}}$​96 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​148

ELI5

Before a Pi chat starts, Orca reads a text model table and rebuilds a coarse thinking menu. Running Pi chats read richer RPC metadata, so the choices before the first message and after refresh can lose model-specific thinking levels.

This PR uses the installed CLI's RPC inventory and the same checked projection as live Pi. Cold labels match runtime names, provider-qualified model IDs remain intact, and thinking choices retain per-model levels, explicit exclusions and offered extended levels. Non-reasoning models have no effort control.

What changed

Discovery uses a fresh bounded sessionless child in the requested folder, with caller/account environment isolation and one inventory request. It uses the existing host/account/folder catalog, refresh pacing and retained-good result. Folder discovery starts on demand through the existing quiet loading state. Refresh uses a fresh installed CLI while an existing chat retains its child. Saved chat choices and mixed-peer wire payloads remain unchanged.

The catalog now writes schema 4 in the same atomically replaced JSON file. Exact canonical model definitions can be shared by generation-local ordinal references; each source retains its own support, origin, clocks and completeness, while configured choices and order remain independent. The checked schema 3 reader preserves valid existing source lists during upgrade. Complete framing and reference validation precede yielded reconstruction and hydration. Nested graphs are owned before asynchronous acceptance, outward answers are detached, and a weak encoding cache reuses only owned model graphs. The writer retains coalescing, one active operation, retryable diagnosed failure, old-or-new publication and latest joined flush behavior.

The common pattern is one checked source of model facts with persistence serving observation bookkeeping. Intended differences preserve Orca's retained folder/source history, independent execution hosts and mixed-peer behavior. Existing configured-default source handling remains unchanged; an inventory observation is not execution evidence.

Review also corrected account-only preload applicability through the existing optional folder marker. Modern clients do not use those rows for an unrelated folder's first frame; direct account reads and saved rows remain intact.

Remaining integration and risk

Review is ongoing; this is not a readiness claim. #31927 and #31321 remain integration prerequisites for their separately owned action/read-boundary and cleanup contracts. No unmerged branch is imported here. Integration must preserve the nested capture before the relocated live-listing queue and keep those owners' fences. Lifetime/admission, native-baseline startup, final cold behavior and typed cleanup integration remain pending, as do final main sync and required changed-flow QA.

All-distinct whole-file bandwidth is an UNMEASURED risk. Exact sharing reduces equal-content repetition; genuinely distinct source bodies are still rewritten in full. No all-distinct timing pass or failure is claimed.

The previous schema 3 implementation failed the defined sustained-write throughput gate: 9 of 83 full acknowledged writes took at least 500 ms. That timing includes encoding, scheduling, asynchronous I/O and retirement; it does not establish a disk-only cause. The schema 4 physical gate also failed: on the same low-spec 100-folder × 401-model restore burst, one full acknowledged write took 1,009.918 ms against the required under-500 ms limit. Publication alone took 1,009.469 ms. No disk-only cause is established. The run stopped at that first required failure; later load and sustained-update phases were not exercised.

Validation

  • At e942079547a1e5c02da2dd9a0adba9808a05db63, 160 tests passed across 12 explicitly named files through the test gate, and the normal pre-commit hook passed. Tests cover legacy/source preservation, final framing and shared-reference corruption, current-load-wins, retention/order, publication failures/reversion/retry, joined latest flush, nested input/output ownership, registered preload consumers, and equal/distinct actual-trigger work bounds at 10 and 100 scopes.
  • Full PR CI is blocked on this head by its current merge conflict; only the target-side clean workflow ran successfully. The single final main sync remains held until the external integration stage. A fresh independent storage implementation/work-shape review found no actionable correctness or architecture issue. Final hydration still synchronously clones admitted graphs; the full-load physical phase was not reached, so its latency remains unmeasured.
  • The unchanged low-spec physical gate failed its first restore-burst phase at this head (Node exit 2). Callback p95 was 0.801 ms and max 25.473 ms, within the 16/50 ms limits; acknowledged writes were 1,009.918 and 101.468 ms, so the every-write-under-500 ms requirement failed. The run wrote 216,537 bytes; steady bytes per minute, full load/hydration, 20 normal writes, sustained backlog and latest shutdown reload remain unmeasured. The recorded process retired, no handles remained, config hashes were unchanged, and the slot was released. No rerun or alternative pass is claimed.
  • Real-agent changed-flow QA, previous-build restart/upgrade and required phone/mixed-peer evidence remain pending. Full review path applies because RPC/process lifetime, persistence and ownership change.

Visual proof

Pending the required changed-flow QA.

Agent skill upstream boundary

  • Not applicable; this change copies no skill-installer material.

@brennanb2025
brennanb2025 marked this pull request as ready for review October 23, 2026 08:33
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Pi model discovery now uses sessionless JSONL RPC inventory data instead of a text listing. Pi is configured to list models in chat folders. The catalog service marks workspace-dependent models for agents configured for folder listings. Tests cover concurrent folder reads, account switching, saved catalog preload, and RPC inventory behavior. Catalog persistence now uses SQLite, imports legacy JSON documents, and coalesces writes using accepted and durable revisions. Additional tests cover persistence timing, failure handling, and session-document array validity.

Priority: Normal

Merge Risk: Moderate · up to 49b77

If a saved catalog row is rejected, for example after a later build tightens parsing, model catalog saving stops and saved models are not restored. Hydrating a full saved catalog can also evict a model listing fetched in the same run, which then has to be fetched again. Fix the unparseable-row handling before merging; the eviction ordering is a smaller follow-up.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check Warning The description gives detailed ELI5, change, risk, and validation information. However, it omits the required Linked Issue section and does not provide the required Testing and Checklist sections. Vis… Add a valid issue link under “Linked Issue” using “Fixes #”. Add the required Testing and Checklist sections, including completed or explicitly deferred checklist items. Provide the required visual proof, or state “N/A” with a brief…
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly describes the main change: preserving Pi runtime model choices before the first message.
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 gives detailed ELI5, change, risk, and validation information. However, it omits the required Linked Issue section and does not provide the required Testing and Checklist sections. Visual proof is marked pending instead of providing evidence or stating N/A with a reason.

Resolution

Add a valid issue link under “Linked Issue” using “Fixes #<number>”. Add the required Testing and Checklist sections, including completed or explicitly deferred checklist items. Provide the required visual proof, or state “N/A” with a brief reason if there is no visual or interaction change. Complete the AI Disclosure section when applicable and add Notes addressing the listed compatibility and performance considerations.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 69cc68aa-1336-4695-a4b9-ba9e2ab98723
📥 Commits

Reviewing files that changed from the base of the PR and between 9b54cf9 and 1da6d7a.

📒 Files selected for processing: 4
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.test.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts
  • src/renderer/src/runtime/host-model-catalog-snapshots.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

oldEntry
)
recordHostModelCatalogSnapshot(LOCAL, agent, null, {
...list(false),

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

Use the scoped account result in the final assertion.

For Pi and OpenCode, account.modelsDifferByWorkspace is true. list(false) removes that flag, so the final assertion expects a folder-scoped first frame to borrow the old account model. Record account instead, then expect the old model only when folderScoped is false. This keeps the post-failure check aligned with the result the service actually returns.

@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: 2


ℹ️ Review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 645edc7d-872a-46df-a784-c8543442e7bc
📥 Commits

Reviewing files that changed from the base of the PR and between b04d8d7 and 49b7708.

📒 Files selected for processing: 7
  • src/main/ai-vault/session-document-stream-contract.test.ts
  • src/main/ai-vault/session-document-stream.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-database.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts
  • src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts
  • tests/e2e/folder-model-catalog-preload.unit.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment on lines +116 to +125
const entry =
typeof row.payload === 'string' ? parseEntry(JSON.parse(row.payload)) : null
if (
!entry ||
entry.fingerprint !== row.fingerprint ||
entry.agent !== row.agent ||
row.position !== rows.length
) {
throw new Error('Invalid model catalog source row')
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Does agentModelCatalogEntry / entry-with-success validate labels and effort choices like parseModel does?
fd -t f 'agent-model-catalog-entry.ts' --exec sed -n '1,200p' {}
rg -nP -C4 '\bexport function agentModelCatalogEntry(WithSuccess)?\s*\(' --type=ts
# Pi RPC inventory mapping: can it emit empty labels/efforts?
fd -t f 'rpc-options.ts' --exec rg -n -C3 'label|efforts|value' {}

Repository: stablyai/orca

Length of output: 12930


🏁 Script executed:

set -u
# Locate the database factory caller, the persistence drain/initialize owner, and the entry parser definitions.
rg -n -F --glob '*.ts' -e 'createAgentModelCatalogDatabase' -e 'function initialize' -e 'ready = ' -e 'drain(' -e 'parseEntry' -e 'persistedEntry' src/main/native-chat/ || test "$?" -eq 1

echo '--- database reader (agent-model-catalog-database.ts) ---'
nl -ba src/main/native-chat/agent-model-catalog/agent-model-catalog-database.ts | sed -n '1,200p'

echo '--- persistence owner (agent-model-catalog-persistence.ts) 150-260 ---'
nl -ba src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts | sed -n '150,260p'

echo '--- parseEntry / persistedEntry definitions ---'
rg -n -F --glob '*.ts' -e 'parseEntry' -e 'persistedEntry' src/main/native-chat/agent-model-catalog/ || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 18403


Skip unparseable catalog rows instead of stopping all saves.

A stored row that fails parseEntry, or fails the identity or position checks, makes read() throw. The error then stops every later save:

  • initialize() rejects, so ready stays false.
  • drain() runs initialize() inside its try. Its catch skips database.write. Each later drain repeats the read and fails the same way.
  • Nothing rewrites the database. Saved rows are not hydrated until the file changes outside the app.

The legacy JSON path behaves differently. Its consume callback skips entries that parseEntry rejects.

A row can reach this state after a later build tightens parseEntry and rejects rows that an earlier build wrote. The SQLite read checks only user_version and the table schema. It does not check SCHEMA_VERSION.

Skipping such a row also needs a matching change in write(). Skipped rows leave gaps in the stored position values. write() renumbers a kept row only when its index differs from the prior acknowledged order, and that order excludes skipped rows. A kept row can therefore keep its old stored position. The next read then fails the strict position check.

Corrected approach:

  • On read, skip a row whose parseEntry result is null or whose identity differs. Keep the payload type check. Check each row's stored position against the SQL row index, counting skipped rows, so the ordering check still holds.
  • On write, renumber every kept row whenever the read skipped one, so the stored positions become contiguous.

Comment on lines +78 to +87
const hydrate = (loaded: AgentModelCatalogEntry[]): void => {
for (const entry of loaded) {
if (!this.entries.has(entry.fingerprint)) {
this.entries.set(entry.fingerprint, entry)
if (independentAgentModelCatalog(entry.agent)) {
this.dueEntries.add(entry.fingerprint)
}
}
}
this.evictOverCap()

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

Hydration evicts entries from this run before saved entries.

hydrate adds loaded entries after the entries this run already recorded. evictOverCap() then deletes keys in insertion order, oldest first. Entries recorded before or during attachment are now the oldest, so they are evicted first. Saved entries survive in their place. This breaks the docstring rule: "Anything this run already listed wins."

Trigger: the saved catalog holds AGENT_MODEL_CATALOG_MAX_ENTRIES (256) entries. The store records a listing for a new fingerprint before attach finishes. The SQLite read now yields once per row, so this window is longer than before. Hydration then grows the map to 257 entries and evicts the new listing. The listing has to be fetched again.

Fix: put loaded entries before the entries this run recorded, so the current-run entries count as most recent.

Proposed fix
--- "a/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts"
+++ "b/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts"
@@ -75,17 +75,22 @@
   /** Hydrates last-good entries from disk. Anything this run already listed wins. */
   async attachPersistence(persistence: AgentModelCatalogPersistence): Promise<void> {
     this.persistence = persistence
     const hydrate = (loaded: AgentModelCatalogEntry[]): void => {
+      const current = [...this.entries]
+      this.entries.clear()
       for (const entry of loaded) {
-        if (!this.entries.has(entry.fingerprint)) {
+        if (!current.some(([key]) => key === entry.fingerprint)) {
           this.entries.set(entry.fingerprint, entry)
           if (independentAgentModelCatalog(entry.agent)) {
             this.dueEntries.add(entry.fingerprint)
           }
         }
       }
+      for (const [key, entry] of current) {
+        this.entries.set(key, entry)
+      }
       this.evictOverCap()
     }
     return persistence.attach?.(this.persistedEntries, hydrate) ?? persistence.load().then(hydrate)
   }
 

For large maps, build a Set of the current keys and use it instead of current.some.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const hydrate = (loaded: AgentModelCatalogEntry[]): void => {
for (const entry of loaded) {
if (!this.entries.has(entry.fingerprint)) {
this.entries.set(entry.fingerprint, entry)
if (independentAgentModelCatalog(entry.agent)) {
this.dueEntries.add(entry.fingerprint)
}
}
}
this.evictOverCap()
const hydrate = (loaded: AgentModelCatalogEntry[]): void => {
const current = [...this.entries]
this.entries.clear()
for (const entry of loaded) {
if (!current.some(([key]) => key === entry.fingerprint)) {
this.entries.set(entry.fingerprint, entry)
if (independentAgentModelCatalog(entry.agent)) {
this.dueEntries.add(entry.fingerprint)
}
}
}
for (const [key, entry] of current) {
this.entries.set(key, entry)
}
this.evictOverCap()

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Superseded by #34592, which merged. Pi's pre-first-message thinking menu now comes from the same model listing the live chat uses.

@brennanb2025
brennanb2025 deleted the brennanb2025/pi-rpc-inventory branch October 30, 2026 07:27
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