ai-powered-conversational-intelligence

40 — Governed Predictive Analytics Engine

Prompt 40 of the ongoing Enterprise AI Analytics & Recommendation Platform initiative, expanding analytics.forecasting (Prompt 16’s time-series projection engine) into general-purpose, governed regression and classification — demand, churn, risk, and beyond. INSPECT/PLAN/ IMPLEMENT/TEST/REVIEW/FIX/DOCUMENT — one new sibling module within the existing analytics/ package (analytics/predictive.py), additive model extensions, a new multi-agent specialist, a new standalone REST surface (api/predictive.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 regression/classification/ML-model concept existed anywhere in this codebase prior to this prompt. analytics.forecasting.generate_forecast fits one of five deterministic stdlib-only baseline models to a single chronological series and projects it forward — it has no concept of multiple input features, no train/test split, no classification at all. analytics.scenario/ analytics.causal compare or perturb already-known values; neither fits a model. The closest existing building blocks worth reusing, all found by inspection:

2. What was built

analytics/predictive.py (new)

train_predictive_model is a pure function over an already-fetched baseline dataset (columns, rows): it never queries a database and never calls an LLM. The model catalog is a small, closed, reviewed set (PredictiveModelType.LINEAR_REGRESSION/LOGISTIC_REGRESSION) — never an arbitrary class name a caller (or an LLM) could inject.

Every governance control the mission names, each with its own code path and its own dedicated test:

  1. Data sufficiency — Settings.predictive_min_training_rows/ predictive_min_rows_per_feature/predictive_min_rows_per_class, checked before any split or fit is attempted.
  2. Leakage checks (_detect_leakage) — a feature identical to the target, or correlated with it at/above Settings .predictive_leakage_correlation_threshold (Pearson correlation via scipy.stats.pearsonr), is flagged; rejected by default (Settings .predictive_reject_on_leakage), always disclosed in PredictiveModelResult.leakage_findings either way.
  3. Train/test separation — every evaluation metric is computed only on a held-out test split the model was never fit on. The split itself is a deterministic, hash-based ordering (_deterministic_order: sha256(f"{seed}:{index}")), not Python’s or numpy’s own global random state — the literal mechanism behind “test reproducibility,” verified directly (TestReproducibility::test_the_same_data_and_seed_always_produce_the_same_result). Classification uses a stratified variant (_stratified_split) so both splits contain examples of every class.
  4. Feature validation — every feature/target column must exist, a feature may not also be the target, and (a disclosed, bounded scope for this engine version) every feature and a regression target must be numeric — categorical features are rejected outright, never silently coerced.
  5. Versioning and evaluation — PredictiveModelMetadata records the model type, feature list, target, split sizes/fraction, random seed, and both a data and a model fingerprint; RegressionMetrics(MAE/RMSE/R²)/ClassificationMetrics(accuracy/ macro-precision/recall/F1), each with its own formula string — master-contract rule 11.
  6. Authorization — a feature or target column config .sensitive_columns classifies restricted is rejected (PredictiveModelStatus.UNAUTHORIZED) unless the caller holds Permission.VIEW_RESTRICTED_COLUMNS.
  7. “Store model/data fingerprints, features and metrics” — every successful training run is audit-logged (security.audit_log .log_security_event, "predictive_model_trained") carrying both fingerprints, the feature list, and split sizes — never the raw data or the fitted coefficients. Deliberate, disclosed choice, not an oversight: this engine (like every other one in this package) has no persisted model registry in this pass — “storing” happens through the identical audit-log mechanism every other authorization/ governance event in this codebase already uses, not a new database table. See §4 for the full reasoning.

Uncertainty, exposed per task type (PredictionWithUncertainty): regression predictions carry a residual-based prediction interval (the same z-based convention analytics.forecasting.ForecastPoint already establishes); classification predictions carry the full per-class probability distribution (predict_proba).

detect_feature_drift — a standalone, two-dataset comparison (mirroring RootCauseResult’s own “standalone, not one more finding” precedent) using a two-sample Kolmogorov-Smirnov test (scipy.stats.ks_2samp) per feature, flagged at Settings .predictive_drift_p_value_threshold. A column missing from either side, non-numeric, or with too few points is skipped and disclosed in notes, never silently ignored.

analytics/models.py (extended, additive only)

New types: PredictiveDomain, PredictiveTaskType, PredictiveModelType, PredictiveModelStatus, LeakageFinding, RegressionMetrics, ClassificationMetrics, PredictiveModelMetadata, PredictionWithUncertainty, PredictiveModelResult, FeatureDriftFinding, FeatureDriftReport. Every pre-existing type is byte-for-byte unchanged.

Multi-agent wiring (agent/multiagent/)

A new AgentName.PREDICTIVE specialist, gated on an explicit, caller-supplied PredictiveRequest (agent/multiagent/supervisor.py) — the planner never creates one. Like ScenarioRequest (and unlike OptimizationRequest), it carries a data_task: the training data comes from one sql_data subquestion’s own already-governed rows, never a second query. The tool is registered at Permission.ASK (the identical, now-recurring reasoning TOOL_OPTIMIZATION’s own comment already documents: the registry-level gate is a pure formality, and the real, specific Permission.VIEW_RESTRICTED_COLUMNS check happens inside train_predictive_model itself, surfaced as a properly disclosed PredictiveModelStatus.UNAUTHORIZED open item, never a bare, unexplained registry denial) — this prompt did not need to rediscover Prompt 39’s own bug-fix the hard way, since the pattern was already established and followed from the start.

REST surface (api/predictive.py, api/predictive_schemas.py, new)

POST /predictive/train and POST /predictive/drift — neither route ever queries a database or calls an LLM. Both take the dataset(s) directly in the request body. Gated by Settings .enable_predictive_analytics (404 when off), Permission.ASK, rate limiting, and payload bounds (Settings.max_result_rows/ predictive_max_features/predictive_max_predict_rows).

Config (config/settings.py)

enable_predictive_analytics: bool = True, predictive_min_training_rows/predictive_min_rows_per_feature/ predictive_min_rows_per_class, predictive_leakage_correlation_threshold, predictive_reject_on_leakage, predictive_drift_p_value_threshold, predictive_max_features, predictive_max_predict_rows — same on-by-default-but-escapable, fully-documented posture as every flag in this series.

3. Proof: reproducibility, drift, insufficient data, and authorization

All directly in tests/test_predictive_analytics.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

5 test files touched (4 new, 1 extended):

Full backend suite: 4181/4181 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 7 remaining errors are pre-existing, in files this prompt never touched — confirmed via git status). bandit: 0 findings across every new/changed production module (2616 lines scanned).

6. Security / tenant-isolation / performance review

7. Known limitations / remaining risks

Add a persisted model registry (a new, dedicated table, following the exact pattern Prompt 18’s RecommendationRecord already established for a different engine’s own outputs) so a model trained once can be scored against many later, separate requests by its own model_fingerprint — closing this prompt’s own most consequential disclosed gap (“no persisted model registry,” §4) — and/or categorical feature encoding (one-hot/ordinal), extending feature validation to accept and transparently encode non-numeric columns rather than rejecting them outright.