ai-powered-conversational-intelligence

39 — Governed Optimization Engine

Prompt 39 of the ongoing Enterprise AI Analytics & Recommendation Platform initiative, inspecting and reusing the conventions Prompt 37 (causal), Prompt 38 (scenario), and Prompt 34 (multi-agent supervisor) already established, applied to a genuinely new kind of problem: optimal decision-variable values subject to constraints, not a comparison or a projection. INSPECT/PLAN/IMPLEMENT/TEST/REVIEW/FIX/DOCUMENT — one new top-level package (optimization/), a new RBAC permission, a new multi-agent specialist, a new standalone REST surface (api/optimization.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 decision-optimization/LP/MILP concept existed anywhere in this codebase prior to this prompt. analytics.scenario/analytics.causal compare real-vs-hypothetical or real-vs-real datasets; nothing searches for an optimal assignment of variables subject to constraints. recommendation.engine reasons over already-computed facts into a suggested next step; it has no notion of a mathematical objective/constraint system at all. The closest existing building blocks worth reusing, all found by inspection:

2. What was built

optimization/models.py (new)

The mission’s own named requirement, made concrete and structural: “Define decision variables, objective, constraints, rules, source data and version” — and, separately, “never let an LLM invent constraints or objectives.” That second rule is enforced by the shape of these types themselves, not a runtime check: ObjectiveTerm/ConstraintTerm are (variable, coefficient) numeric pairs referencing an already- declared DecisionVariable by name — there is no field anywhere in this module, or in its REST-layer mirror (api/optimization_schemas.py), that accepts a free-text formula/expression string. Proven directly (tests/security/test_optimization_never_presents_recommendation_as_fact.py ::TestStructuralNoFormulaField): both term types, at both layers, have exactly two fields.

optimization/validator.py (new)

validate_problem — the mission’s own “reject invalid or unauthorized assumptions” requirement. Reports every violation found, never stopping at the first (the identical “no partial trust” convention analytics.scenario.validate_scenario_parameters already establishes): undeclared variable references (objective and every constraint), duplicate names, non-finite/malformed bounds, too many variables/ constraints, and the two authorization checks below. OptimizationValidation .is_unauthorized is a typed flag (not a string-matching inference over violations), so optimization.engine.solve_optimization_problem can report UNAUTHORIZED vs. INVALID precisely.

optimization/engine.py (new) — deterministic LP/MILP solving

solve_optimization_problem validates, then solves via scipy.optimize.linprog (HiGHS) — one solver entry point for both continuous and mixed-integer problems (via linprog’s own integrality parameter), never two parallel code paths to keep in sync.

Sensitivity information, only when it is theoretically valid. Shadow prices (LP duals) are a well-defined concept only for a continuous linear program — a mixed-integer problem’s duals (whatever HiGHS happens to report for its final LP relaxation) do not have the same marginal-value interpretation once integrality constraints bind, a standard result in optimization theory, not an arbitrary choice this engine makes. sensitivity_available is True, and shadow prices/ reduced costs are ever populated, only when every decision variable is CONTINUOUS — verified directly (TestSolve::test_a_mixed_integer_problem_never_reports_sensitivity, tests/test_optimization_engine.py::TestFeasible ::test_a_mixed_integer_problem_solves_and_respects_integrality).

The sign-convention math was empirically verified, not just derived on paper, against six hand-computed combinations of (ConstraintOperator, ObjectiveSense) — see optimization.engine ._shadow_price_sign’s own docstring for the full derivation and the exact worked numbers, and tests/test_optimization_engine.py ::TestRegression for the three regression tests this produced (a published textbook maximize-LP with three constraints, a minimize-with- GE-vs-EQ equivalence check, and a maximize-with-GE sign-cancellation check).

RBAC — a new, dedicated permission

agent.authz.Permission.RUN_OPTIMIZATION (new), granted starting at the _ANALYST tier (the identical reasoning VIEW_RESTRICTED_COLUMNS already uses) — the mission’s own “require authorization” requirement, deliberately not folded into Permission.ASK: an optimization result is a suggested real-world decision (a price, a shift schedule, an allocation), a more consequential capability than a read-only question. Enforced at the REST layer (Depends(require_permission (Permission.RUN_OPTIMIZATION))) and, independently, inside optimization.validator.validate_problem itself (has_role_permission) — the second check is the one that actually fires for the multi-agent specialist, which deliberately registers its own tool at the ASK tier (see the next section for why) and relies on the engine’s own richer, disclosed UNAUTHORIZED status instead of a bare, unexplained denial.

Audit

Every authorization denial inside validate_problem is logged via security.audit_log.log_security_event ("optimization_unauthorized") — never the problem’s own coefficients/values, only problem_id/ domain/(for the restricted-column case) which columns, the identical “log metadata, never the sensitive content” posture recommendation .engine’s own "recommendation_evidence_suppressed" event already establishes.

Multi-agent wiring (agent/multiagent/) — and a real bug this prompt’s

own test suite found and fixed

A new AgentName.OPTIMIZATION specialist, gated on an explicit, caller-supplied OptimizationRequest (agent/multiagent/supervisor.py) — the planner never creates one. Unlike ScenarioRequest/RootCausePair, it carries no data_task: a problem is already fully specified by its own caller, never derived from a sql_data task’s rows.

A real, found-and-fixed design bug: the new tool was first registered with permission=Permission.RUN_OPTIMIZATION at the registry level. tests/test_multiagent_supervisor.py ::TestOptimizationAndWorkspace::test_an_unauthorized_caller_never_gets_a_solved_result caught that this made the registry’s own ToolGateway/ToolRegistry .execute deny the call with a bare, generic AgentOutput(status="denied", detail="tool not permitted") before optimization_handler’s own, richer UNAUTHORIZED-status handling ever ran — a materially worse, unexplained user-facing outcome than scenario/root_cause give for their own (always-granted) Permission.ASK-gated tools. Fixed by registering TOOL_OPTIMIZATION at Permission.ASK too (a pure formality every caller who can reach the supervisor at all already clears) and letting the engine’s own internal validate_problem be the only place Permission.RUN_OPTIMIZATION is actually enforced for this path — restoring the identical two-tier pattern scenario/root_cause already use, verified by re-running the fixed test.

REST surface (api/optimization.py, api/optimization_schemas.py, new)

POST /optimization/validate and POST /optimization/solve — neither route ever queries a database or calls an LLM. Both take a fully- specified problem directly in the request body. Gated by Settings .enable_optimization_engine (404 when off), Permission.RUN_OPTIMIZATION, rate limiting, and payload bounds (Settings .optimization_max_variables/optimization_max_constraints).

Config (config/settings.py)

enable_optimization_engine: bool = True, optimization_max_variables: int = Field(default=50, gt=0), optimization_max_constraints: int = Field(default=100, gt=0) — same on-by-default-but-escapable, fully-documented posture as every flag in this series.

3. Proof: feasible, infeasible, boundary, and regression cases

All directly in tests/test_optimization_engine.py:

4. Explicitly out of scope

5. Testing

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

Full backend suite: 4129/4129 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 (2608 lines scanned in optimization/ alone).

6. Security / tenant-isolation / performance review

7. Known limitations / remaining risks

Promote OptimizationProblem.business_rules from descriptive labels into a real, reusable, named constraint-template registry (mirroring config/sensitive_columns.yaml’s own hand-authored-YAML, loaded-fresh convention), and/or teach the multi-agent supervisor to resolve an OptimizationProblem’s own coefficients from a sql_data task’s real rows (the identical integration ScenarioRequest already has) rather than requiring every problem to be fully caller-specified — closing both of this prompt’s own disclosed “not yet wired” gaps, the same recurring, deliberate deferral every engine prompt in this series has made at least once.