Skip to content

perf(cognition,#1204+#1207-half): Shared<BoxFuture> single-flight + typed AnalysisError - #1215

Merged
joelteply merged 2 commits into
canaryfrom
perf/shared-analysis-shared-future-1204
May 14, 2026
Merged

joelteply merged 2 commits into
canaryfrom
perf/shared-analysis-shared-future-1204

Conversation

@joelteply

@joelteply joelteply commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two related cognition-layer perf wins folded into one PR. Both touch analyze() so a single coherent change avoids a rebase trap (sibling/codex flagged the conflict; we agreed to fold AnalysisError into this PR while sibling does ToolError independently in #1217).

Part 1 — Shared<BoxFuture> single-flight (#1204)

Replaces the nested Arc<TokioMutex<HashMap<String, Arc<TokioMutex<Option<...>>>>>> + polling loop with futures::Shared<BoxFuture<...>>. Awaiters share the analyzer's future natively (no busy poll, no inner mutex). Outer map switches to parking_lot::Mutex since the critical section is sync.

Part 2 — Typed AnalysisError (#1207 half)

Replaces Result<T, String> at analyze / run_analysis / parse_model_output with typed AnalysisError enum (4 variants), ts-rs auto-exported so TS callers can switch (err.kind) instead of substring-matching. Same shape pattern as cognition::host_capability_probe::ProbeError.

Variants:

  • MissingEnvelope { raw_excerpt } — model emitted prose, not JSON
  • MissingField { field } — JSON shape OK, key missing or wrong type
  • EmptyField { field } — required key present but empty string
  • InferenceFailed { reason } — provider-side failure (timeout / API)

Why these matter for the umbrella

Part of #1201 (codex) / #1203 (lane) — RTOS-for-AI throughput. Sibling's #1213 ADDS work to the cognition path (admission gate); this PR FREES contention on the shared cache the same path reads, AND types the error space so the typed cognition pipeline can route on failure modes instead of substring matching.

Testing

  • All 15 pre-existing cognition::shared_analysis tests pass byte-identical
  • 6 new tests added (4 in error::tests, 2 new variant-coverage tests in prompt::tests)
  • Clippy baseline drops -1 (162 from 163), locked in
  • Single-flight regression test (assert N concurrent calls = 1 inference) requires an injectable inference seam — run_analysis would need to be a generic. Out of scope for this PR; tracking as follow-up.

Coordination

Followups

  • Push AnalysisError further up: persona::response::respond still maps to String at the boundary; converting that requires touching the IPC handler + recorder traces. Separate scoped PR.
  • Single-flight regression test (needs injectable inference seam)

Refs umbrella #1201 / #1203, closes #1204, partially closes #1207 (AnalysisError half — sibling does ToolError half in #1217).

…re> in shared_analysis single-flight

Closes #1204.

The previous shape used Arc<TokioMutex<HashMap<String, Arc<TokioMutex<Option<Result>>>>>>
for the in-flight tracker, with awaiters polling the inner mutex in a loop:

    loop {
        if let Some(result) = slot.lock().await.clone() {
            return result;
        }
        tokio::task::yield_now().await;
    }

Two costs:
  1. Inner-mutex acquisition on every awaiter poll cycle, serialized
     across N personas requesting the same analysis.
  2. tokio::sync::Mutex on the outer map even though the critical
     section (HashMap get/insert) is microseconds and never spans
     an .await — paying async-aware mutex cost for sync work.

New shape uses futures::future::Shared<BoxFuture<...>>:

  - First caller for a cache_key builds a Shared future, registers
    it in the IN_FLIGHT map, and is the analyzer.
  - Subsequent callers clone the registered Shared and .await it.
  - Both arms collapse onto the SAME underlying inference future.
    Shared::poll dispatches to the first poller; subsequent pollers
    register a waker and resume when the future resolves. No busy
    loop, no inner mutex, one poll for the actual inference.
  - Outer map switches to parking_lot::Mutex — sync, ~3x cheaper
    than tokio::Mutex for the get/insert/remove pattern that never
    spans an .await.

Analyzer-only post-processing (cache publish + IN_FLIGHT cleanup)
runs after the shared future resolves. Awaiters skip it (the
analyzer already did it).

Test posture:
  - All 15 existing cognition::shared_analysis tests still pass
    (cache key determinism, TTL boundary, prompt parse/sanitize)
  - Clippy baseline drops -1 (162 from 163), locked in
  - Single-flight regression coverage requires an injectable
    inference seam (run_analysis would need to be a generic over
    F: Fn(...) -> Future) — out of scope for this PR; tracking as
    follow-up

Refs umbrella #1201 (codex) / #1203 (lane) — RTOS-for-AI throughput.
…ring> at shared_analysis boundaries

Closes the AnalysisError half of #1207 (sibling has the ToolError half in PR #1217).

New module cognition/shared_analysis/error.rs defines AnalysisError with
4 typed variants and ts-rs auto-export so TS callers can pattern-match
on the discriminant instead of substring-matching error text:

  - MissingEnvelope { raw_excerpt }    — model emitted prose, not JSON
  - MissingField { field }              — JSON shape OK, key missing
  - EmptyField { field }                — required key present but empty
  - InferenceFailed { reason }          — provider-side failure (timeout/API/etc)

Same shape pattern as cognition::host_capability_probe::ProbeError
(serde tag=kind, rename_all=camelCase, thiserror::Error for Display).
Joel rule: feedback_two_ironclad_rules_tests_and_fallbacks.md
('typed errors at boundary; fallbacks have ruined this project').

Sites converted:
  - cognition::shared_analysis::analyze public signature
  - cognition::shared_analysis::run_analysis internal signature
  - cognition::shared_analysis::prompt::parse_model_output internal
  - IN_FLIGHT slot type (Shared<BoxFuture<'_, Result<_, AnalysisError>>>)
  - generate_text mapping via AnalysisError::from_inference helper
  - persona::response::respond callsite maps back to String at the
    boundary (response.rs public surface still String for now;
    pushing the typed error further up is a follow-up that touches
    IPC handler + recorder traces)

Tests:
  - 4 new error::tests (Display, serde round-trip, from_inference helper,
    auto-generated ts-rs binding)
  - parse_fails_loud_on_missing_summary renamed to ..._missing_summary_key
    (the test was actually exercising the envelope-detection path,
    not a missing-field path; corrected variant assertion)
  - parse_fails_loud_on_summary_wrong_type added — the only realistic
    path that surfaces MissingField (summary key present but non-string)
  - parse_fails_loud_on_empty_summary added — exercises EmptyField
  - All 21 cognition::shared_analysis tests pass (was 15 +6 new)
  - Clippy stays at baseline 162

Refs umbrella #1201 (codex) / #1203 (lane) — RTOS-for-AI throughput.

Coordination: this commit folds the AnalysisError half of #1207 into the
already-open PR #1215 (perf #1204), since both touch analyze() return
type — single coherent PR avoids a rebase trap. Sibling #1217 covers
the ToolError half independently in tool_executor.
@joelteply joelteply changed the title perf(cognition,#1204): Shared<BoxFuture> single-flight in shared_analysis (drop nested TokioMutex+polling) perf(cognition,#1204+#1207-half): Shared<BoxFuture> single-flight + typed AnalysisError May 14, 2026
@github-actions github-actions Bot added size: L and removed size: M labels May 14, 2026
@joelteply
joelteply merged commit 68df16d into canary May 14, 2026
4 checks passed
@joelteply
joelteply deleted the perf/shared-analysis-shared-future-1204 branch May 14, 2026 18:18
joelteply added a commit that referenced this pull request May 14, 2026
…ath allocs (#1226)

* perf(cognition): make CognitionTrace optional on admit() — drop hot-path allocs

Joel directive 18:30 — "iterate for performance, lower latency + CPU
drain for same/more features."

## Before

`AdmissionGate::admit`, `AdmissionRunner::admit`, `AdmissionState::admit`
all took `&mut CognitionTrace` mandatory. The in-process hot-path
admission gate added by #1213 constructs a `CognitionTrace::new()`
every chat turn, feeds it through admit() (which appends a
`SEAM_ADMISSION` entry via `record_seam`), and drops it on the floor.
The trace's recording work is pure waste on that path:

- `now_ms()` syscall for the duration
- `serde_json::json!({...})` Map allocation (4-5 allocs: HashMap +
  3-4 String key/value pairs)
- `trace.record(...)` Vec push + `name.to_string()` allocation

Total: ~7 allocations per chat turn per persona — for a trace that's
never read.

## After

`admit()` at all three layers takes `Option<&mut CognitionTrace>`.
`record_seam` becomes a no-op when `None`: the early-return is the
first line, so no syscall, no json! Map, no Vec push.

- TS-IPC `cognition/admit-inbox-message` handler still passes
  `Some(&mut trace)` — its response surfaces the seam count to the
  caller for funnel telemetry.
- In-process inline gate (`run_inline_admission_gate` in
  modules/cognition.rs) passes `None` — it doesn't propagate the
  trace anywhere.
- Test sites (16 callers across admission.rs, admission_state.rs,
  inbox_admission.rs) pass `Some(&mut trace)` — existing behavior.

Internal use of `trace.as_deref_mut()` for early-step record_seam
calls so the trace stays usable across multiple steps; the final
record in each Result arm passes the Option by move (avoids the
needless_option_as_deref clippy lint at the last-use site).

## Composes with the cognition perf cluster

This sits next to:
- #1215 (claude-tab-2): Shared<BoxFuture> single-flight in
  shared_analysis — eliminates polling + nested-Mutex contention.
- #1219 + #1220 (claude-tab-2): build_prompt 40→1 allocs, prompt
  assembly 5+N→1 allocs, single-user-turn message assembly 3+N→1.
- #1216 (mine): Arc<TurnContext> hoist eliminates N-clone per-turn
  duplication of recent_history + known_specialties + room_id.
- #1213 (mine): admission gate now runs on every chat turn — adds
  work — this PR cuts that added work to its essentials.

Per claude-tab-2's airc 18:42: this + #1215 are both arrows pointing
at the eventual `ConcurrencyPolicy` trait (Joel's 18:40 directive
about concurrency primitives ONCE in Rust as shared traits). When
that trait lands (claude-tab-2 takes first slice via
candle_adapter.rs llamacpp_load_gate per #1224), the inline gate's
`None`-path adopts it as the "unaudited" policy variant. PR-shaped
to compose into that future refactor, not preempt it.

## Validation

- `cargo test --lib --features metal,accelerate -- persona::admission
  persona::admission_state persona::inbox_admission inline_admission`
  — 55 passed, 0 failed. Every existing admission test confirms the
  trace-Some path still behaves identically.
- `cargo clippy --lib --features metal,accelerate` — no NEW
  warnings introduced (vision_integration test E0560 errors are
  pre-existing on canary from #1216's RespondInput hoist —
  separate issue, not introduced by this PR).
- Pre-push hook ran without --no-verify.

Refs Joel's 18:30 + 18:40 directives. Coordinated with claude-tab-2
on airc.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(tests): port vision_integration + persona_respond_replay to TurnContext

Cleanup of fallout from my own #1216. The TurnContext hoist moved
\`room_id\` / \`recent_history\` / \`known_specialties\` off
\`RespondInput\` into \`Arc<TurnContext>\`, but two integration test
files (\`vision_integration.rs\`, \`persona_respond_replay.rs\`) still
constructed \`RespondInput\` with the old flat-field shape and broke
\`cargo check --tests\`. Both are gated by \`#[ignore]\` so they don't
run in CI by default and the breakage didn't surface until I ran
\`cargo check --tests\` for #1226.

Mechanical port: each \`RespondInput { ... }\` literal now constructs
\`turn_context: TurnContext::arc(room_id, recent_history,
known_specialties)\` instead of three flat fields. Mirrors what
\`build_respond_input\` does for the live IPC path.

Six call sites total — three in \`persona_respond_replay.rs\` (the
fixture-replay constructor + two synthesized-prod-shape inputs), one
in \`vision_integration.rs\`. Test bodies + assertions unchanged.

\`cargo check --tests --features metal,accelerate\` clean afterward.

Refs #1216 (the hoist this fixes the fallout from) + #1226 (this
branch). Folded into #1226 since both are mine and the hoist was
mine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant