Files
ss-tools/backend/tests/api/test_scenario_registry.py
busya 58c5ae39cb feat(scenario): server-owned handle pipeline T029d–h + MCP bootstrap/automation + UI launch/approval
Backend (Phase 2c, closes ADR-0023):
- T029b/c: 9 automation MCP tools (REST-parity RBAC, scheduler registration, idempotency), migration 0018; fresh-DB MCP E2E.
- Guard BOOTSTRAP_REVISION_NOT_RUNNABLE in derive_runner_plan (provenance-only revisions never queue a vacuous zero-step PASS); demoted to defense-in-depth after materialization landed.
- T029d: CompiledScenarioHandle/ValidationResultHandle/DraftPackHandle (immutable, owner-bound, content-addressed canonical-bytes store), migrations 0019/0021; minting at REST compile/validate/resolve/draft-pack boundaries; single consumption under SELECT...FOR UPDATE + populate_existing, proven on PostgreSQL (Testcontainers).
- T029e: handle-first create_scenario/create_initial materialize canonical graph_snapshot (+ server-owned action_registry identity) in-transaction; OutboxEvent + RevisionMaterialization (0020) with idempotent worker wired into the scheduler poll loop (30s tick).
- T029f: MCP register_draft_pack write tool; bootstrap accepts only stored handle ids (transitional compile:{run}:{digest} removed); legacy REST POST /scenarios/{id}/revisions retired -> 410; catalog 2.0.0 (pinned-major ritual); ActionRegistry 038.2.0 — generate_report reclassified non-mutating (local draft write), register_artifact/row_edit/bulk_edit stay mutating.
- T029h (hybrid C+X1): inspect_dashboard_context MCP tool (live DashboardQueryModel resolver); context_authority evaluation — server recomputes client-context fingerprint (claimed values ignored), sentinel fingerprints never verify, unreachable env fails open to unverified, live-env mismatches reject typed with zero rows; marker persists on DraftPackHandle, materializes into graph_snapshot; PROD start refuses explicit non-verified (CONTEXT_AUTHORITY_REQUIRED_FOR_PROD); validator recursively rejects query_context/SQL smuggling in dashboard_context; catalog 2.1.0. 043 editor path provably inherits the marker.

Frontend:
- D2: scenario detail route scenarios/[id] — first production host of RunConfigurationPanel (typed 044 launch + Idempotency-Key + redirect to run monitor); ROUTES.scenarioDetail SSOT; registry index links to detail (launch stays off the index).
- D4: ApprovalDecisionPanel + RunMonitorModel.decideApproval — PROD gates decidable from the web UI (run-detail aside on pending_approval).
- Pre-existing suite repairs: oauth-consent raw goto -> ROUTES.login(); InvestigationModels stale dispose signature; settings mcp_oauth_* bind:value undefined crash (backend defaults 15/30/90).
- i18n: approval_* + scenario_detail_* keys in en+ru.

Specs/docs (amendments 2026-09-06/07):
- 038: PackCompiler.Generate contract corrected (pure manifest); ServerOwnedPipeline handle-persistence amendment; verification-program reconciliation (implemented vs PROPOSED IR entities).
- 042: synchronous graph materialization + outbox scope; CreateInitial amendments; RevisionChain @REJECTED for raw client graph_snapshot.
- 050: stage-table implementation-status note, handle-rules status, T029–T029h evidence; WORKSTATE checkpoints; ADR-0023 -> IMPLEMENTED.

Gates: backend full regression 3360 passed (+ PostgreSQL integration green), alembic single head 0021; frontend vitest 3506 passed, lint 0 errors, build OK.
2026-09-07 11:26:34 +03:00

521 lines
23 KiB
Python

# #region Test.ScenarioRegistry.Api [C:3] [TYPE Module] [SEMANTICS testing,api,scenario,registry,list,detail,404,rbac]
# @defgroup ScenarioRegistry Test.Api GET list/detail route tests (T008/T010, US1/US2).
# @LAYER Test
# @RELATION VERIFIES -> [Api.DashboardTesting.Scenarios]
# @TEST_EDGE: not_found->404 NOT_FOUND envelope; empty registry->empty state; filters->empty; paged.
# @TEST_EDGE: RBAC denied->403; invalid paging->422.
# @RATIONALE A standalone FastAPI app with only the scenarios router + real in-memory SQLite session
# keeps the slice isolated from the full app while still exercising real query/serialization.
from __future__ import annotations
from datetime import datetime
import json
from pathlib import Path
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from src.api.routes.dashboard_testing.scenarios import router
from src.core.database import get_db
from src.dependencies import get_current_user
from src.models.agent_run import AgentRun, DraftArtifact
from src.models.auth import Role, User
_FIXTURE_PATH = (
Path(__file__).resolve().parents[1] / "fixtures" / "scenario_registry" / "registry.json"
)
def _parse_ts(value: str | None) -> datetime | None:
if not value:
return None
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def _seed_registry(session) -> None:
from src.models.scenario_registry import (
ScenarioRegistryEntry,
ScenarioRevision,
ScenarioStalenessSignal,
)
data = json.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))
for row in data["entries"]:
session.add(ScenarioRegistryEntry(
scenario_id=row["scenario_id"],
scenario_key=row["scenario_key"],
name=row["name"],
description=row.get("description"),
dashboard_id=row["dashboard_id"],
environment_ids=row.get("environment_ids", []),
owner_id=row["owner_id"],
owner_username=row["owner_username"],
tags=row.get("tags", []),
metadata_version=row["metadata_version"],
current_revision_id=row.get("current_revision_id"),
lifecycle_status=row["lifecycle_status"],
validation_status=row["validation_status"],
last_run_id=row.get("last_run_id"),
last_successful_run_id=row.get("last_successful_run_id"),
health=row.get("health", "none"),
baseline_compatibility=row.get("baseline_compatibility"),
last_modified_at=_parse_ts(row["last_modified_at"]),
created_at=_parse_ts(row["created_at"]),
))
for row in data["revisions"]:
session.add(ScenarioRevision(
revision_id=row["revision_id"],
scenario_id=row["scenario_id"],
content_hash=row["content_hash"],
parent_revision_id=row.get("parent_revision_id"),
graph_snapshot=row.get("graph_snapshot", {}),
execution_template_hash=row.get("execution_template_hash", ""),
template_version=row.get("template_version", "v1"),
schema_version=row.get("schema_version", 1),
compatibility_family=row.get("compatibility_family", "default"),
change_summary=row.get("change_summary", {}),
created_by=row["created_by"],
created_at=_parse_ts(row["created_at"]),
activation_status=row["activation_status"],
activated_by=row.get("activated_by"),
activated_at=_parse_ts(row.get("activated_at")),
activation_agent_action_id=row.get("activation_agent_action_id"),
))
for row in data["staleness_signals"]:
session.add(ScenarioStalenessSignal(
id=row["id"],
scenario_id=row["scenario_id"],
source_type=row["source_type"],
source_fingerprint=row["source_fingerprint"],
kind=row["kind"],
severity=row["severity"],
reason=row["reason"],
affected_ref=row["affected_ref"],
detected_at=_parse_ts(row["detected_at"]),
resolved_at=_parse_ts(row.get("resolved_at")),
))
session.commit()
# #region Test.ScenarioRegistry.Api.RegistryRouteEnv [C:2] [TYPE Class]
# @BRIEF Isolated in-memory SQLite app for one registry test: seed session + TestClient factory.
class RegistryRouteEnv:
def __init__(self):
self.engine = create_engine(
"sqlite:///:memory:",
poolclass=StaticPool,
connect_args={"check_same_thread": False},
)
event.listen(self.engine, "connect", lambda c, _: c.execute("PRAGMA foreign_keys=ON"))
from src.models.mapping import Base
Base.metadata.create_all(self.engine)
self.session_factory = sessionmaker(bind=self.engine)
def seed(self) -> None:
session = self.session_factory()
try:
_seed_registry(session)
finally:
session.close()
def client(self, *, admin: bool = True) -> TestClient:
app = FastAPI()
app.include_router(router)
def _override_db():
session = self.session_factory()
try:
yield session
finally:
session.close()
if admin:
admin_role = Role(id="admin-role-scenario-registry", name="Admin", is_admin=True)
user = User(id="test-user-scenario-registry", username="tester", email="tester@test.com")
user.roles = [admin_role]
app.dependency_overrides[get_current_user] = lambda: user
else:
from types import SimpleNamespace
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
id="u1", username="u1", roles=[]
)
app.dependency_overrides[get_db] = _override_db
return TestClient(app)
def close(self) -> None:
self.engine.dispose()
# #endregion Test.ScenarioRegistry.Api.RegistryRouteEnv
@pytest.fixture
def registry_route_env():
env = RegistryRouteEnv()
yield env
env.close()
# #region Test.ScenarioRegistry.Api.TestListRoutes [C:2] [TYPE Class]
class TestListRoutes:
"""GET /api/dashboard-testing/scenarios — list/search/filter/paginate."""
def test_list_returns_paged_envelope(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get("/api/dashboard-testing/scenarios")
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["total"] == 3
assert len(body["items"]) == 3
first = body["items"][0]
assert first["scenario_key"] == "fi-0042_sales-overview-smoke"
assert set(first) >= {
"scenario_id", "scenario_key", "name", "dashboard_id", "owner_username",
"tags", "lifecycle_status", "validation_status", "current_revision",
"metadata_version", "health", "last_modified_at", "created_at",
}
def test_empty_registry_returns_empty_state(self, registry_route_env):
resp = registry_route_env.client().get("/api/dashboard-testing/scenarios")
assert resp.status_code == 200
assert resp.json() == {"items": [], "total": 0}
def test_filter_by_dashboard(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
resp = client.get("/api/dashboard-testing/scenarios", params={"dashboard_id": 42})
assert resp.status_code == 200
body = resp.json()
assert body["total"] == 1
assert body["items"][0]["dashboard_id"] == 42
def test_filter_unknown_dashboard_yields_empty(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios", params={"dashboard_id": 999999}
)
assert resp.status_code == 200
assert resp.json() == {"items": [], "total": 0}
def test_filter_by_status_and_tag_and_owner(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
resp = client.get("/api/dashboard-testing/scenarios", params={"status": "READY"})
assert resp.json()["total"] == 1
resp = client.get("/api/dashboard-testing/scenarios", params={"tag": "filters"})
assert resp.json()["total"] == 2
resp = client.get("/api/dashboard-testing/scenarios", params={"owner": "dev.engineer"})
assert resp.json()["total"] == 1
def test_search_q(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios", params={"q": "cross-filter"}
)
assert resp.status_code == 200
assert resp.json()["total"] == 1
def test_pagination(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios", params={"page": 2, "page_size": 1}
)
assert resp.status_code == 200
body = resp.json()
assert body["total"] == 3
assert len(body["items"]) == 1
def test_invalid_paging_yields_422(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
assert client.get("/api/dashboard-testing/scenarios", params={"page": 0}).status_code == 422
assert client.get("/api/dashboard-testing/scenarios", params={"page_size": 101}).status_code == 422
assert client.get("/api/dashboard-testing/scenarios", params={"page_size": 0}).status_code == 422
def test_rbac_denied_returns_403(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client(admin=False).get("/api/dashboard-testing/scenarios")
assert resp.status_code == 403
# #endregion Test.ScenarioRegistry.Api.TestListRoutes
# #region Test.ScenarioRegistry.Api.TestDetailRoutes [C:2] [TYPE Class]
class TestDetailRoutes:
"""GET /api/dashboard-testing/scenarios/{scenario_id} — detail + 404 (fixes getScenarioDraft 404)."""
def test_detail_by_uuid(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333"
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["entry"]["scenario_key"] == "fi-0042_sales-overview-smoke"
assert body["graph"]["scenario_id"] == "fi-0042_sales-overview-smoke"
assert body["run_count"] == 0
assert body["refresh_required"] is False
def test_detail_by_slug(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/fi-0080_verify-filters-metric-xlsx"
)
assert resp.status_code == 200
body = resp.json()
assert body["entry"]["scenario_id"] == "11111111-1111-4111-8111-111111111111"
assert body["refresh_required"] is True
def test_detail_not_found_returns_404_envelope(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
)
assert resp.status_code == 404
body = resp.json()
assert body["detail"]["code"] == "NOT_FOUND"
def test_detail_empty_registry_returns_404(self, registry_route_env):
resp = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/11111111-1111-4111-8111-111111111111"
)
assert resp.status_code == 404
def test_detail_rbac_denied_returns_403(self, registry_route_env):
registry_route_env.seed()
resp = registry_route_env.client(admin=False).get(
"/api/dashboard-testing/scenarios/11111111-1111-4111-8111-111111111111"
)
assert resp.status_code == 403
# #endregion Test.ScenarioRegistry.Api.TestDetailRoutes
# #region Test.ScenarioRegistry.Api.TestCreateRoutes [C:2] [TYPE Class]
# @BRIEF POST Save→Register route binds only server-owned draft artifacts.
class TestCreateRoutes:
def test_create_registers_server_owned_pack(self, registry_route_env, monkeypatch):
import hashlib
pack = b"api-pack"
plan = b"api-plan"
pack_sha = hashlib.sha256(pack).hexdigest()
plan_sha = hashlib.sha256(plan).hexdigest()
session = registry_route_env.session_factory()
run = AgentRun(
id="api-create-run", user_id="test-user-scenario-registry", intent="dashboard_scenario_build",
trigger="manual", dashboard_id="42", environment_id="preprod", context_snapshot={}, status="COMPLETED",
)
session.add(run)
session.add(DraftArtifact(
id="api-pack-draft", run_id=run.id, kind="scenario_pack", name="scenario.yaml",
intended_path="dashboard-tests/api-smoke/scenario.yaml", content_ref="pack-ref", sha256=pack_sha,
validation_status="valid",
))
session.add(DraftArtifact(
id="api-plan-draft", run_id=run.id, kind="scenario_pack", name="runner.plan.json",
intended_path="dashboard-tests/api-smoke/runner.plan.json", content_ref="plan-ref", sha256=plan_sha,
validation_status="valid",
))
session.commit()
session.close()
class Storage:
@staticmethod
def retrieve(ref):
return pack if ref == "pack-ref" else plan
monkeypatch.setattr("src.services.dashboard_testing.registry.create.get_draft_storage", lambda: Storage())
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios",
json={
"compiled_handle_id": "compiled-api",
"draft_pack_id": "api-pack-draft",
"draft_pack_digest": pack_sha,
},
)
assert response.status_code == 201, response.text
body = response.json()
assert body["scenario_id"]
assert body["revision_id"]
assert body["materialization_status"] == "materialized"
def test_create_digest_mismatch_returns_conflict(self, registry_route_env, monkeypatch):
import hashlib
pack = b"api-pack"
pack_sha = hashlib.sha256(pack).hexdigest()
session = registry_route_env.session_factory()
run = AgentRun(
id="api-mismatch-run", user_id="test-user-scenario-registry", intent="dashboard_scenario_build",
trigger="manual", dashboard_id="42", environment_id="preprod", context_snapshot={}, status="COMPLETED",
)
session.add(run)
session.add(DraftArtifact(
id="api-mismatch-pack", run_id=run.id, kind="scenario_pack", name="scenario.yaml",
intended_path="dashboard-tests/api-mismatch/scenario.yaml", content_ref="mismatch-ref", sha256=pack_sha,
validation_status="valid",
))
session.add(DraftArtifact(
id="api-mismatch-plan", run_id=run.id, kind="scenario_pack", name="runner.plan.json",
intended_path="dashboard-tests/api-mismatch/runner.plan.json", content_ref="mismatch-plan", sha256=pack_sha,
validation_status="valid",
))
session.commit()
session.close()
class Storage:
@staticmethod
def retrieve(_ref):
return pack
monkeypatch.setattr("src.services.dashboard_testing.registry.create.get_draft_storage", lambda: Storage())
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios",
json={"compiled_handle_id": "compiled-api", "draft_pack_id": "api-mismatch-pack", "draft_pack_digest": "0" * 64},
)
assert response.status_code == 409
assert response.json()["detail"]["code"] == "REGISTRATION_CONFLICT"
# #endregion Test.ScenarioRegistry.Api.TestCreateRoutes
# #region Test.ScenarioRegistry.Api.TestRevisionRoutes [C:2] [TYPE Class]
# @BRIEF Verify immutable revision list, checkout, diff, and append routes.
class TestRevisionRoutes:
def test_revision_list_checkout_and_diff(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
base = "/api/dashboard-testing/scenarios/11111111-1111-4111-8111-111111111111"
response = client.get(f"{base}/revisions")
assert response.status_code == 200
assert [row["revision_id"] for row in response.json()] == [
"22222222-2222-4222-8222-222222222222",
"77777777-7777-4777-8777-777777777777",
]
response = client.get(f"{base}/revisions/22222222-2222-4222-8222-222222222222")
assert response.status_code == 200
assert response.json()["is_current"] is True
response = client.get(
f"{base}/revisions/22222222-2222-4222-8222-222222222222/diff/77777777-7777-4777-8777-777777777777"
)
assert response.status_code == 200
assert response.json()["changed"][0]["key"] == "revision_hash"
def test_revision_append_keeps_current_pointer(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
response = client.post(
"/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333/revisions",
json={
"graph_snapshot": {"scenario_id": "fi-0042_sales-overview-smoke", "changed": True},
"base_revision_id": "44444444-4444-4444-8444-444444444444",
},
)
assert response.status_code == 410, response.text
assert response.json()["code"] == "REVISIONS_RAW_GRAPH_RETIRED"
# #endregion Test.ScenarioRegistry.Api.TestRevisionRoutes
# #region Test.ScenarioRegistry.Api.TestLifecycleRoutes [C:2] [TYPE Class]
# @BRIEF Verify lifecycle transition, clone, archive and restore endpoints.
class TestLifecycleRoutes:
def test_transition_archive_restore(self, registry_route_env):
registry_route_env.seed()
client = registry_route_env.client()
base = "/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333"
response = client.post(f"{base}/transition", json={"target_state": "READY", "reason": "validated"})
assert response.status_code == 200
assert response.json()["lifecycle_status"] == "READY"
response = client.post(f"{base}/archive", json={"reason": "retire"})
assert response.status_code == 200
assert response.json()["lifecycle_status"] == "ARCHIVED"
response = client.post(f"{base}/restore", json={"reason": "reopen"})
assert response.status_code == 200
assert response.json()["lifecycle_status"] == "DRAFT"
def test_clone_creates_distinct_scenario(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios/11111111-1111-4111-8111-111111111111/clone"
)
assert response.status_code == 201
body = response.json()
assert body["scenario_id"] != "11111111-1111-4111-8111-111111111111"
assert body["revision_id"]
def test_illegal_transition_returns_conflict(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333/transition",
json={"target_state": "ARCHIVED", "reason": "not directly from draft"},
)
assert response.status_code == 200
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333/transition",
json={"target_state": "READY", "reason": "invalid after archive"},
)
assert response.status_code == 409
# #endregion Test.ScenarioRegistry.Api.TestLifecycleRoutes
# #region Test.ScenarioRegistry.Api.TestHealthRoutes [C:2] [TYPE Class]
# @BRIEF Verify read-only health projection endpoint.
class TestHealthRoutes:
def test_health_projection(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/33333333-3333-4333-8333-333333333333/health"
)
assert response.status_code == 200
assert response.json()["health"] == "none"
assert response.json()["source"] == "analytics_projection"
def test_missing_health_is_not_found(self, registry_route_env):
response = registry_route_env.client().get("/api/dashboard-testing/scenarios/missing/health")
assert response.status_code == 404
# #endregion Test.ScenarioRegistry.Api.TestHealthRoutes
# #region Test.ScenarioEditor.Api.TestLoadRoute [C:2] [TYPE Class]
# @BRIEF Verify the read-only revision-bound editor projection route.
class TestEditorLoadRoute:
def test_editor_load_is_clean_and_revision_bound(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().get(
"/api/dashboard-testing/scenarios/fi-0042_sales-overview-smoke/edit"
)
assert response.status_code == 200
body = response.json()
assert body["dirty"] is False
assert body["base_revision_id"] == "44444444-4444-4444-8444-444444444444"
def test_editor_load_missing_scenario_is_not_found(self, registry_route_env):
response = registry_route_env.client().get("/api/dashboard-testing/scenarios/missing/edit")
assert response.status_code == 404
# #endregion Test.ScenarioEditor.Api.TestLoadRoute
# #region Test.ScenarioEditor.Api.TestRevalidateRoute [C:2] [TYPE Class]
# @BRIEF Verify stale scenario migration proposal endpoint.
class TestEditorRevalidateRoute:
def test_revalidate_returns_read_only_proposal(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios/55555555-5555-4555-8555-555555555555/revalidate",
params={"base_revision_id": "66666666-6666-4666-8666-666666666666"},
)
assert response.status_code == 200
assert response.json()["conflicts"]
def test_revalidate_ready_scenario_returns_conflict(self, registry_route_env):
registry_route_env.seed()
response = registry_route_env.client().post(
"/api/dashboard-testing/scenarios/11111111-1111-4111-8111-111111111111/revalidate",
params={"base_revision_id": "22222222-2222-4222-8222-222222222222"},
)
assert response.status_code == 409
# #endregion Test.ScenarioEditor.Api.TestRevalidateRoute
# #endregion Test.ScenarioRegistry.Api