Repository navigation
fix(backend): keep execute_tool off the event loop - #10601
Conversation
`POST /v1/agent/execute-tool` is `async def`, but ran two blocking calls directly on the event loop: - `load_app_tools(uid)` — a Redis read plus one Firestore document read per enabled app - `target.invoke(params, config=config)` — every `CORE_TOOLS` entry is a sync `@tool` that fans out to Firestore/Pinecone, and `get_conversations_tool` accepts `limit` up to 5000 One agent VM calling this endpoint parked the whole backend event loop for the duration of that scan: every other connection, `/health`, and the HPA metrics endpoint froze with it. The canonical path one file over already does both correctly (`utils/retrieval/agentic.py:707` and `:331`); this router was the drift. Both calls now go through `run_blocking(db_executor, ...)`, which copies the current context so `agent_config_context` still resolves inside the worker thread. `scan_async_blockers.py` does not catch this — its DB detector is import-aware over `database.*` names, and neither `load_app_tools` nor `t.invoke` is one. Also stops echoing raw exception text: pydantic renders `input_value=<...>`, so a ValidationError from caller-supplied params wrote user content verbatim into backend logs and returned it over the wire. The log line now carries `error_type` only and the response is routed through `sanitize`, matching this file's existing GCE-body handling. Verification: see the regression test in the following commit — 3.01s blocked before, 0.08s after.
Behavioral, not a static tripwire: a sync tool blocks inside `invoke` while the test coroutine tries to regain control. If the tool runs on the loop it cannot, and the elapsed time records the full block. The shared fixture stubs `run_blocking` to call `fn()` inline, which would erase the seam under test, so this case restores a real ThreadPoolExecutor offload (including the contextvar copy `agent_config_context` depends on). Confirmed to fail on the unfixed router: `assert 3.006059459061362 < 1.0`. With the fix the whole file runs in 0.08s.
…nvoke This guard pins that preserve_chat_memory_tool_result_boundary runs between the tool invoke and the return. It anchors on the literal source line, so moving the invoke onto run_blocking broke the substring lookup with 'ValueError: substring not found' while the ordering it checks was unchanged. Retargets the anchor only; the assertion and its intent are identical.
Failure-Class: none Verification: 18 focused backend tests passed
Git-on-my-level
left a comment
There was a problem hiding this comment.
Reviewed and approved. This correctly moves the two blocking calls in POST /v1/agent/execute-tool (load_app_tools and target.invoke) onto db_executor via run_blocking, matching the canonical path already used in utils/retrieval/agentic.py. The contextvar copy in run_blocking keeps agent_config_context resolving in the worker thread, and app tools with a coroutine still take the async path (no double-offload).
The exception-text hardening is a good catch: pydantic renders input_value=..., so a ValidationError could previously echo caller-supplied content into logs and the HTTP 200 body. Logging error_type only and returning a fixed category is the right call.
Verified: synced the backend venv and ran the touched suites locally — test_tools_agent_route_response_shape.py (incl. the new event-loop-blocking and exception-sanitization cases) and test_chat_memory_tool_caller.py all pass, plus test_agent_vm_async.py and test_agent_tool_geolocation_async.py (18 total).
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
kodjima33
left a comment
There was a problem hiding this comment.
Backend bug fix: /v1/agent/execute-tool ran blocking Firestore/Pinecone work on the event loop; now routed through run_blocking like the canonical agentic.py path, with a behavioral regression test.
…ements Seven conflicts, all semantic — #10599/#10600/#10601 landed on main while this branch was in review, and they touch the same files. - agent-proxy/main.py: keeps this branch's restart circuit-breaker (the restart_failed/restart_succeeded fields) AND main's usable-IP guards. Both are needed: the breaker stops hammering GCE, the guard stops persisting a placeholder address as ready. - routers/agent_tools.py: takes main's executor offload and bounded error logging, and keeps this branch's record_fallback on the degraded-toolset path — AGENTS.md requires it on a fail-open branch and main has no equivalent. - routers/integrations.py: the registry supersedes the inline OAUTH_CONFIGS / AUTH_PROVIDERS tables (neither is referenced elsewhere in the file), but GMAIL_READONLY_SCOPE, GOOGLE_INTEGRATION_KEY and google_integration_has_scope each still have a live caller, so their import is kept. - agent-cloud/agent.mjs: main fixed the /sync row-schema data loss (#10602) by grouping rows by column set; this branch added a SQL-identifier guard on the interpolated column names. Kept both — the guard now runs against the union of every row's columns, which is a superset of the old rows[0] check. - utils/llm/app_generator.py: took main's deletion of _generate_app_icon_via_openai. It has no callers and main removed it deliberately in "enforce gateway-only LLM routing" (bbbdf3b). - chat-hermetic.yaml: union of both covers lists. - desktop-swift-providers.json: line-count baseline, regenerated below.
…andling (#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge #10600, #10601, and #10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
…andling (#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge #10600, #10601, and #10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
…ements Seven conflicts, all semantic — BasedHardware#10599/BasedHardware#10600/BasedHardware#10601 landed on main while this branch was in review, and they touch the same files. - agent-proxy/main.py: keeps this branch's restart circuit-breaker (the restart_failed/restart_succeeded fields) AND main's usable-IP guards. Both are needed: the breaker stops hammering GCE, the guard stops persisting a placeholder address as ready. - routers/agent_tools.py: takes main's executor offload and bounded error logging, and keeps this branch's record_fallback on the degraded-toolset path — AGENTS.md requires it on a fail-open branch and main has no equivalent. - routers/integrations.py: the registry supersedes the inline OAUTH_CONFIGS / AUTH_PROVIDERS tables (neither is referenced elsewhere in the file), but GMAIL_READONLY_SCOPE, GOOGLE_INTEGRATION_KEY and google_integration_has_scope each still have a live caller, so their import is kept. - agent-cloud/agent.mjs: main fixed the /sync row-schema data loss (BasedHardware#10602) by grouping rows by column set; this branch added a SQL-identifier guard on the interpolated column names. Kept both — the guard now runs against the union of every row's columns, which is a superset of the old rows[0] check. - utils/llm/app_generator.py: took main's deletion of _generate_app_icon_via_openai. It has no callers and main removed it deliberately in "enforce gateway-only LLM routing" (bf36684). - chat-hermetic.yaml: union of both covers lists. - desktop-swift-providers.json: line-count baseline, regenerated below.
…andling (BasedHardware#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge BasedHardware#10600, BasedHardware#10601, and BasedHardware#10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
Problem
POST /v1/agent/execute-toolisasync def, but ran two blocking calls directly on the event loop:load_app_tools(uid)— a Redis read plus one Firestore document read per enabled apptarget.invoke(params, config=config)— everyCORE_TOOLSentry is a sync@toolthat fans out to Firestore/Pinecone, andget_conversations_toolacceptslimitup to 5000One agent VM calling this endpoint parked the whole backend event loop for the duration of that scan: every other connection,
/health, and the HPA metrics endpoint froze with it. This is the "silent poison" classbackend/AGENTS.md→ Common Gotchas #3 describes.The canonical path one file over already does both correctly —
utils/retrieval/agentic.py:707(await run_blocking(db_executor, load_app_tools, uid)) and:331(await tool_obj.ainvoke(...)). This router was the drift.Not caught by
scan_async_blockers.py: its DB detector is import-aware overdatabase.*names, and neitherload_app_toolsnort.invokeis one.Change
Both calls now go through
run_blocking(db_executor, ...), which copies the current context soagent_config_contextstill resolves inside the worker thread (verified:utils/executors.py:89usescontextvars.copy_context()).Also stops echoing raw exception text. Pydantic renders
input_value=<...>, so aValidationErrorfrom caller-supplied params wrote user content verbatim into backend logs and returned it over the wire under HTTP 200. The log line now carrieserror_typeonly and the response returns a fixedTool execution failedcategory. Sanitizing free-form text was insufficient because ordinary user prose contains no token pattern to redact.Product invariants
None matched by these paths.
Failure-Class: none
Verification
pytest tests/unit/test_tools_agent_route_response_shape.py tests/unit/test_agent_vm_async.py tests/unit/test_agent_tool_geolocation_async.py tests/unit/test_chat_memory_tool_caller.py— 18 passedinvokewhile the test coroutine tries to regain control. Confirmed to fail on the unfixed router withassert 3.006059459061362 < 1.0; the whole file runs in 0.08s with the fix.run_blockingto callfn()inline, which would erase the seam under test, so this case restores a realThreadPoolExecutoroffload including the contextvar copy.