Repository navigation
perf(cognition,#1204+#1207-half): Shared<BoxFuture> single-flight + typed AnalysisError - #1215
Merged
Merged
Conversation
…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.
4 tasks done
…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.
This was referenced May 14, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 withfutures::Shared<BoxFuture<...>>. Awaiters share the analyzer's future natively (no busy poll, no inner mutex). Outer map switches toparking_lot::Mutexsince the critical section is sync.Part 2 — Typed AnalysisError (#1207 half)
Replaces
Result<T, String>atanalyze/run_analysis/parse_model_outputwith typedAnalysisErrorenum (4 variants), ts-rs auto-exported so TS callers canswitch (err.kind)instead of substring-matching. Same shape pattern ascognition::host_capability_probe::ProbeError.Variants:
MissingEnvelope { raw_excerpt }— model emitted prose, not JSONMissingField { field }— JSON shape OK, key missing or wrong typeEmptyField { field }— required key present but empty stringInferenceFailed { 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
cognition::shared_analysistests pass byte-identicalrun_analysiswould need to be a generic. Out of scope for this PR; tracking as follow-up.Coordination
cognition::tool_executor(no overlap with this PR)respondhot path — pairs cleanly (admission ADDS work, this PR FREES contention)Followups
persona::response::respondstill maps to String at the boundary; converting that requires touching the IPC handler + recorder traces. Separate scoped PR.Refs umbrella #1201 / #1203, closes #1204, partially closes #1207 (AnalysisError half — sibling does ToolError half in #1217).