Skip to content

Cache OpenAI-compat model discovery with a 30s TTL - #1860

Merged
malibio merged 3 commits into
mainfrom
issue-1807-model-cache
Jul 31, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1807-model-cache

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a 30-second TTL cache over discover_openai_compat_models in the daemon's LocalAgentService, so repeated ListModels RPCs within the window are served from cache instead of re-querying every configured OpenAI-compatible endpoint.
  • Adds ListModelsRequest.force_refresh (proto → daemon → Tauri chat_model_list → frontend chatModelList(forceRefresh)) so the explicit "Refresh remote models" action in Settings can bypass a fresh cache hit.
  • Updates the CLI and the unused list_local_models Tauri command for the new proto field.

Design notes

A TTL-only cache (no invalidate-on-config-write wiring) was chosen because SettingsServiceImpl (process-global, one instance) and LocalAgentServiceImpl (per-database, potentially multiple instances under ADR-053) are constructed in different scopes in assembly.rs — sharing invalidation state between them would require threading a new field through SharedContext and touching 4 platform-gated entrypoints in main.rs, for marginal benefit over a short TTL plus an explicit refresh escape hatch.

Acceptance criteria (issue #1807)

  • Repeated ListModels calls within the TTL do not re-query endpoints
  • A newly available model still appears without an app restart — TTL expiry (30s) or the "Refresh remote models" button (force_refresh)
  • A slow or dead endpoint does not stall the selector on every mount — cache hit avoids DISCOVERY_TIMEOUT on repeated calls

Test plan

  • cargo test -p nodespace-daemon — added 4 unit tests covering fresh-hit, stale-miss, force_refresh-bypass, and cache-population
  • cargo test --workspace — full workspace, no failures
  • bun run test — 171/171 files, 4113/4113 tests (frontend baseline unchanged)
  • bun run test:all — clean
  • bun run quality:fix — clean (ESLint, tsc, cargo fmt, cargo clippy -D warnings)

Closes #1807

🤖 Generated with Claude Code

malibio and others added 2 commits July 31, 2026 22:28
## Completed in This Session
- [x] Added a 30s TTL cache over discover_openai_compat_models in local_agent_service.rs
- [x] Added ListModelsRequest.force_refresh to bypass the cache (proto + daemon + Tauri + frontend)
- [x] Wired the Settings "Refresh remote models" button to force_refresh=true
- [x] Updated CLI and secondary Tauri list_local_models call sites for the new proto field
- [x] Added 4 daemon unit tests covering fresh-hit, stale-miss, force_refresh-bypass, and cache-population
- [x] cargo test -p nodespace-daemon passes (all suites); bun run test passes 171/171 files, 4113/4113 tests

## Remaining Work
- [ ] Run bun run test:all end to end and confirm no regressions
- [ ] bun run quality:fix and commit any formatting changes
- [ ] Push and open PR against #1807
- [ ] /pragmatic-code-review, address feedback loop

## Current State
- Files modified: packages/proto/proto/local_agent_service.proto,
  packages/daemon/src/services/local_agent_service.rs,
  packages/desktop-app/src-tauri/src/commands/chat_models.rs,
  packages/desktop-app/src-tauri/src/commands/local_agent.rs,
  packages/desktop-app/src/lib/services/tauri-commands.ts,
  packages/desktop-app/src/lib/components/settings/model-manager.svelte,
  packages/dev-tools/src/dev-proxy.ts,
  packages/cli/src/commands/model.rs
- Tests status: Passing (daemon unit tests + frontend bun run test baseline)
- Known issues: none currently open
- Dependencies: none

## Context for Next Session
TTL-only cache (no cross-service invalidation wiring) was chosen over an
invalidate-on-config-write design because SettingsServiceImpl (process-global)
and LocalAgentServiceImpl (per-database, potentially multiple instances) are
constructed in different scopes in assembly.rs, making shared invalidation
state architecturally awkward for the benefit gained. The 30s TTL plus an
explicit force_refresh bypass (used by the Settings "Refresh remote models"
button) satisfies all three acceptance criteria on issue #1807 without that
complexity.

## Acceptance Criteria Status
From issue #1807:
- [x] Repeated ListModels calls within the TTL do not re-query endpoints
- [x] A newly available model still appears without an app restart — TTL expiry
      (30s) or the explicit "Refresh remote models" button (force_refresh)
- [x] A slow or dead endpoint does not stall the selector on every mount —
      cache hit avoids DISCOVERY_TIMEOUT on repeated calls

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1860 (issue #1807)

Review Type: Initial Review

Reviewed the full diff against origin/main (2 commits, 9 files). Verified all ListModelsRequest construction sites, ran cargo test -p nodespace-daemon --lib services::local_agent_service (35 passed, incl. the 4 new tests), and read packages/core/src/services/relationship_cache.rs as the reference pattern.


Requirements Check

Acceptance criterion Status Notes
Repeated ListModels calls within the TTL do not re-query endpoints ✅ discover_openai_compat_models(false) returns the cached Vec when fetched_at.elapsed() < 30s. local_agent_service.rs:1120-1137. Covered by fresh_cache_entry_is_returned_without_requerying.
A newly available model still appears without an app restart; the mechanism is documented ✅ Two mechanisms: 30s TTL expiry, and force_refresh from the Settings "Refresh remote models" button. Documented at the const (local_agent_service.rs:103-112), on the proto field, on the Tauri command, and in chatModelList's TSDoc. Documentation quality here is genuinely above average.
A slow or dead endpoint does not stall the selector on every mount ⚠️ Satisfied for model-store and ai-chat-model-selector, but not for the Settings model-manager — see 🟡 finding #1.

Code Review Findings

🟡 Important

1. model-manager.svelte:121 — mount-time force_refresh: true re-introduces the exact stall the issue is about, for the Settings pane.

refreshRemoteModels() was changed to call chatModelList(true) (line 48), but it is invoked from two places:

 48:      const list = await chatModelList(true);   // now always force_refresh
...
121:    await refreshRemoteModels();                // <-- called from onMount
...
323:        onclick={refreshRemoteModels}           // <-- the explicit button

The issue's framing is explicit user action bypasses the cache. Mounting the Settings pane is not an explicit refresh action — it's a mount, structurally identical to the three mount-time call sites the issue names as the problem. As written, opening Settings unconditionally pays up to DISCOVERY_TIMEOUT (5s) with a spinner, every single time, even if the user opened Settings two seconds ago. That is a regression against acceptance criterion #3 for this pane.

The principle is least astonishment / intent-preserving parameterization: a function whose behavior is "bypass the cache" should not be reachable from a code path whose intent is "render initial state." Suggested fix — make the bypass a parameter of the call, not a property of the function:

async function refreshRemoteModels(forceRefresh = false) { ... await chatModelList(forceRefresh); ... }

// onMount:
await refreshRemoteModels();          // cache-friendly
// button:
onclick={() => refreshRemoteModels(true)}   // explicit bypass

Note the button's onclick={refreshRemoteModels} currently passes the DOM MouseEvent as the first argument, so a naive forceRefresh first param would be truthy-by-accident — the arrow wrapper above is required, not optional.

2. model-manager.svelte:191, 199 — config writes don't refresh the discovered list, which is the one case where the 30s TTL is user-visible as a bug.

saveConfig() and deleteConfig() write endpoint configs via saveOpenAiConfigs(...) and then call buildDefaultOptions(), but never re-run discovery. So after adding a new OpenAI-compat endpoint, "Available remote models" shows the pre-change result for up to 30 seconds unless the user manually hits refresh.

I want to be explicit that I agree with the author's decision to skip daemon-side invalidate-on-config-write. That reasoning is sound: SettingsServiceImpl is process-global while LocalAgentServiceImpl is built per-database in build_database_services (assembly.rs:191), they share no mutable state, and wiring an Arc through SharedContext plus 4 platform-gated main.rs call sites is real complexity for a 30-second window. YAGNI applies; that's the right call.

But the same user-visible outcome is available for ~2 lines at the layer that already knows a config just changed — the frontend. Adding await refreshRemoteModels(true); after each saveOpenAiConfigs(...) gets the invalidation-on-write behavior with none of the cross-service plumbing. This is the pragmatic middle path between the two options the issue listed, and it's worth taking. (Combined with finding #1, both changes land in the same function.)

3. local_agent_service.rs:1120-1137 — no single-flight; concurrent cold-start callers all stampede past the cache.

The lock is correctly released before the network call (good — no deadlock, no holding a tokio::sync::Mutex across .await on a 5s round trip), but that means the check and the fill are not atomic. The issue's own motivating scenario is three frontend call sites hitting ListModels on mount — and those fire concurrently (Promise.all in model-store.svelte.ts:171, agent-store.svelte.ts:150, ai-chat-model-selector.svelte:118, plus model-manager). On the very first chat open, with a cold cache, all of them miss and all of them run a full discovery round in parallel. The cache only helps from the second mount onward.

The docstring at line 1105 says the cache exists "so repeated ListModels calls (three frontend call sites hit it on mount) don't each re-pay the endpoint round trip" — which is precisely the case that is not covered.

This is not a correctness bug (the fan-out is already bounded and per-endpoint-degrading, and the last writer simply wins), so I'm not blocking on it. But the cost/benefit favors fixing it: the first chat open is the worst-case latency the issue was filed about, and the cheapest correct form is small. Either use a tokio::sync::Mutex held across the discovery (serializing cold callers, so the 2nd..Nth wait on the 1st rather than duplicating it), or store a shared Shared<BoxFuture> / broadcast handle. At minimum, if you decide to defer, the docstring should say the cache covers subsequent mounts, so it doesn't over-claim.

For contrast, InboundRelationshipCache (relationship_cache.rs) has the same benign race under RwLock and documents it as acceptable — so precedent supports deferring. Your call; just don't let the comment claim more than the code does.

🟢 Suggestions

4. local_agent_service.rs:3283-3290 — discovery_result_is_cached_for_subsequent_calls doesn't test what its name says.

The other three tests are genuinely well-constructed — I want to call that out, because the "seed a cache entry containing a fake model that discovery could never produce (zero endpoints configured)" trick makes cache-hit-vs-miss observable without HTTP mocking, and the comments explain exactly why the empty-daemon.toml baseline can't mask a bug. That's careful test design.

This fourth one is weaker. It asserts the cache is Some(_) after one call — i.e. that the cache was populated — but never makes the "subsequent call" the name promises, so it does not observe that the second call is served from the cache. Given tests 1 and 3 already cover the read paths, the unique value here is only "an empty result still populates the cache rather than leaving None". Either rename it to match (empty_discovery_result_still_populates_the_cache) or assert the timestamp is unchanged after a second call:

let first_fetched_at = { ...lock, unwrap, .0 };
let _ = svc.discover_openai_compat_models(false).await;
let second_fetched_at = { ...lock, unwrap, .0 };
assert_eq!(first_fetched_at, second_fetched_at, "second call must be served from cache, not re-discovered");

5. local_agent_service.rs:170-175 — consider a named type for the cache tuple.

Mutex<Option<(Instant, Vec<ModelInfo>)>> is a 6-line type expression at the field, and the tuple's .0/.1 are positional. A struct CachedDiscovery { fetched_at: Instant, models: Vec<ModelInfo> } would read better at both the field and the two access sites. Minor — the current form is legible and the doc comment carries the meaning.

Nit — dev-proxy.ts:653-654: the agentCall<{ forceRefresh: boolean }, ...> line runs ~105 chars and would be wrapped by the formatter. packages/dev-tools has no lint/format script and isn't in the quality:check pipeline, so nothing enforces it — purely cosmetic.


Verified Clean

  • All call sites covered. grep -rn "ListModelsRequest {}" packages --include="*.rs" returns nothing; all three remaining constructions (cli/src/commands/model.rs:47, chat_models.rs:69, local_agent.rs:321) set force_refresh explicitly. false is the right default for the CLI list and the unused list_local_models.
  • Lock safety. No .await while holding the guard: the read guard drops at the inner block's end (line 1129) before discover_openai_compat_models_uncached(), and the write guard is taken after. No deadlock, no lock held across the 5s network call. This is the part most likely to be gotten wrong, and it's right.
  • Staleness check. Instant::elapsed() is monotonic — correctly immune to wall-clock adjustment, which SystemTime would not be.
  • Proto change is additive. New bool force_refresh = 1 on a previously-empty message; proto3 default false preserves prior behavior for any non-updated client. Field number 1 on a fresh message has no reuse hazard.
  • Multi-database / tenant isolation. Not a leak. Discovery reads daemon.toml via load_openai_compat_configs (local_agent_service.rs:1147) — process-global endpoint config, not per-database data. The cache lives on a per-database LocalAgentServiceInner, so each instance caches independently from the same global source. No cross-database exposure, and no model data crosses a DB boundary.
  • Security. force_refresh is a reachability, not an authorization, concern: it only lets a local caller do what an uncached ListModels already did before this PR. The pre-existing fan-out bound (DISCOVERY_TIMEOUT, per-endpoint degradation) is unchanged, and the daemon surface is local. The TTL strictly reduces outbound request volume vs. main. No new risk.
  • Test-file fix. chat_model_list(state, None) in model_download_terminal_state_test.rs is the minimal correct adaptation.
  • Tests pass. 35/35 in the touched module, including all 4 new ones.
  • Scope discipline. No CLI flag added, no speculative abstraction, no backward-compat shims. Consistent with the repo's pre-release ethos and with YAGNI.

Recommendation

REQUEST CHANGES

The core daemon-side implementation is solid — correct lock discipline, monotonic staleness, complete end-to-end plumbing, genuinely good documentation, and three of four tests are thoughtfully constructed. The architectural judgment call on skipping cross-service invalidation is the right one and well-reasoned.

The blocker is narrow and frontend-side: refreshRemoteModels() now force-refreshes on mount (model-manager.svelte:121), which re-creates the per-mount stall that acceptance criterion #3 exists to eliminate. Findings #1 and #2 are a handful of lines in one function and together get you both the fix and true invalidate-on-config-write behavior — closing the last gap the issue raised without any of the daemon plumbing you correctly declined. Finding #3 (cold-start stampede) is a judgment call I'd accept either way, as long as the docstring doesn't over-claim. Finding #4 is a rename.

Happy to re-review once #1 and #2 are addressed.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

REQUEST CHANGES (posted as a comment — GitHub blocks formal change-requests on one's own PR). See the detailed review comment above. Blocker is narrow and frontend-side: refreshRemoteModels() now force-refreshes on mount (model-manager.svelte:121), re-creating the per-mount stall acceptance criterion #3 exists to eliminate. Daemon-side cache implementation is solid.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1860 (issue #1807)

Review Type: Initial Review

Requirements Check

  • ✅ Repeated ListModels calls within the TTL do not re-query endpoints. discover_openai_compat_models checks a Mutex<Option<(Instant, Vec<ModelInfo>)>> cache first and returns the cached clone if fetched_at.elapsed() < OPENAI_COMPAT_DISCOVERY_CACHE_TTL (30s) and force_refresh is false. Verified with a passing test (fresh_cache_entry_is_returned_without_requerying).
  • ✅ A newly available model still appears without an app restart; the mechanism is documented. Two paths: (1) TTL expiry after 30s, (2) explicit force_refresh via the Settings "Refresh remote models" button (model-manager.svelte:48, chatModelList(true)). The mechanism is documented in code comments across local_agent_service.rs, chat_models.rs, and tauri-commands.ts. Not written up in nodespace-docs/, but for a mechanism at this level of implementation detail that's consistent with how this codebase scopes that directory (architecture/decisions, not per-feature caching behavior) — acceptable.
  • ✅ A slow or dead endpoint does not stall the selector on every mount. All three known mount-time call sites (model-store.svelte.ts:171, agent-store.svelte.ts:150, ai-chat-model-selector.svelte:118) call chatModelList() with no argument, defaulting forceRefresh to false — they get cache hits on repeat mounts within the TTL window. Verified by reading each call site directly.

All three acceptance criteria are met.

Code Review Findings

🟡 Important: Cache invalidation option was dismissed without the cheapest version being considered

📁 packages/daemon/src/services/local_agent_service.rs (design rationale, not a specific line)

The PR's own reference pattern, InboundRelationshipCache (packages/core/src/services/relationship_cache.rs), doesn't only do TTL — it's an explicit hybrid of TTL and event-driven invalidation via a single AtomicBool (schema_change_flag) plus a public invalidate() method (relationship_cache.rs:171-174). That invalidation hook is cheap: no Arc wiring across services, no shared mutable state, no changes to main.rs's platform-gated bootstrap — just self.schema_change_flag.store(true, Ordering::Release) called from whatever code path already knows a schema changed.

The author's stated reason for skipping config-write invalidation is that SettingsServiceImpl and LocalAgentServiceImpl are constructed in different scopes in assembly.rs and don't share state, and wiring a shared Arc would mean touching 4 platform-gated call sites in main.rs. That's true for a shared cache object, but it's not what the reference pattern requires — an AtomicBool (or even nothing at all, since 30s TTL + explicit button already meet the acceptance criteria) doesn't need bidirectional service wiring the way the write-up frames it. This isn't a blocker: the 3 acceptance criteria are satisfied as written by TTL + force_refresh alone, and the issue explicitly lists "TTL alone" as one of the acceptable options. But the tradeoff writeup overstates the wiring cost relative to the pattern it cites as precedent, and a future author reading this code side-by-side with relationship_cache.rs may reasonably ask why one cache in this codebase got event-driven invalidation and the sibling didn't, for the same class of "config changed underneath a cache" problem. Recommend either: (a) leave as-is since it meets criteria, or (b) if picked up again, note in the code comment that event-driven invalidation was considered and explicitly deferred as YAGNI rather than "too costly to wire," since the actual cost is much lower than described.

Engineering principle: when a comparison pattern is explicitly named as the design reference, the tradeoff analysis should engage with what that pattern actually does, not a more expensive version of it.

🟡 Important: Thundering herd on concurrent cache miss

📁 packages/daemon/src/services/local_agent_service.rs:1120-1138

discover_openai_compat_models has no single-flight/in-flight-request de-duplication. If two callers race a cache miss simultaneously (e.g. the three frontend mount call sites arriving within the same tick on a cold cache), both will independently observe a stale/absent cache, both drop the lock, and both run their own discover_openai_compat_models_uncached() round — i.e. two full concurrent endpoint fan-outs instead of one caller waiting on the other's in-flight result. This is the same property as the InboundRelationshipCache reference pattern (it has the identical gap in refresh_cache/needs_refresh), so it's not a regression relative to precedent, and the cold-start window is narrow (first mount only, self-heals for all subsequent calls once either round completes and populates the cache). Not a blocker given the precedent and narrow blast radius, but worth a one-line comment noting it's a known, accepted gap rather than an oversight, so a future reader doesn't "fix" it inconsistently from the sibling cache.

Engineering principle: an accepted tradeoff that isn't called out in a comment reads as an oversight to the next reader; a short note prevents redundant re-litigation.

🟢 Suggestion: list_models gRPC handler's force_refresh extraction is untested at the handler level

📁 packages/daemon/src/services/local_agent_service.rs:929-942

All 4 new tests call discover_openai_compat_models(bool) directly; none exercise the actual list_models gRPC method to confirm request.into_inner().force_refresh is correctly threaded from the wire type into the call. The line itself (let force_refresh = request.into_inner().force_refresh;) is low-risk, but it's the one piece of this feature that's genuinely only covered by manual/integration testing right now. A 5th test constructing a Request<ListModelsRequest> with force_refresh: true against a seeded cache and asserting the handler bypasses it would close that gap cheaply and catch a future refactor that silently drops the field.

🟢 Suggestion: Cache is duplicated per open database instance

📁 packages/daemon/src/services/assembly.rs:191, packages/daemon/src/services/local_agent_service.rs

LocalAgentServiceImpl::new runs once per build_database_services call (per ADR-053's multi-database model), so each open database gets its own independent openai_compat_discovery_cache, even though OpenAI-compat endpoint configuration is process-wide, not per-database. This means N open databases each independently discover and cache the same endpoint set — harmless (no cross-database leakage; each cache is correctly scoped to its own instance, so there's no security/correctness issue), just a small amount of redundant network chatter on cold start across databases. Out of scope for this issue; flagging only so it's a known, not-hidden characteristic if multi-database use becomes more common.

🟢 Nit: proto field numbering

📁 packages/proto/proto/local_agent_service.proto

bool force_refresh = 1; on a previously-empty message is correct and additive/non-breaking (default false matches every prior implicit-empty-request caller's behavior). No concerns — flagging only to confirm this was explicitly checked: default false preserves old semantics for anything encoding an old empty ListModelsRequest{}, so this is wire-compatible.

Call-site audit (verification, not just trust in the summary)

  • grep -rn "ListModelsRequest {}" packages --include="*.rs" → empty, confirmed no stale zero-arg constructions remain.
  • grep -rn "ListModelsRequest {" packages --include="*.rs" → exactly 3 sites (cli/src/commands/model.rs, chat_models.rs, local_agent.rs), all explicitly set force_refresh.
  • grep -rn "chatModelList(" packages --include="*.ts" --include="*.svelte" → all mount-time call sites (model-store.svelte.ts, agent-store.svelte.ts, ai-chat-model-selector.svelte) correctly omit the argument (cache-hit default); only model-manager.svelte's explicit refresh button passes true.
  • dev-proxy.ts's browser-mode path correctly parses ?force_refresh=true and defaults to false otherwise, matching the Tauri path's default.
  • Mutex lock in discover_openai_compat_models is correctly scoped ({ } block) and dropped before the network round trip — no lock held across .await on the slow path, so no deadlock risk and no blocking of concurrent cache-hit readers during a slow discovery round.
  • cargo build --workspace succeeds; cargo test -p nodespace-daemon --lib local_agent_service:: passes all 35 tests including the 4 new ones; bun run --cwd packages/desktop-app test -- tauri-commands passes 9/9.

Recommendation

APPROVE

This is a clean, well-scoped fix for the issue as filed. All three acceptance criteria are met and independently verified against the actual diff and call sites (not just the author's summary). The Mutex-based cache is correctly structured — no lock held across the network await, no deadlock potential, staleness check is correct. The force_refresh plumbing is complete and consistent end-to-end (proto → gRPC handler → Tauri commands → frontend → dev-proxy), with no missed call sites. Tests are meaningful, not tautological — each specifically defeats a possible bug (e.g. fresh_cache_entry_is_returned_without_requerying seeds a distinguishable fake model so a false cache-hit can't hide behind an empty-endpoints coincidence). The two 🟡 Important findings above are worth a follow-up conversation (ideally as inline replies here, not a blocking change) but don't undermine the correctness or the acceptance-criteria coverage of this PR — they're about consistency with a cited reference pattern and a narrow, precedented cold-start race, not bugs introduced by this change.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review recommendation: APPROVE (GitHub disallows self-approval on this PR's author account, so recording the verdict here instead of via --approve). See the full review comment above for the complete report. All 3 acceptance criteria from issue #1807 are met and independently verified; cache logic is correct (no lock held across the network await, staleness check correct, force_refresh plumbing complete end-to-end across proto/daemon/Tauri/frontend/dev-proxy); tests are meaningful, not tautological. Two Important (non-blocking) notes: (1) the cache-invalidation tradeoff writeup overstates the cost of the InboundRelationshipCache-style event-driven invalidation it cites as precedent — worth a comment noting it was deferred as YAGNI rather than 'too costly to wire'; (2) no single-flight guard on concurrent cache-miss (thundering herd), same gap as the precedent pattern, narrow blast radius, worth a one-line comment marking it as accepted rather than an oversight.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my review above (Approve → Request Changes)

I need to retract my "APPROVE" recommendation. On re-checking after seeing another review pass on this PR flag the same thing, I verified directly and confirmed a real bug I missed the first time.

🔴 Critical: model-manager.svelte force-refreshes on every Settings mount, reproducing the exact stall this PR fixes

📁 packages/desktop-app/src/lib/components/settings/model-manager.svelte:42-48, 101-121

refreshRemoteModels() unconditionally calls chatModelList(true) (line 48) — always force_refresh: true. That function is called from two places:

  • Line 121: onMount(async () => { ... await refreshRemoteModels(); }) — runs on every mount of the Settings pane.
  • Line 323: onclick={refreshRemoteModels} — the explicit "Refresh remote models" button.

Because the same function is shared and hardcodes force_refresh: true, opening Settings bypasses the 30s cache and re-queries every configured OpenAI-compatible endpoint live, every time, exactly the stall-on-every-mount behavior issue #1807 exists to eliminate — just relocated from the chat model selector to the Settings pane instead of removed. This directly fails acceptance criterion #3 ("A slow or dead endpoint does not stall the selector on every mount") for this call site, even though the other three mount-time call sites (model-store, agent-store, ai-chat-model-selector) correctly default to a cache hit.

Fix: give refreshRemoteModels a parameter (e.g. refreshRemoteModels(forceRefresh = false)), pass false from the onMount call at line 121 (a normal cache-respecting load, consistent with every other mount site) and true only from the button's onclick at line 323 — the only place where "explicit user action bypasses cache" is actually true.

Engineering principle: a shared function whose name and internal comment claim "explicit user-triggered refresh" was silently made to run on component mount too, without updating the comment or callers to reflect that it's no longer only user-triggered. When a function's contract changes because it grew a second caller, the function's behavior needs to be parameterized per-caller, not left hardcoded to serve the caller that came first.

Revised Recommendation: REQUEST CHANGES

The core daemon-side cache implementation, proto/Tauri/frontend plumbing, and tests are all sound and remain as assessed in my first comment. But this one call site is a real, verifiable defect that fails one of the three acceptance criteria for the Settings surface. It's a small, well-scoped fix (one parameter, one call-site change) — not an architectural problem — so this should be quick to address and does not call the rest of the design into question.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

REVISED review recommendation: REQUEST CHANGES (posted as a comment -- GitHub blocks formal review states on one's own PR). Retracting my earlier APPROVE; see the correction comment above. Verified a real bug: model-manager.svelte's onMount calls refreshRemoteModels(), which unconditionally passes force_refresh:true, so opening Settings bypasses the cache and re-queries every endpoint live on every mount -- reproducing the exact stall issue #1807 exists to fix, for this one surface (fails acceptance criterion #3 for this call site). Fix is small: parameterize refreshRemoteModels(forceRefresh = false), pass true only from the button's onclick at line 323. Everything else in the PR (daemon cache logic, proto/Tauri/frontend plumbing, tests) remains sound per my first comment.

…, strengthen cache test

- Fixed model-manager.svelte's refreshRemoteModels() unconditionally passing
  force_refresh: true — it was called from onMount, reintroducing the
  per-mount stall this issue exists to fix for the Settings pane. Now
  parameterized (forceRefresh = false), with onMount passing false and the
  explicit "Refresh remote models" button passing true.
- saveConfig()/deleteConfig() now call refreshRemoteModels(true) after
  writing, so editing/removing an endpoint config is reflected immediately
  instead of waiting out the 30s TTL.
- Strengthened discovery_result_is_cached_for_subsequent_calls to assert the
  cache's fetch timestamp is unchanged across a second call, so it actually
  verifies "subsequent calls are served from cache" rather than only that
  the cache gets populated once.
- Documented two accepted tradeoffs raised in review as deferred-not-missed:
  no event-driven cache invalidation (Settings' force_refresh(true) after a
  config write already covers it without cross-service wiring), and no
  single-flight de-dup on a concurrent cache miss (same accepted gap as
  InboundRelationshipCache's refresh_cache, narrow blast radius).

Addresses reviewer recommendations from the pragmatic-code-review on PR #1860
(🔴 critical mount-time bug, 🟡 config-write refresh, 🟢 test tautology).
Skipped: gRPC-handler-level test for force_refresh extraction (marginal value,
single field read with no branching) and a named struct for the cache tuple
(documented, used in exactly two places) — both style/coverage polish beyond
this PR's scope.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review — commit 6ae387a

Addressed the findings from both review passes (both converged on the same critical bug independently).

✅ Addressed

🔴 Critical — mount-time force-refresh in model-manager.svelte. refreshRemoteModels() unconditionally passed force_refresh: true, and was called from onMount as well as the explicit button — so every Settings-pane mount bypassed the cache and re-queried every endpoint live, reintroducing the exact stall acceptance criterion #3 exists to eliminate. Fixed: refreshRemoteModels(forceRefresh = false), onMount passes false (cache-friendly), the "Refresh remote models" button passes true via an arrow wrapper (onclick={() => refreshRemoteModels(true)} — needed since the bare function reference would otherwise receive the click's MouseEvent as forceRefresh).

🟡 Important — config writes don't refresh the discovered list. saveConfig() and deleteConfig() now call await refreshRemoteModels(true) after writing, so adding/editing/removing an OpenAI-compat endpoint is reflected immediately instead of waiting out the 30s TTL. This gets the practical effect of invalidate-on-config-write with zero cross-service wiring, addressing both reviews' note that this was the pragmatic middle path.

🟢 Suggestion — tautological test. discovery_result_is_cached_for_subsequent_calls only asserted the cache became Some(_), never that a second call was actually served from it. Strengthened to assert the cache's fetch Instant is unchanged across a second call — if the second call had re-run discovery, the timestamp would differ.

⏭️ Skipped (with reasoning)

🟡 Important — cache-invalidation design tradeoff writeup. Both reviews agreed the underlying decision (TTL-only, no Arc wiring across SettingsServiceImpl/LocalAgentServiceImpl) is sound, just that my writeup overstated the cost relative to InboundRelationshipCache's cheap AtomicBool approach. Rather than add that machinery, I tightened the code comment on OPENAI_COMPAT_DISCOVERY_CACHE_TTL to state explicitly that this was deferred as YAGNI — because the frontend's new refreshRemoteModels(true)-after-config-write (above) already covers the one path that writes this cache's source data — not ruled out, and revisit if a second writer appears.

🟡 Important — no single-flight de-dup on concurrent cache miss (thundering herd). Both reviews explicitly called this a narrow, precedented gap (same property as InboundRelationshipCache::refresh_cache) and not a blocker. Added a comment on discover_openai_compat_models marking it as an accepted tradeoff — self-heals after the first round completes — rather than adding single-flight/broadcast machinery, which would be scope creep for this issue.

🟢 Suggestion — gRPC-handler-level test for force_refresh extraction. The line (request.into_inner().force_refresh) is a single field read with no branching; the existing 4 tests already exercise the branching logic directly. Marginal coverage value for the added surface.

🟢 Suggestion — named struct instead of the cache tuple. Mutex<Option<(Instant, Vec<ModelInfo>)>> is used in exactly two places, both documented. Not worth the abstraction for this PR.

Verification

  • cargo test -p nodespace-daemon --lib -- services::local_agent_service — 35/35 passing (incl. strengthened test)
  • bun run test — 171/171 files, 4113/4113 tests
  • bun run quality:fix — clean (ESLint, tsc, cargo fmt, cargo clippy -D warnings)
  • Pre-push gate (test:all + workspace build) — passed, pushed as 6ae387a5

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: The critical finding was a real functional bug in a code path both reviews independently flagged, and the fix changes call-site behavior (mount vs. explicit-refresh semantics) — worth a second pass to confirm the fix is complete and didn't introduce a new gap (e.g. double-checking the button's arrow-wrapper doesn't regress to passing the event object).

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review — commit 6ae387a

Review Type: Re-Review (delta since 522f8d1a, the commit both prior review passes were against)

Previous Review Summary

  • Number of previous recommendations: 1 Critical + 2 Important + 3 Suggestions (both independent review passes converged on the same set)
  • Addressed: 6 / 6 (Critical fixed; both Important items resolved — one via code change, one via an honest deferral comment; all 3 Suggestions actioned or explicitly declined with reasoning)
  • Not addressed: 0
  • New issues found: 0

Verification of the Critical fix

📁 packages/desktop-app/src/lib/components/settings/model-manager.svelte

Confirmed by reading the full current file, not just the diff:

  • refreshRemoteModels(forceRefresh = false) (line 42) now takes the parameter; chatModelList(forceRefresh) is passed through correctly (matches chatModelList(forceRefresh = false) in tauri-commands.ts).
  • onMount (line 118) calls await refreshRemoteModels(); — no argument, defaults to false. Mount now respects the daemon's 30s discovery cache, which is the whole point of acceptance criterion Desktop shell with resizable panels #3.
  • The "Refresh remote models" button (line 326) uses onclick={() => refreshRemoteModels(true)} — the arrow-wrapper is present, so the DOM MouseEvent is never passed as forceRefresh (a bare onclick={refreshRemoteModels} here would have been truthy-always and silently reintroduced the bug in a different shape). This was exactly the failure mode I flagged checking for — verified absent.
  • saveConfig() (line 195) and deleteConfig() (line 206) both now call await refreshRemoteModels(true) after saveOpenAiConfigs/persisting the delete — a config write is reflected immediately rather than waiting out the TTL, addressing the Important cache-invalidation note pragmatically (no cross-service Arc wiring needed).

This is a complete, correct fix. All three call sites now have the semantics the issue requires: passive mount (cache-friendly), explicit user refresh (bypass), and config write (bypass, since the source data changed).

Verification of the strengthened test

📁 packages/daemon/src/services/local_agent_service.rs:3298-3332

discovery_result_is_cached_for_subsequent_calls previously only asserted cache.is_some() after one call — true whether or not the second call actually hit the cache (tautological, as flagged). The rewrite now:

  • captures first_fetched_at (the cached Instant) after call 1
  • makes a second call to discover_openai_compat_models(false)
  • captures second_fetched_at and asserts equality

Verified the cache field really is Mutex<Option<(Instant, Vec<ModelInfo>)>> (local_agent_service.rs:183-188), so .0 is the fetch timestamp — a regression that caused the second call to re-run discovery would produce a new Instant::now() and fail this assertion. This is now a real behavioral test, not a structural one.

Ran the full module: cargo test -p nodespace-daemon --lib -- services::local_agent_service → 35/35 passed, including this test and force_refresh_bypasses_a_fresh_cache_entry / stale_cache_entry_triggers_a_fresh_discovery_round / fresh_cache_entry_is_returned_without_requerying, which together cover the three TTL states end to end.

Also ran packages/desktop-app/src/tests/components/model-manager-selection.test.ts (6/6 passed) — no regression in the adjacent selection-encoding logic (this file doesn't cover the refresh call sites directly, which is a minor gap but not a blocker given the fix is a straightforward, directly-verified call-site change).

Judgment on the two new code comments

📁 local_agent_service.rs:113-122 (YAGNI note on OPENAI_COMPAT_DISCOVERY_CACHE_TTL) and :1132-1139 (thundering-herd note on discover_openai_compat_models)

Both comments make specific, checkable claims about InboundRelationshipCache (packages/core/src/services/relationship_cache.rs). I verified both:

  • The YAGNI comment claims InboundRelationshipCache solves the same cache-vs-config-write problem with a single AtomicBool schema_change_flag. Confirmed: relationship_cache.rs:78,174,188,243 — an Arc<AtomicBool> set on write and checked/cleared on refresh, exactly as described.
  • The thundering-herd comment claims the same "lock released before the network round trip, so concurrent misses each redo discovery" gap exists in InboundRelationshipCache::refresh_cache. Confirmed: refresh_cache (relationship_cache.rs:201-243) awaits self.store.get_all_schemas() with no lock held, then takes the write lock only to swap in the result — identical shape to discover_openai_compat_models's lock-release-then-fetch pattern.

Both comments are accurate, not overclaiming. They correctly scope the deferral: "revisit if a second config writer appears that can't reach for the same frontend hook" is an honest, falsifiable condition rather than a vague "future work" wave-off.

New issues introduced by this commit

None found. The two call sites added (saveConfig/deleteConfig forcing a refresh) each independently lock/unlock the discovery-cache mutex — worst case under rapid successive saves is redundant network fan-out, not corruption or deadlock, which is the same accepted tradeoff already documented for the button and consistent with discover_openai_compat_models_uncached's per-endpoint JoinSet (a slow/dead endpoint still can't block the others, per its own doc comment).

Recommendation: APPROVE

The critical bug is fixed correctly and completely, verified by direct code reading (not just trusting the diff) against exactly the failure mode both prior reviews and my own instructions called out (arrow-wrapper vs. bare function reference). The test strengthening is genuine — it would now catch a cache-bypass regression. The two deferred Important items are honestly and accurately documented as accepted tradeoffs with a concrete revisit condition, not swept under the rug. No new issues introduced by the fix commit.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review recommendation: APPROVE (GitHub disallows self-approval on this PR's author account, so recording the verdict here instead of via --approve). See the detailed re-review comment above for full verification: critical bug fixed and verified by direct code reading against the exact failure mode flagged (arrow-wrapper vs bare function ref), strengthened cache test genuinely distinguishes cache-hit from cache-populate (35/35 daemon tests pass), deferred Important items honestly documented as accepted tradeoffs with concrete revisit conditions, no new issues introduced by commit 6ae387a.

@malibio
malibio merged commit a1d6295 into main Jul 31, 2026
2 checks passed
@malibio
malibio deleted the issue-1807-model-cache branch July 31, 2026 21:45
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.

ListModels inherits remote-endpoint latency: no caching on the catalog read path

1 participant