ai-powered-conversational-intelligence

38 — Governed What-If Scenario Engine

Prompt 38 of the ongoing Enterprise AI Analytics & Recommendation Platform initiative, built on top of Prompt 13’s analytics engine (analytics.engine.compute_analytics_result, reused verbatim), Prompt 16’s forecasting engine (analytics.forecasting.generate_forecast, reused for the forecast-scenario path), Prompt 34’s multi-agent supervisor (a new specialist, following the exact root_cause/forecast precedent), and Prompt 37’s own “explicit, caller-supplied, the planner never creates one” gate. INSPECT/PLAN/IMPLEMENT/TEST/REVIEW/FIX/DOCUMENT — one new computation module (analytics/scenario.py), additive model/ visualization extensions, a new multi-agent specialist, a new, standalone REST surface (api/scenarios.py), additive config surface, and a dedicated cross-cutting 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

Exhaustive grep confirmed: no “what-if”/”scenario”/hypothetical-parameter concept existed anywhere in this codebase prior to this prompt. analytics.forecasting.generate_forecast projects a historical trend forward, but offers no way to ask “what if growth were different from what actually happened.” analytics.root_cause/analytics.causal compare two real periods; nothing compares a real baseline against a hypothetical one. recommendation.engine reasons over already-executed results; nothing lets a caller propose an assumption and see its modeled effect before (or without) it ever becoming real. The closest existing building blocks worth reusing, all found by inspection and reused rather than reimplemented:

2. What was built

analytics/scenario.py (new)

The engine’s three public functions:

Clearly separating observed facts, assumptions, and modeled estimates

The mission’s central requirement, met two ways:

  1. A dedicated, orthogonal enum — analytics.models .ScenarioValueKind (OBSERVED/ASSUMPTION/MODELED_ESTIMATE), deliberately not agent.provenance.DataTruthLevel (that vocabulary answers “how sure are we,” not “which part of this number is a real measurement vs. a caller’s own input vs. this engine’s arithmetic”).
  2. Structural, not conventional — ScenarioMetricComparison.baseline_kind/.scenario_kind are fixed Literal[ScenarioValueKind.OBSERVED]/Literal [ScenarioValueKind.MODELED_ESTIMATE] — pydantic itself refuses to construct one with the two kinds swapped (proven directly, tests/security/test_scenario_never_presents_estimate_as_fact.py ::TestTypeLevelGuarantee). Every claim the live multi-agent handler renders says “(observed)”/”(modeled estimate)” explicitly, proven through that same handler end to end.

Baseline/scenario comparison and visualization

ScenarioResult.comparisons — one ScenarioMetricComparison per distinct affected metric, computed from the real baseline total vs. the scenario-adjusted total (reusing the identical current_total/baseline_total/zero-denominator-guarded-percent convention analytics.root_cause.investigate_root_cause already established). analytics.visualization.build_scenario_chart_spec (new) mirrors build_forecast_chart_spec’s exact style: a grouped BAR_STACKED chart with distinct Y/SERIES fields for “Baseline” and “Scenario” — never one blended bar — with the scenario’s hypothetical nature disclosed in both notices and accessibility.

Multi-agent wiring (agent/multiagent/)

A new AgentName.SCENARIO specialist (cost_units=1, max_truth_level= AI_INFERENCE, allowed only TOOL_SCENARIO). scenario_handler runs only for an explicit, caller-supplied ScenarioRequest (agent/multiagent/supervisor.py, the identical shape RootCausePair already established) naming which sql_data task’s own already-governed rows to run against — never a second query, never caller-side raw data. caller_roles is never included in the dict the handler passes to ctx.call; agent.tools.registry.ToolRegistry.execute injects the real, already-authorized roles into the tool’s own payload automatically (proven directly, test_a_scenario_cannot_smuggle_identity_through_its_own_tool_call).

REST surface (api/scenarios.py, new)

Two routes, neither of which ever queries a database: POST /scenarios/validate and POST /scenarios/run. Both take the baseline columns/rows directly in the request body — the caller’s own already-fetched, already-governed result (e.g. from a prior POST /execute). This is the literal, structural mechanism behind “run scenarios without changing source data” at the API layer: there is no sql field on either request, no database connection, nothing to validate as a query at all. Gated by Settings.enable_what_if_scenarios (404 when off, mirroring api/analyst.py’s own feature-flag pattern), Permission.ASK, enforce_api_action_rate_limit, and payload bounds (Settings.max_result_rows/scenario_max_parameters) so this pure- compute endpoint can’t become a resource-exhaustion vector just because it never touches a database. api/scenario_schemas.py mirrors analytics.models’ own scenario types field-by-field, the identical “mirror the internal model, don’t re-export it” convention VisualizationSpecOut already established.

Config (config/settings.py)

enable_what_if_scenarios: bool = True, scenario_unrealistic_change_percent_threshold: float = Field(default= 500.0, gt=0.0), scenario_reject_unrealistic: bool = False, scenario_max_parameters: int = Field(default=20, gt=0) — same on-by-default-but-escapable, fully-documented posture as every flag in this series.

3. Proof: boundary, unrealistic, and missing-data cases

All directly in tests/test_analytics_scenario.py:

All example numbers in every test file were independently hand-computed and cross-checked by directly exercising the module (via a scratch script, not shown in the final diff) before being written into the test files — not “whatever the code happened to produce.”

4. Explicitly out of scope

5. Testing

6 test files touched (4 new, 2 extended):

Full backend suite: 4079/4079 tests pass, zero regressions (pytest -q, re-run after every change in this prompt). ruff check/ black --check clean on every new/changed file. mypy clean on every new/changed production and test file (the 5 remaining errors are pre-existing, in 3 files this prompt never touched — confirmed via git status). bandit: 0 findings across every new/changed production module (4369 lines scanned).

6. Security / tenant-isolation / performance review

7. Known limitations / remaining risks

Teach the agent pipeline to recognize a “what if” question (a natural extension of Prompt 11’s AnalyticalIntentType taxonomy, which has no WHAT_IF/SCENARIO category today) and propose a candidate ScenarioParameter set from it — surfaced for the caller’s explicit confirmation before run_scenario/the multi-agent ScenarioRequest ever executes it, preserving this prompt’s own “the planner never creates one” gate rather than weakening it. Alternatively, wire recommendations_for_scenario/build_scenario_chart_spec into a live path and a frontend surface, closing this prompt’s own two disclosed “not yet wired” gaps — the same recurring, deliberate deferral every engine prompt in this series has made at least once.