ai-powered-conversational-intelligence

37 — Advanced Root Cause Engine

Prompt 37 of the ongoing Enterprise AI Analytics & Recommendation Platform initiative, following 14_ANOMALY_ROOT_CAUSE_CONTRACT.md (the original anomaly-detection/root-cause engine) and reusing Prompt 34’s multi-agent supervisor (34_MULTI_AGENT_SUPERVISOR_CONTRACT.md), which had already wired Prompt 14’s flat engine into one live (test-only, not yet caller-triggered) agent. INSPECT/PLAN/IMPLEMENT/TEST/REVIEW/FIX/ DOCUMENT — one new computation module (analytics/causal.py), additive model/engine extensions, one new multi-agent tool, additive config surface, and a dedicated security regression test. No existing route, node, prompt, or Settings field changed behavior for any pre-existing caller.

1. Inspection: what already existed vs. the real gap

analytics/root_cause.py::investigate_root_cause (Prompt 14) already does one, flat, single-level contribution breakdown between a current and a baseline period: group by a dimension (or a flattened composite of several), rank by |contribution|, keep only what clears a percentage- of-magnitude bar. What it does not do, and what this prompt’s mission explicitly names:

Separately, inspection found Prompt 34’s multi-agent supervisor (agent/multiagent/agents.py::root_cause_handler) already calls investigate_root_cause as its one root_cause specialist, gated on an explicit, caller-supplied RootCausePair — but api/analyst.py’s own /analyst route never populates root_cause_pairs at all (confirmed by reading the route directly), so in production today this path is reachable only by a future caller of run_supervised_analysis that supplies one explicitly, or by tests. This prompt’s new capability rides the same, already-established “explicit pair, planner never creates one” gate — see §4 for what stays deliberately out of scope.

2. What was built

analytics/causal.py (new)

investigate_root_cause_advanced(current_rows, baseline_rows, columns, dimension_hierarchy, value_column, settings=None) -> AdvancedRootCauseResult — reuses investigate_root_cause (Prompt 14, byte-for-byte, never reimplemented) as the per-level computation, and layers four new capabilities on top of it:

  1. Sample-size/confidence enforcement (StatisticalSignificance/_two_sample_significance): every contributor Prompt 14’s own contribution-percent bar already validated is re-checked with a Welch-style two-sample z-test over the raw per-row values underlying each period’s total (stdlib only — statistics.pvariance for within-group variance, math.erf for the exact normal CDF; no numpy/scipy). A contributor with fewer than Settings.root_cause_min_sample_size rows on either side never gets a p-value computed at all (SignificanceVerdict.INSUFFICIENT_SAMPLE) — the literal “enforce sample-size/confidence thresholds and return insufficient evidence when necessary” requirement.
  2. Known causes vs. distractors (ContributorEvidence.is_distractor): a contributor that clears the contribution-percent bar but fails the significance check is a distractor — numerically large, statistically unsupported — reported in HierarchicalRootCauseNode.distractors, never promoted into a claim.
  3. Hierarchical drill-down (HierarchicalRootCauseNode.children): for a multi-level dimension_hierarchy (e.g. [["Region"], ["Category"]]), only a statistically supported (never a distractor) top-level contributor is drilled into, over the real subset of rows matching its own label — “only drill where there’s already evidence” bounds the recursion to Settings.root_cause_max_hierarchy_depth, never a combinatorial expansion of every contributor at every level.
  4. Interaction testing (InteractionEffect/_detect_interactions): when a hierarchy names exactly two single-column levels, this module runs the textbook two-way, unweighted-means fixed-effects interaction decomposition (interaction = cell_contribution - (row_mean(a) + col_mean(b) - grand_mean)) over the full observed (label_a, label_b) grid — exactly 0 for a perfectly additive dataset, verified directly (TestInteractionDetection ::test_a_perfectly_additive_dataset_has_exactly_zero_interaction), and strictly non-zero whenever one specific combination moves differently than its two main effects alone would predict. A genuine interaction is only ever reported (is_statistically_justified=True) when that cell’s own sample clears the significance bar and its residual clears Settings.root_cause_interaction_min_percent.

Correlation, never confirmed causation (structural, not conventional)

AdvancedRootCauseResult.causation_confirmed is declared Literal[False] — pydantic rejects construction with True (proven directly: tests/security/test_causal_never_asserts_causation.py ::TestTypeLevelGuarantee::test_causation_confirmed_cannot_be_constructed_as_true), and mypy rejects it statically too. evidence_type is a new, deliberately singleton enum, CausalEvidenceStrength.CORRELATION_ONLY — the only value any code path in this module can ever produce, until (if ever) a future module with a real controlled experiment/counterfactual method earns a second member. Every result carries a fixed, non-LLM-authored causation_disclaimer constant. truth_level is always DataTruthLevel.AI_INFERENCE (the same framing ForecastResult .truth_level already established for a deterministic-but-still- inferential result — the raw contribution arithmetic is DATABASE_FACT- equivalent, but which contributors to trust and how the hierarchy/ interactions are framed is an interpretation over it).

analytics/engine.py (extended, minimal diff)

One new, additive function: group_values_by_label — the identical grouping/null-skipping/composite-label convention group_and_sum_by_label already established (Prompt 14), but returning every underlying raw value per label instead of just the sum. Does not modify group_and_sum_by_label itself at all — a second, independent pass over the same rows, so neither function’s contract changes for its existing callers.

analytics/models.py (extended, additive only)

New types: CausalEvidenceStrength, CAUSATION_DISCLAIMER, SignificanceVerdict, StatisticalSignificance, ContributorEvidence, InteractionEffect, HierarchicalRootCauseNode (recursive, via model_rebuild()), AdvancedRootCauseResult, CAUSAL_ENGINE_VERSION. Every pre-existing Prompt-13/14/16 type (RootCauseResult, ContributorStat, ForecastResult, …) is byte-for-byte unchanged.

Multi-agent wiring (agent/multiagent/)

“Governed dimensions” (retrieval/retriever.py)

New extract_governing_dimensions — the mission’s “compare baselines across time and governed dimensions” requirement, mirroring Prompt 10’s own extract_governing_metrics exactly: filters already-retrieved BUSINESS_CONCEPT chunks (zero new query) down to concept_type == "dimension" ones, returning each one’s business name and underlying schema column (Chunk.table_name, which business_concept_chunk_from_catalog_entry populates from the catalog entry’s own technical_name). Not yet wired into any live dimension_hierarchy resolution — see §4; built and tested so a future caller (a planner deciding which column names to offer the advanced engine) can prefer an officially governed dimension name over an arbitrary schema column with confidence it is CONFIRMED_BUSINESS_TRUTH.

Config (config/settings.py)

enable_advanced_root_cause: bool = True, root_cause_min_sample_size: int = Field(default=5, ge=1), root_cause_significance_alpha: float = Field(default=0.05, gt=0.0, lt=1.0), root_cause_max_hierarchy_depth: int = Field(default=3, ge=1, le=6), root_cause_interaction_min_percent: float = Field(default=5.0, gt=0.0) — same on-by-default-but-escapable, fully-documented posture as every flag in this series.

3. Proof: known causes, distractors, no-cause, and insufficient data

All four, directly in tests/test_analytics_causal.py:

Every number in every test was independently hand-computed and cross-checked by directly exercising the module before being written into the test file — not “whatever the code happened to produce.”

4. Explicitly out of scope

5. Testing

6 test files touched (3 new, 3 extended):

Full backend suite: 4020+ tests pass, zero regressions (pytest -q, re-run after every change in this prompt — exact count at submission time: 4020 passed before this prompt’s own new tests were added, plus this prompt’s own ~39 new tests). ruff check/black --check clean on every new/changed file. mypy clean on every new/changed production file (the one pre-existing, unrelated error in db/schema_introspection.py predates this prompt and was not touched). bandit clean (0 findings) on every new/changed production module.

6. Security / tenant-isolation / performance review

7. Known limitations / remaining risks

Teach the agent pipeline to recognize a “why did X change” question (Prompt 11’s AnalyticalIntentType.ROOT_CAUSE/ANOMALY, already classified but still unused for this) and generate the second, baseline-comparison SQL query investigate_root_cause_advanced needs, resolving its dimension_hierarchy preferentially from extract_governing_dimensions — the concrete next step that closes both of this prompt’s own disclosed “not live-wired” gaps at once, and the same recommendation Prompt 14 already made, now with a genuinely richer engine on the other end of it.