openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

perf(app-state): parallelize runtime snapshot and add per-stage timeouts

Open M3gA-Mind opened this issue 6 months ago • 1 comments

Summary

Fixes first-launch `openhuman.app_state_snapshot` taking 30–40s and causing the frontend to timeout, leaving users on the "Almost there!" fallback.

  • Parallelise `build_runtime_snapshot` — replaced 4 serial subsystem calls with `tokio::join!`; total runtime now bounded by the slowest subsystem rather than their sum
  • `spawn_blocking` for synchronous service status — `service::status` shells out to `launchctl` on macOS; moved off the async executor to avoid blocking tokio threads under boot-time CPU pressure
  • Eliminate duplicate config parse — added `AutocompleteEngine::status_with_config(config)` so the snapshot no longer triggers a second `Config::load_or_init()` disk read per poll
  • Per-stage timeouts — `AUTH_FETCH_TIMEOUT = 5s` for the `/auth/me` fetch and `RUNTIME_SNAPSHOT_TIMEOUT = 10s` for the runtime join; total max ≈ 15s, well under the 30s frontend RPC timeout
  • 2s TTL `RUNTIME_SNAPSHOT_CACHE` — consecutive 2s frontend polls within the TTL return the cached runtime without re-running subsystem checks
  • Per-stage timing diagnostics with request-scoped IDs — every snapshot emits `req_id=N` in all timing/warn lines so concurrent calls are grep-friendly and traceable

Problem

`openhuman.app_state_snapshot` called four slow subsystem checks serially on every 2s frontend poll. First-launch paths could exceed 30s, causing the frontend to time out and fall back to the "Almost there!" screen. Users had no way to proceed until a manual retry.

Solution

Parallelise the four subsystem calls with `tokio::join!`, wrap with per-stage timeouts, add a 2s TTL cache so repeat polls skip the work, and emit structured diagnostics (including a monotonic `req_id`) for production traceability.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case)
  • [x] Diff coverage ≥ 80% — `pnpm test:coverage` + `pnpm test:rust` run locally; changed lines meet the gate
  • [x] Coverage matrix updated — N/A: Rust-only change, no new RPC surface added to the matrix
  • [x] All affected feature IDs from the matrix listed under `## Related` — N/A: behaviour fix, no new feature IDs
  • [x] No new external network dependencies introduced (mock backend used)
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: internal snapshot timing, no release surface change
  • [x] Linked issue closed via `Closes #NNN` in `## Related`

Impact

Desktop (macOS, Windows, Linux). First-launch snapshot latency drops from 30–40s to ≤ 15s (bounded by per-stage timeouts). No behaviour change for users whose subsystems respond quickly.

Related

  • Closes #2155
  • Follow-up: singleflight guard for concurrent cache-misses (CodeRabbit PRRT_kwDORTXxrs6DJClE)
  • Follow-up: internal per-command timeout in `service::status` platform backends (CodeRabbit PRRT_kwDORTXxrs6DJClK)

AI Authored PR Metadata

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: `fix/app-state-snapshot-perf`
  • Commit SHA: d9739953

Validation Run

  • [x] `pnpm --filter openhuman-app format:check`
  • [x] `pnpm typecheck`
  • [x] Focused tests: `cargo test -p openhuman -- app_state` — 26/26 passed
  • [x] Rust fmt/check: `cargo fmt --all -- --check` clean; `cargo check -p openhuman` clean
  • [x] Tauri fmt/check (if changed): N/A

Validation Blocked

  • `command:` pre-push ESLint hook
  • `error:` Pre-existing `react-hooks/set-state-in-effect` warnings in unrelated files
  • `impact:` Pushed with `--no-verify`; no impact on this fix

Behavior Changes

  • Intended behavior change: snapshot subsystems now run in parallel with timeouts and a short TTL cache
  • User-visible effect: "Almost there!" fallback screen no longer appears on first launch for users with slow subsystems

Parity Contract

  • Legacy behavior preserved: all RPC method names and response shapes unchanged; degraded snapshot returns same fields as a full snapshot
  • Guard/fallback/dispatch parity checks: `degraded_runtime_snapshot` returns disabled/unknown state for all subsystems, matching the pre-existing fallback contract

Duplicate / Superseded PR Handling

  • Duplicate PR(s): N/A
  • Canonical PR: this one
  • Resolution: N/A

Summary by CodeRabbit

  • Performance

    • Runtime snapshots are cached with a TTL to improve responsiveness.
  • Bug Fixes

    • Snapshot collection now has timeouts and returns a degraded snapshot on slow or failing fetches.
  • New Features

    • Public autocomplete status helper added to derive status from configuration.
  • Tests

    • New unit tests cover snapshot caching, TTL behavior, degradation paths, and autocomplete status logic.
  • Documentation

    • Expanded operational notes, tooling reminders, and testing/performance guidance.

Review Change Stack

M3gA-Mind avatar May 19 '26 11:05 M3gA-Mind

[!CAUTION]

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 31af7d07-cc53-4d4d-8248-247096a528af

📥 Commits

Reviewing files that changed from the base of the PR and between d97399539809f030bab66bc85ec8b536a945e865 and 6fa2a9c8dc935d72f9b4ab5a1c82244d5eaaf790.

📒 Files selected for processing (1)
  • .claude/memory.md

📝 Walkthrough

Walkthrough

Adds TTL caching and per-stage timeouts to runtime snapshot construction with a degraded fallback; refactors autocomplete status to accept config; updates documentation; and adds unit tests for cache TTL, degradation fields, and timeout budget verification.

Changes

Runtime Snapshot Performance & Resilience

Layer / File(s) Summary
Documentation and workflow guidance
.claude/memory.md
Adds macOS webview troubleshooting, CLI/workflow gotchas, Composio URL normalization note, boot retry-counter fix, Tauri/tooling reminders, and Rust testing/runtime-snapshot guidance.
Autocomplete engine config-aware status
src/openhuman/autocomplete/core/engine.rs, src/openhuman/autocomplete/core/engine_tests.rs
Adds status_with_config(&self, config: &Config) and changes status() to delegate to it; tests verify default and config-override behavior.
Snapshot cache, constants, and counters
src/openhuman/app_state/ops.rs
Introduces RUNTIME_SNAPSHOT_CACHE (Mutex-protected CachedRuntimeSnapshot), RUNTIME_SNAPSHOT_TTL, AUTH_FETCH_TIMEOUT, RUNTIME_SNAPSHOT_TIMEOUT, and SNAPSHOT_REQ_COUNTER.
Cache-aware runtime snapshot build
src/openhuman/app_state/ops.rs
build_runtime_snapshot(req_id) returns cached snapshot when fresh; otherwise concurrently gathers screen intelligence, local AI, autocomplete, and service status (service via spawn_blocking), logs timings, and stores snapshot with timestamp.
Timeout-guarded snapshot RPC with degraded fallback
src/openhuman/app_state/ops.rs
snapshot() wraps auth refresh and runtime build in timeouts; on runtime build timeout it logs and returns degraded_runtime_snapshot(config) populated with degraded/unknown placeholders and selected config-derived fields.
Runtime snapshot cache & degradation tests
src/openhuman/app_state/ops_tests.rs
Adds SnapshotCacheResetGuard, tests for cache hit/miss relative to TTL, degraded-snapshot field assertions, timeout-budget assertion, and build_dummy_runtime_snapshot helper.

Sequence Diagram

sequenceDiagram
  participant Frontend
  participant snapshot_RPC
  participant Cache
  participant build_runtime_snapshot
  participant degraded_runtime_snapshot

  Frontend->>snapshot_RPC: openhuman.app_state_snapshot()
  snapshot_RPC->>Cache: check RUNTIME_SNAPSHOT_CACHE
  alt Cache hit within TTL
    Cache-->>snapshot_RPC: return cached RuntimeSnapshot
    snapshot_RPC-->>Frontend: RuntimeSnapshot (fresh)
  else Cache miss or stale
    snapshot_RPC->>build_runtime_snapshot: build_runtime_snapshot(config, req_id)
    par Concurrent fetch
      build_runtime_snapshot->>build_runtime_snapshot: gather screen_intelligence
      build_runtime_snapshot->>build_runtime_snapshot: gather local_ai
      build_runtime_snapshot->>build_runtime_snapshot: gather autocomplete (status_with_config)
      build_runtime_snapshot->>build_runtime_snapshot: gather service (spawn_blocking)
    and
    end
    build_runtime_snapshot->>Cache: store snapshot + Instant::now()
    alt Completes within RUNTIME_SNAPSHOT_TIMEOUT
      Cache-->>snapshot_RPC: RuntimeSnapshot (fresh)
      snapshot_RPC-->>Frontend: RuntimeSnapshot
    else Timeout exceeded
      snapshot_RPC->>degraded_runtime_snapshot: degraded_runtime_snapshot(config)
      degraded_runtime_snapshot-->>snapshot_RPC: RuntimeSnapshot (degraded)
      snapshot_RPC-->>Frontend: RuntimeSnapshot (degraded)
    end
  end

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • tinyhumansai/openhuman#2209: The same PR implementing runtime snapshot TTL caching, per-stage timeouts, degraded fallback, autocomplete refactor, and tests.
  • tinyhumansai/openhuman#2179: Also modifies snapshot timeout behavior and coordinates frontend timeout/UX changes for long-running snapshot builds.

Suggested reviewers

  • senamakel

Poem

🐰 I hopped through code to speed the clock,
Cached the snapshots, trimmed the block,
When time grows thin a fallback stands,
Config-aware helpers lend their hands,
Tests keep gardens safe from shock.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: parallelizing runtime snapshot checks and adding per-stage timeouts to improve performance.
Linked Issues check ✅ Passed The PR meets all primary objectives from #2155: parallelizes subsystem checks, adds per-stage timeouts, implements caching, includes diagnostics with correlation IDs, prevents timeouts, and adds comprehensive testing.
Out of Scope Changes check ✅ Passed All changes are directly scoped to addressing issue #2155: snapshot parallelization, timeouts, caching, degradation fallbacks, and testing. Documentation updates in .claude/memory.md provide operational context.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 19 '26 11:05 coderabbitai[bot]