Files
ss-tools/backend/tests/api/test_scenario_runs_api.py

988 lines
48 KiB
Python

# #region Test.ScenarioExecution.Api [C:3] [TYPE Module] [SEMANTICS test,api,scenario,run,start,sse,compare,resume,rbac,prod]
# @defgroup ScenarioExecution Test.Api full scenario-runs API (044 T018/T019).
# @RELATION VERIFIES -> [Api.ScenarioExecution.Routes]
# @RELATION VERIFIES -> [Api.ScenarioExecution.Routes.Start]
# @RELATION VERIFIES -> [Api.ScenarioExecution.Routes.ApprovalDecision]
# @TEST_CONTRACT: Persisted ScenarioRun frontier + HumanCheckpoint or infrastructure token -> resumed DAG result without re-running completed steps
# @TEST_INVARIANT Api.ScenarioExecution.Routes: Static /compare remains registered before /{run_id}.
# -> VERIFIED_BY: test_compare_is_not_shadowed_by_run_id
# @TEST_INVARIANT Api.ScenarioExecution.Routes.Start: HTTP start/replay is persistence-only: it
# requires scenario:run (and scenario:run:prod for PROD), returns only a durable
# queued/pending row, and creates no step/lease/notification/queue side effect.
# -> VERIFIED_BY: test_start_creates_run_201, test_idempotent_replay_returns_same_run,
# test_rbac_denied_403, test_prod_start_requires_run_prod_when_body_says_false,
# test_prod_start_with_run_prod_creates_pending_approval
# @TEST_INVARIANT ScenarioExecution.EnvironmentPolicy: ConfigManager, never request is_prod,
# classifies PROD before RBAC/gate creation; unknown environments have no run-side
# effect. -> VERIFIED_BY: test_prod_start_requires_run_prod_when_body_says_false,
# test_preprod_true_body_stays_queued, test_prod_replay_ignores_body_classification,
# test_unknown_environment_has_no_run_side_effect
# @TEST_INVARIANT Api.ScenarioExecution.Routes.ApprovalDecision: PROD approval decisions require
# the gate's dedicated scenario:run_prod authority. -> VERIFIED_BY:
# test_approve_prod_gate_queues_run_and_replay_conflicts,
# test_approval_decision_requires_run_prod
# @TEST_INVARIANT ScenarioExecution.Runner.ContinueAfterHuman: A confirmed checkpoint continues
# only dependent saved-frontier steps; completed local deterministic steps stay attempt 1.
# -> VERIFIED_BY: test_human_confirm_resumes_dependents_without_rerunning_completed_steps
# @TEST_INVARIANT ScenarioExecution.Runner.ContinueAfterInfrastructureResume: A valid one-time
# resume token continues only the saved frontier; stale/replayed tokens reject.
# -> VERIFIED_BY: test_infrastructure_resume_continues_saved_frontier_without_rerunning_completed_step
# @TEST_EDGE static_compare_before_dynamic_run_id; idempotent_replay; changed_request_409;
# stale_revision_409; rbac_403; prod_requires_run_prod; sse_replay_via_last_event_id;
# human_checkpoint_resume_409
# @TEST_FIXTURE graph/run_states -> specs/044-dashboard-scenario-execution/fixtures (materialized under tests/fixtures/scenario_execution/)
# @RATIONALE A standalone FastAPI app uses the explicitly selected migrated PostgreSQL and per-test outer rollback; request commits release savepoints. Exact authored publication receipts exercise consumer admission, not Git publication.
from __future__ import annotations
import json
from pathlib import Path
import pytest
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from uuid import uuid4
from datetime import UTC, datetime
from src.api.routes.dashboard_testing.scenario_runs import history_router, runs_router
from src.core.database import get_db
from src.dependencies import get_config_manager, get_current_user, get_current_user_browser_stream
from src.models.auth import Permission, Role, User
from src.models.scenario_run import ScenarioRun
from src.services.dashboard_testing.scenario.templates import (
ACTION_REGISTRY_VERSION,
action_registry_fingerprint,
resolve_action_descriptor,
)
_FIXTURE_DIR = Path(__file__).resolve().parents[1] / "fixtures" / "scenario_execution"
_SCENARIO = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1"
_REV_CURRENT = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1"
_REV_STALE = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2"
_RUN_1 = "run-exec-0001"
_RUN_2 = "run-exec-0002"
def _action_step(step_id: str, tool: str, action: str, **extra) -> dict:
return {
"logical_step_id": step_id,
"tool": tool,
"action": action,
"action_descriptor": resolve_action_descriptor(
tool=tool, action=action, registry_version=ACTION_REGISTRY_VERSION,
registry_hash=action_registry_fingerprint(),
).snapshot(),
**extra,
}
def _assertion_step(step_id: str, value: str) -> dict:
# Authored deterministic comparison inputs, never live capture evidence.
normalized = {"kind": "chart_response", "canonical_value": json.dumps({
"schema_version": 1, "queries": [{"query_index": 0, "query_sha256": "a" * 64,
"adapter": {"adapter_id": "fixed_aggregate", "policy_contract": "chart_query_columns",
"normalization_contract": "fixed_aggregate"}, "from_dttm": None, "to_dttm": None,
"columns": ["fixture_value"], "rows": [[value]]}]})}
return _action_step(step_id, "assertion", "structural_assert", actual=normalized, expected=normalized,
policy={"type": "chart_response", "query_policies": [{"query_index": 0,
"query_sha256": "a" * 64, "key_columns": [], "per_column": {"fixture_value": {"type": "exact"}}}]})
_HUMAN_CONTINUATION_GRAPH = {
"schema_version": 1,
"action_registry_version": ACTION_REGISTRY_VERSION,
"action_registry_hash": action_registry_fingerprint(),
"environment_ids": ["env-preprod-02"],
"steps": [
_assertion_step("before_human", "11"),
_action_step("human_signoff", "human", "human_checkpoint"),
_assertion_step("after_human", "7"),
],
"dependencies": [
{"source": "before_human", "target": "human_signoff"},
{"source": "human_signoff", "target": "after_human"},
],
}
_INFRA_RESUME_GRAPH = {
"schema_version": 1,
"action_registry_version": ACTION_REGISTRY_VERSION,
"action_registry_hash": action_registry_fingerprint(),
"environment_ids": ["env-preprod-02"],
"steps": [
_action_step("before_resume", "browser", "open_dashboard", session_id="fixture-browser-session"),
_assertion_step("after_resume", "7"),
],
"dependencies": [{"source": "before_resume", "target": "after_resume"}],
}
# #region Test.ScenarioExecution.Api.ExactCatalog [C:3] [TYPE Function]
# @TEST_INVARIANT Explicit source environment/dashboard and exact PostgreSQL revision reach the real resolver.
# @RATIONALE A matching authored DB publication receipt tests consumer admission; it is not real Git publication proof.
def _catalog_fixture(db, environment_id):
from tests.services.dashboard_testing.execution.pg_consumer_fixture import literal_wrapper, digest, STAMP
from src.models.publication_operation import PublicationOperation
from src.schemas.dashboard_testing import BaselineEntry
from src.schemas.dashboard_testing.catalog_revision import CatalogEntryRevision, CatalogRevisionOperation, ExactCatalogRevision
from src.services.dashboard_testing.catalog_revision_wiring import build_entry_revisions
from src.services.dashboard_testing.catalog_store import seed_catalog, append_catalog_revision, render_catalog_revision
raw = literal_wrapper()
raw["entry"]["dashboard_id"] = 80
raw["entry"]["provenance"]["environment"] = environment_id
source = raw["reference_source"]
source["dashboard_id"] = 80
source["environment_id"] = environment_id
source["reference_digest"] = digest({key: source[key] for key in (
"environment_id", "dashboard_id", "resolved_native_filters", "filters_hash", "query_model_fingerprint")})
entry = BaselineEntry.model_validate_json(json.dumps(raw["entry"]))
wrapped = build_entry_revisions(entry, {"reference_source": source,
"capture_artifact_id": raw["capture_artifact_id"], "capture_profile_sha256": raw["capture_profile_hash"]})[0]
wrapper = CatalogEntryRevision.model_validate_json(json.dumps(wrapped))
repository = str(uuid4())
seeded = seed_catalog(db, repository=repository, dashboard_key="dashboard-80", actor_id="fixture",
reason="Exact API catalog fixture", idempotency_key=str(uuid4()))
snapshot = append_catalog_revision(db, catalog_id=seeded.revision.catalog_id,
expected_revision_id=seeded.revision.catalog_revision_id, expected_cas=1,
entries=(wrapper,), observatory_entries=(), release_id=str(uuid4()), baseline_family="5" * 64,
actor_id="fixture", reason="Current API start fixture",
operation=CatalogRevisionOperation(kind="approval_consume", invocation_id=str(uuid4()), request_sha256="6" * 64))
selector = ExactCatalogRevision(kind="revision", catalog_id=snapshot.revision.catalog_id,
catalog_revision_id=snapshot.revision.catalog_revision_id)
render = render_catalog_revision(db, selector)
commit = "7" * 40
db.add(PublicationOperation(id=str(uuid4()), idempotency_key=str(uuid4()),
catalog_revision_id=selector.catalog_revision_id, render_sha256=render.render_sha256,
catalog_digest=snapshot.revision.catalog_digest, repository=repository,
destination={"base_url":"https://git.test", "repository":"fixture/catalog", "branch":"main", "path":render.path},
branch="main", expected_branch_head="8" * 40, state="published", commit_sha=commit,
published_receipt={"catalog_revision_id":selector.catalog_revision_id, "render_sha256":render.render_sha256,
"integrity_sha256":snapshot.integrity_sha256, "commit_sha":commit, "head_after":commit, "verified_at":STAMP},
attempts=1, actor="fixture", created_at=datetime.now(UTC), updated_at=datetime.now(UTC)))
db.commit()
return selector, snapshot
# #endregion Test.ScenarioExecution.Api.ExactCatalog
def _seed(session) -> None:
from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision
from src.models.scenario_run import ScenarioRun, ScenarioStepRun
graph = json.loads((_FIXTURE_DIR / "graph.json").read_text(encoding="utf-8"))
run_states = json.loads((_FIXTURE_DIR / "run_states.json").read_text(encoding="utf-8"))
def _ts(value):
return __import__("datetime").datetime.fromisoformat(value.replace("Z", "+00:00"))
session.add(ScenarioRegistryEntry(
scenario_id=_SCENARIO, scenario_key="fi-0080_execution-fixture", name="Execution fixture", # gitleaks:allow
description="canonical", dashboard_id=80, environment_ids=["env-preprod-02"],
# Owned by the non-admin RUN/RUN_PROD principal used by _user_with, so the object ACL lets
# the PROD-gate tests exercise 403/approval instead of collapsing to a 404 foreign run.
owner_id="user-scenario-run", owner_username="runner", tags=["execution"],
metadata_version="etag-exec-001", lifecycle_status="READY", validation_status="valid",
current_revision_id=_REV_CURRENT,
last_modified_at=_ts("2026-08-05T08:00:00+00:00"), created_at=_ts("2026-08-01T08:00:00+00:00"),
))
session.add(ScenarioRevision(
revision_id=_REV_CURRENT, scenario_id=_SCENARIO, content_hash="d" * 64,
graph_snapshot=graph, template_version="v1", schema_version=1,
created_by="fixture", activation_status="current",
created_at=_ts("2026-08-05T08:00:00+00:00"),
))
session.add(ScenarioRevision(
revision_id=_REV_STALE, scenario_id=_SCENARIO, content_hash="e" * 64,
graph_snapshot=graph, template_version="v1", schema_version=1,
created_by="fixture", activation_status="candidate",
created_at=_ts("2026-08-04T08:00:00+00:00"),
))
for run_row in run_states["runs"]:
session.add(ScenarioRun(
id=run_row["id"], scenario_id=run_row["scenario_id"],
scenario_revision_id=run_row["scenario_revision_id"],
scenario_content_hash=run_row["scenario_content_hash"],
environment_id=run_row["environment_id"], status=run_row["status"],
phase=run_row["phase"],
parameter_bindings=run_row.get("parameter_bindings", {}),
target_snapshot=run_row.get("target_snapshot", {}),
trigger_source=run_row.get("trigger_source", "manual"),
idempotency_key=run_row["idempotency_key"],
request_hash=run_row.get("request_hash"),
runner_plan=run_row.get("runner_plan", {}),
execution_principal_fingerprint=run_row.get("execution_principal_fingerprint"),
created_at=_ts(run_row["created_at"]),
started_at=_ts(run_row.get("started_at")),
finished_at=_ts(run_row.get("finished_at")),
))
for step_row in run_row.get("steps", []):
session.add(ScenarioStepRun(
id=step_row["id"], run_id=run_row["id"],
logical_step_id=step_row["logical_step_id"],
step_position=step_row["step_position"], attempt=step_row["attempt"],
status=step_row["status"],
inputs_snapshot=step_row.get("inputs_snapshot", {}),
outputs=step_row.get("outputs", {}),
artifact_refs=step_row.get("artifact_refs", []),
progress=step_row.get("progress", 0),
error_code=step_row.get("error_code"),
step_outcome=step_row.get("step_outcome", {}),
))
session.commit()
def _user_with(*perms: tuple[str, str]) -> User:
role = Role(id="role-scenario-run", name="ScenarioRunner", is_admin=False)
role.permissions = [Permission(resource=r, action=a) for r, a in perms]
user = User(id="user-scenario-run", username="runner", email="runner@test.com")
user.roles = [role]
return user
class RunRouteEnv:
def __init__(self, *, admin: bool = True, user: User | None = None):
from tests.services.dashboard_testing.execution.pg_consumer_fixture import connection_url
self.engine = create_engine(connection_url())
self.connection = self.engine.connect()
self.transaction = self.connection.begin()
self.session_factory = sessionmaker(bind=self.connection, join_transaction_mode="create_savepoint")
self.catalogs = {}
self.admin = admin
self.user = user
self.config_manager = SimpleNamespace(
get_environment=lambda environment_id: {
"env-preprod-02": SimpleNamespace(
stage="PREPROD", is_production=False
),
"env-prod-01": SimpleNamespace(stage="PROD", is_production=True),
}.get(environment_id)
)
def seed(self) -> None:
session = self.session_factory()
try:
_seed(session)
for environment_id in ("env-preprod-02", "env-prod-01"):
self.catalogs[environment_id] = _catalog_fixture(session, environment_id)
finally:
session.close()
def start_body(self, *, environment_id="env-preprod-02", **overrides) -> dict:
selector, _ = self.catalogs[environment_id]
body = {"scenario_id": _SCENARIO, "revision_id": _REV_CURRENT, "environment_id": environment_id,
"params": {}, "catalog_id": selector.catalog_id, "catalog_revision_id": selector.catalog_revision_id}
body.update(overrides)
return body
def client(self) -> TestClient:
app = FastAPI()
app.include_router(runs_router)
app.include_router(history_router)
def _override_db():
session = self.session_factory()
try:
yield session
finally:
session.close()
if self.admin:
admin_role = Role(id="admin-role-scenario-runs", name="Admin", is_admin=True)
user = User(id="test-user-scenario-runs", username="tester", email="tester@test.com")
user.roles = [admin_role]
elif self.user is not None:
user = self.user
else:
user = SimpleNamespace(id="u1", username="u1", roles=[])
app.dependency_overrides[get_current_user] = lambda: user
# The SSE events route authenticates via the browser-stream resolver (?token= fallback);
# override it too so the route contract is exercised without a real JWT.
app.dependency_overrides[get_current_user_browser_stream] = lambda: user
app.dependency_overrides[get_db] = _override_db
app.dependency_overrides[get_config_manager] = lambda: self.config_manager
return TestClient(app)
def close(self) -> None:
self.transaction.rollback()
self.connection.close()
self.engine.dispose()
@pytest.fixture
def route_env():
env = RunRouteEnv()
env.seed()
yield env
env.close()
# #region Test.ScenarioExecution.Api.TestStart [C:2] [TYPE Class]
class TestStart:
def test_start_creates_run_201(self, route_env):
resp = route_env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-1"},
json=route_env.start_body(params={"region": "emea"}),
)
assert resp.status_code == 201, resp.text
body = resp.json()
assert body["status"] == "queued"
assert body["scenario_revision_id"] == _REV_CURRENT
assert body["scenario_content_hash"] == "d" * 64
assert body["runner_plan"]["topological_order"][0] == "s1_setup_filters"
selector, snapshot = route_env.catalogs["env-preprod-02"]
pin = body["runner_plan"]["baseline_pin"]
assert pin["catalog_id"] == selector.catalog_id
assert pin["catalog_revision_id"] == selector.catalog_revision_id
assert body["target_snapshot"]["baseline_pin"] == pin
assert pin["catalog_digest"] == snapshot.revision.catalog_digest
assert pin["entries"][0]["reference_source"]["environment_id"] == "env-preprod-02"
assert pin["entries"][0]["reference_source"]["dashboard_id"] == 80
def test_start_without_baseline_set_is_422(self, route_env):
from src.models.scenario_registry import ScenarioRevision
with route_env.session_factory() as db:
revision = db.get(ScenarioRevision, _REV_CURRENT)
revision.graph_snapshot = {**revision.graph_snapshot, "baselines": {"revenue": {"reference": "explicit-required"}}}
db.commit()
resp = route_env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-missing-set"},
json={
"scenario_id": _SCENARIO,
"revision_id": _REV_CURRENT,
"environment_id": "env-preprod-02",
"params": {},
},
)
assert resp.status_code == 422
assert resp.json()["detail"]["code"] == "BASELINE_MISSING"
def test_start_rejects_release_different_from_published_baseline_before_run(self, route_env):
response = route_env.client().post(
"/api/scenario-runs", headers={"Idempotency-Key": "start-mismatched-release"},
json=route_env.start_body(dashboard_release_id="foreign-release"),
)
assert response.status_code == 422
assert response.json()["detail"]["code"] == "BASELINE_STALE"
with route_env.session_factory() as db:
assert db.query(ScenarioRun).filter_by(idempotency_key="start-mismatched-release").count() == 0
def test_idempotent_replay_returns_same_run(self, route_env):
from src.models.scenario_automation import ScenarioNotificationEvent
from src.models.scenario_investigation import InvestigationQueueItem
from src.models.scenario_run import ScenarioStepRun
client = route_env.client()
payload = route_env.start_body()
first = client.post("/api/scenario-runs", headers={"Idempotency-Key": "start-2"}, json=payload)
second = client.post("/api/scenario-runs", headers={"Idempotency-Key": "start-2"}, json=payload)
assert first.status_code == 201 and second.status_code == 201
assert first.json()["id"] == second.json()["id"]
session = route_env.session_factory()
try:
run_id = first.json()["id"]
assert session.query(ScenarioStepRun).filter_by(run_id=run_id).count() == 0
assert session.query(InvestigationQueueItem).filter_by(run_id=run_id).count() == 0
assert session.query(ScenarioNotificationEvent).filter_by(run_id=run_id).count() == 0
finally:
session.close()
def test_changed_request_same_key_409(self, route_env):
client = route_env.client()
payload = route_env.start_body(params={"a": 1})
client.post("/api/scenario-runs", headers={"Idempotency-Key": "start-3"}, json=payload)
resp = client.post(
"/api/scenario-runs", headers={"Idempotency-Key": "start-3"},
json={**payload, "params": {"a": 2}},
)
assert resp.status_code == 409
assert resp.json()["detail"]["code"] == "IDEMPOTENCY_KEY_REUSED"
def test_stale_revision_409(self, route_env):
resp = route_env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-4"},
json=route_env.start_body(revision_id=_REV_STALE),
)
assert resp.status_code == 409
assert "revision mismatch" in resp.json()["detail"]["detail"]
def test_rbac_denied_403(self):
env = RunRouteEnv(admin=False)
env.seed()
try:
resp = env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-5"},
json=env.start_body(),
)
assert resp.status_code == 403
finally:
env.close()
def test_prod_start_requires_run_prod_when_body_says_false(self):
env = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN")))
env.seed()
try:
resp = env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-prod-1"},
json=env.start_body(environment_id="env-prod-01", is_prod=False),
)
assert resp.status_code == 403
finally:
env.close()
def test_prod_start_with_run_prod_creates_pending_approval(self):
env = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN"), ("scenario", "RUN_PROD")))
env.seed()
try:
resp = env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-prod-2"},
json=env.start_body(environment_id="env-prod-01", is_prod=False),
)
assert resp.status_code == 201, resp.text
assert resp.json()["status"] == "pending_approval"
finally:
env.close()
def test_preprod_true_body_stays_queued(self, route_env):
response = route_env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-preprod-true-044"},
json=route_env.start_body(is_prod=True),
)
assert response.status_code == 201, response.text
assert response.json()["status"] == "queued"
def test_prod_replay_ignores_body_classification(self):
from src.models.scenario_approval import ActionApprovalGate
from src.models.scenario_run import ScenarioStepRun
env = RunRouteEnv(
admin=False,
user=_user_with(("scenario", "RUN"), ("scenario", "RUN_PROD")),
)
env.seed()
try:
client = env.client()
payload = env.start_body(
environment_id="env-prod-01",
params={"hardcoded": "prod-replay-044"},
)
first = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-prod-replay-class-044"},
json={**payload, "is_prod": False},
)
second = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-prod-replay-class-044"},
json={**payload, "is_prod": True},
)
assert first.status_code == 201, first.text
assert second.status_code == 201, second.text
assert first.json()["id"] == second.json()["id"]
assert second.json()["status"] == "pending_approval"
session = env.session_factory()
try:
run_id = first.json()["id"]
assert session.query(ActionApprovalGate).filter_by(owner_id=run_id).count() == 1
assert session.query(ScenarioStepRun).filter_by(run_id=run_id).count() == 0
finally:
session.close()
finally:
env.close()
def test_unknown_environment_has_no_run_side_effect(self, route_env):
session = route_env.session_factory()
try:
before = session.query(ScenarioRun).count()
finally:
session.close()
response = route_env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "start-unknown-environment-044"},
json={**route_env.start_body(), "environment_id": "env-unknown-044"},
)
assert response.status_code == 422
assert response.json()["detail"]["code"] == "ENVIRONMENT_NOT_CONFIGURED"
session = route_env.session_factory()
try:
assert session.query(ScenarioRun).count() == before
finally:
session.close()
# #endregion Test.ScenarioExecution.Api.TestStart
# #region Test.ScenarioExecution.Api.TestApprovalDecision [C:2] [TYPE Class] [SEMANTICS test,api,scenario,run,approval,gate,rbac]
# @BRIEF Verify the durable PROD ActionApprovalGate transition and its dedicated RUN_PROD authority.
class TestApprovalDecision:
def test_approve_prod_gate_queues_run_and_replay_conflicts(self):
env = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN"), ("scenario", "RUN_PROD")))
env.seed()
try:
client = env.client()
created = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "approval-prod-1"},
json=env.start_body(environment_id="env-prod-01", is_prod=True),
)
assert created.status_code == 201, created.text
run_id = created.json()["id"]
decided = client.post(
f"/api/scenario-runs/{run_id}/approval/decision",
json={"decision": "approve", "comment": "approved fixture"},
)
assert decided.status_code == 200, decided.text
assert decided.json()["status"] == "approved"
assert decided.json()["run_status"] == "queued"
assert decided.json()["required_permission"] == "scenario:run_prod"
replay = client.post(
f"/api/scenario-runs/{run_id}/approval/decision",
json={"decision": "approve"},
)
assert replay.status_code == 409
assert replay.json()["detail"]["code"] == "GATE_ALREADY_DECIDED"
finally:
env.close()
def test_approval_decision_requires_run_prod(self):
creator = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN"), ("scenario", "RUN_PROD")))
creator.seed()
try:
created = creator.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "approval-prod-2"},
json=creator.start_body(environment_id="env-prod-01", is_prod=True),
)
run_id = created.json()["id"]
creator.user = _user_with(("scenario", "RUN"))
denied = creator.client().post(
f"/api/scenario-runs/{run_id}/approval/decision",
json={"decision": "approve"},
)
assert denied.status_code == 403
finally:
creator.close()
# #endregion Test.ScenarioExecution.Api.TestApprovalDecision
# #region Test.ScenarioExecution.Api.TestDetailHistory [C:2] [TYPE Class]
class TestDetailHistory:
def test_get_run_200_and_404(self, route_env):
client = route_env.client()
ok = client.get(f"/api/scenario-runs/{_RUN_1}")
assert ok.status_code == 200
assert ok.json()["id"] == _RUN_1
assert ok.json()["status"] == "failed"
missing = client.get("/api/scenario-runs/no-such-run")
assert missing.status_code == 404
assert missing.json()["detail"]["code"] == "RUN_NOT_FOUND"
def test_history_lists_scenario_runs_newest_first(self, route_env):
resp = route_env.client().get(f"/api/scenarios/{_SCENARIO}/runs")
assert resp.status_code == 200
runs = resp.json()
assert [r["id"] for r in runs] == [_RUN_2, _RUN_1]
def test_history_unknown_scenario_empty(self, route_env):
resp = route_env.client().get("/api/scenarios/00000000-0000-4000-8000-000000000000/runs")
assert resp.status_code == 200
assert resp.json() == []
def test_foreign_run_is_indistinguishable_from_missing(self):
"""SEC-01: a RUN/RUN_PROD holder without scenario ownership cannot read a foreign run."""
from src.models.scenario_registry import ScenarioRegistryEntry
from src.models.scenario_run import ScenarioRun
env = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN"), ("scenario", "RUN_PROD")))
env.seed()
try:
session = env.session_factory()
try:
# A real foreign scenario owned by a different principal, so the run satisfies its
# FK while remaining outside the caller's owned set.
session.add(ScenarioRegistryEntry(
scenario_id="foreign-scenario", scenario_key="foreign-key", name="Foreign",
description="foreign", dashboard_id=81, environment_ids=["env-preprod-02"],
owner_id="other-owner", owner_username="other.owner", tags=[],
metadata_version="m-foreign", lifecycle_status="READY", validation_status="valid",
current_revision_id=_REV_CURRENT,
))
session.add(ScenarioRun(
id="foreign-run-044", scenario_id="foreign-scenario", scenario_revision_id=_REV_CURRENT,
scenario_content_hash="f" * 64, environment_id="env-preprod-02", status="failed",
phase="terminal", trigger_source="manual", idempotency_key="foreign-1",
))
session.commit()
finally:
session.close()
client = env.client()
detail = client.get("/api/scenario-runs/foreign-run-044")
assert detail.status_code == 404
assert detail.json()["detail"]["code"] == "RUN_NOT_FOUND"
assert client.get("/api/scenario-runs/foreign-run-044/result").status_code == 404
assert client.get("/api/scenario-runs/foreign-run-044/events").status_code == 404
assert client.get("/api/scenarios/foreign-scenario/runs").json() == []
finally:
env.close()
def test_start_rejects_foreign_scenario(self):
"""SEC-01: starting a run for an unowned scenario is a 404, not a queued run."""
env = RunRouteEnv(admin=False, user=_user_with(("scenario", "RUN")))
env.seed()
try:
resp = env.client().post(
"/api/scenario-runs",
headers={"Idempotency-Key": "foreign-start-044"},
json={**env.start_body(), "scenario_id": "foreign-scenario"},
)
assert resp.status_code == 404
assert resp.json()["detail"]["code"] == "SCENARIO_NOT_FOUND"
finally:
env.close()
# #endregion Test.ScenarioExecution.Api.TestDetailHistory
# #region Test.ScenarioExecution.Api.TestCompare [C:2] [TYPE Class]
class TestCompare:
def test_compare_is_not_shadowed_by_run_id(self, route_env):
"""Route ordering: /compare is static and must not be captured by /{run_id}."""
resp = route_env.client().get(f"/api/scenario-runs/compare?run_a={_RUN_1}&run_b={_RUN_2}")
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["run_a"] == _RUN_1 and body["run_b"] == _RUN_2
assert body["revision_warning"] is True # fixture runs pin b1 vs b2
assert body["compatibility"]["same_scenario"] is True
assert len(body["step_deltas"]) == 6
def test_compare_step_delta_flags_changed(self, route_env):
resp = route_env.client().get(f"/api/scenario-runs/compare?run_a={_RUN_1}&run_b={_RUN_2}")
deltas = {d["logical_step_id"]: d for d in resp.json()["step_deltas"]}
assert deltas["s3_export_xlsx"]["status_a"] == "failed"
assert deltas["s3_export_xlsx"]["status_b"] == "passed"
assert deltas["s3_export_xlsx"]["changed"] is True
assert deltas["s1_setup_filters"]["changed"] is False
def test_compare_missing_run_404(self, route_env):
resp = route_env.client().get(f"/api/scenario-runs/compare?run_a={_RUN_1}&run_b=nope")
assert resp.status_code == 404
assert resp.json()["detail"]["code"] == "RUN_NOT_FOUND"
# #endregion Test.ScenarioExecution.Api.TestCompare
# #region Test.ScenarioExecution.Api.TestResult [C:2] [TYPE Class]
class TestResult:
def test_result_has_aggregation_provenance_snapshot(self, route_env):
resp = route_env.client().get(f"/api/scenario-runs/{_RUN_1}/result")
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["status"] == "failed"
assert body["step_counts"] == {"passed": 2, "failed": 1, "blocked": 2, "inconclusive": 0}
assert body["provenance"]["scenario_revision_id"] == _REV_CURRENT
assert body["provenance"]["scenario_content_hash"] == "d" * 64
assert len(body["snapshot"]["steps"]) == 6
assert len(body["snapshot"]["snapshot_hash"]) == 64
# #region Test.ScenarioExecution.Api.CapabilityRefusal [C:3] [TYPE Test]
# @TEST_INVARIANT Actual provider/transform outcome survives SQL retention and REST as nonPASS with exact UI-shared projection; no SDK I/O or fake result evidence.
@pytest.mark.parametrize("provider", ["sdk", "transform"])
def test_actual_capability_refusal_is_persisted_and_projected(self, route_env, monkeypatch, provider):
from unittest.mock import AsyncMock
import src.core.database as database
from src.models.scenario_run import ScenarioStepRun
from src.models.provider_operation import ProviderOperationReceipt
from src.services.dashboard_testing.execution.executors import superset_api
from src.services.dashboard_testing.execution.offline_executors import bounded_transform
from src.services.dashboard_testing.execution.walker_publication import _retain_step_outcome
from src.services.dashboard_testing.execution.live_binding import LiveExecutionBinding, superset_adapter_from
from tests.services.dashboard_testing.registry.test_provider_superset import _BINDING, _STEP, _Resolver, _resolved, _EvidenceStore
fixture = json.loads((_FIXTURE_DIR / "capability_refusal_projection.json").read_text())
expected = next(item for item in fixture["cases"] if item["provider"] == provider)
run_id = expected["result"]["run_id"]
step_id = expected["step"]["logical_step_id"]
monkeypatch.setattr(database, "SessionLocal", route_env.session_factory)
client = AsyncMock()
if provider == "sdk":
binding = LiveExecutionBinding.from_snapshot(_BINDING)
resolver = _Resolver(_resolved(binding, client, _EvidenceStore()))
outcome = superset_api({**_STEP, "scenario_run_id": run_id, "logical_step_id": step_id}, {},
adapter=superset_adapter_from(resolver))
else:
outcome = bounded_transform({"scenario_run_id": run_id, "logical_step_id": step_id}, {})
with route_env.session_factory() as db:
run = ScenarioRun(id=run_id, scenario_id=_SCENARIO, scenario_revision_id=_REV_CURRENT,
scenario_content_hash="d" * 64, environment_id="env-preprod-02", status="inconclusive",
phase="execution", idempotency_key=run_id, runner_plan={})
step = ScenarioStepRun(id=expected["step"]["id"], run_id=run_id, logical_step_id=step_id,
step_position=0, attempt=1, status="running", inputs_snapshot={}, outputs={}, artifact_refs=[])
db.add_all([run, step])
retained, integrity = _retain_step_outcome(db, run, step, step_id, outcome)
assert retained == outcome
assert integrity is None
db.commit()
response = route_env.client().get(f"/api/scenario-runs/{run_id}/result")
assert response.status_code == 200
body = response.json()
assert {key: body[key] for key in expected["result"]} == expected["result"]
assert len(body["snapshot"]["steps"]) == 1
actual_step = body["snapshot"]["steps"][0]
assert {key: actual_step[key] for key in expected["step"]} == expected["step"]
client.execute_chart_data_raw.assert_not_awaited()
with route_env.session_factory() as db:
row = db.get(ScenarioStepRun, expected["step"]["id"])
assert row.error_code == expected["step"]["error_code"]
assert row.status == "inconclusive"
if provider == "sdk":
receipt = db.query(ProviderOperationReceipt).filter_by(run_id=run_id).one()
assert (receipt.status, receipt.effect_state) == ("failed", "none")
assert receipt.terminal_at is not None
# #endregion Test.ScenarioExecution.Api.CapabilityRefusal
def test_result_404(self, route_env):
resp = route_env.client().get("/api/scenario-runs/nope/result")
assert resp.status_code == 404
# #endregion Test.ScenarioExecution.Api.TestResult
# #region Test.ScenarioExecution.Api.TestSse [C:2] [TYPE Class]
class TestSse:
def test_events_stream_is_text_event_stream(self, route_env):
with route_env.client().stream("GET", f"/api/scenario-runs/{_RUN_1}/events") as resp:
assert resp.status_code == 200
assert resp.headers["content-type"].startswith("text/event-stream")
body = "\n".join(resp.iter_lines())
assert "event: run_failed" in body
assert "event: step_completed" in body
assert "id: 13" in body # 6 steps * 2 events + final run_failed
def test_events_replay_from_last_event_id(self, route_env):
with route_env.client().stream(
"GET", f"/api/scenario-runs/{_RUN_1}/events", headers={"Last-Event-ID": "5"}
) as resp:
assert resp.status_code == 200
body = "\n".join(resp.iter_lines())
assert "id: 5" not in body
assert "id: 6" in body
def test_events_missing_run_404(self, route_env):
resp = route_env.client().get("/api/scenario-runs/nope/events")
assert resp.status_code == 404
# #endregion Test.ScenarioExecution.Api.TestSse
# #region Test.ScenarioExecution.Api.TestLifecycleRoutes [C:2] [TYPE Class]
class TestLifecycleRoutes:
def test_infrastructure_resume_continues_saved_frontier_without_rerunning_completed_step(self, route_env):
from src.models.scenario_registry import ScenarioRevision
from src.models.scenario_run import ScenarioStepRun
from src.services.dashboard_testing.execution.lifecycle import pause_for_infrastructure
from src.services.dashboard_testing.execution.runner import start_run
session = route_env.session_factory()
try:
revision = session.query(ScenarioRevision).filter_by(revision_id=_REV_CURRENT).one()
revision.graph_snapshot = _INFRA_RESUME_GRAPH
session.flush()
run = start_run(
session, _SCENARIO, _REV_CURRENT, {}, "env-preprod-02",
actor="infra-continuation", idempotency_key="infra-continuation-1",
config_manager=route_env.config_manager,
auto_advance=False,
)
session.add(ScenarioStepRun(
run_id=run.id, logical_step_id="before_resume", step_position=0,
attempt=1, status="passed", progress=100,
step_outcome={"logical_step_id": "before_resume", "status": "passed"},
))
_, token = pause_for_infrastructure(session, run.id)
session.commit()
run_id = run.id
finally:
session.close()
client = route_env.client()
invalid = client.post(
f"/api/scenario-runs/{run_id}/resume",
json={"resume_token": "stale-token", "resume_reason": "worker_recovered"},
)
assert invalid.status_code == 409
resumed = client.post(
f"/api/scenario-runs/{run_id}/resume",
json={"resume_token": token, "resume_reason": "worker_recovered"},
)
assert resumed.status_code == 200, resumed.text
assert resumed.json()["status"] == "passed"
result = client.get(f"/api/scenario-runs/{run_id}/result")
steps = {step["logical_step_id"]: step for step in result.json()["snapshot"]["steps"]}
assert result.json()["status"] == "passed"
assert steps["before_resume"]["status"] == "passed"
assert steps["before_resume"]["attempt"] == 1
assert steps["after_resume"]["status"] == "passed"
assert steps["after_resume"]["attempt"] == 1
replay = client.post(
f"/api/scenario-runs/{run_id}/resume",
json={"resume_token": token, "resume_reason": "worker_recovered"},
)
assert replay.status_code == 409
def test_human_confirm_resumes_dependents_without_rerunning_completed_steps(self, route_env):
from src.models.scenario_registry import ScenarioRevision
from src.models.scenario_run import ScenarioStepRun
from src.services.dashboard_testing.execution.runner import dispatch_queued_runs, start_run
session = route_env.session_factory()
try:
revision = session.query(ScenarioRevision).filter_by(revision_id=_REV_CURRENT).one()
revision.graph_snapshot = _HUMAN_CONTINUATION_GRAPH
session.flush()
run = start_run(
session, _SCENARIO, _REV_CURRENT, {}, "env-preprod-02",
actor="human-continuation", idempotency_key="human-continuation-1",
config_manager=route_env.config_manager,
)
session.commit()
run_id = run.id
assert session.query(ScenarioStepRun).filter_by(run_id=run_id).count() == 0
dispatch_queued_runs(session, worker_id="api-human-continuation")
session.commit()
before = session.query(ScenarioStepRun).filter_by(
run_id=run_id, logical_step_id="before_human"
).one()
assert before.status == "passed"
assert before.attempt == 1
finally:
session.close()
decision = route_env.client().post(
f"/api/scenario-runs/{run_id}/human/decision",
json={"disposition": "confirm", "expected_version": 1, "comment": "fixture sign-off"},
)
assert decision.status_code == 200, decision.text
result = route_env.client().get(f"/api/scenario-runs/{run_id}/result")
assert result.status_code == 200, result.text
assert result.json()["status"] == "passed"
steps = {step["logical_step_id"]: step for step in result.json()["snapshot"]["steps"]}
assert steps["before_human"]["status"] == "passed"
assert steps["before_human"]["attempt"] == 1
assert steps["human_signoff"]["status"] == "passed"
assert steps["after_human"]["status"] == "passed"
@pytest.mark.parametrize(
("disposition", "error_code"),
[("false_positive", "HUMAN_FALSE_POSITIVE"), ("inconclusive", "HUMAN_INCONCLUSIVE")],
)
def test_human_nonpass_dispositions_resume_with_explicit_inconclusive_outcome(
self, route_env, disposition, error_code,
):
from src.models.scenario_registry import ScenarioRevision
from src.services.dashboard_testing.execution.runner import dispatch_queued_runs, start_run
session = route_env.session_factory()
try:
revision = session.query(ScenarioRevision).filter_by(revision_id=_REV_CURRENT).one()
revision.graph_snapshot = _HUMAN_CONTINUATION_GRAPH
session.flush()
run = start_run(
session, _SCENARIO, _REV_CURRENT, {}, "env-preprod-02",
actor="human-nonpass", idempotency_key=f"human-nonpass-{disposition}",
config_manager=route_env.config_manager,
)
session.commit()
run_id = run.id
dispatch_queued_runs(session, worker_id=f"api-human-nonpass-{disposition}")
session.commit()
finally:
session.close()
decision = route_env.client().post(
f"/api/scenario-runs/{run_id}/human/decision",
json={"disposition": disposition, "expected_version": 1},
)
assert decision.status_code == 200, decision.text
result = route_env.client().get(f"/api/scenario-runs/{run_id}/result")
steps = {step["logical_step_id"]: step for step in result.json()["snapshot"]["steps"]}
assert result.json()["status"] == "inconclusive"
assert steps["human_signoff"]["status"] == "inconclusive"
assert steps["human_signoff"]["error_code"] == error_code
assert steps["human_signoff"]["step_outcome"]["disposition"] == disposition
assert steps["after_human"]["status"] == "passed"
def test_cancel_run(self, route_env):
client = route_env.client()
created = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "life-1"},
json=route_env.start_body(),
).json()
resp = client.post(f"/api/scenario-runs/{created['id']}/cancel")
assert resp.status_code == 200
assert resp.json()["status"] == "cancelled"
def test_resume_paused_run(self, route_env):
from src.services.dashboard_testing.execution.lifecycle import pause_for_infrastructure
client = route_env.client()
created = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "life-2"},
json=route_env.start_body(),
).json()
# Mint the pause token through the service (the pause action is server-internal).
session = route_env.session_factory()
try:
_, token = pause_for_infrastructure(session, created["id"])
session.commit()
finally:
session.close()
resp = client.post(
f"/api/scenario-runs/{created['id']}/resume",
json={"resume_token": token, "resume_reason": "worker_recovered"},
)
assert resp.status_code == 200, resp.text
assert resp.json()["status"] == "waiting_human"
assert resp.json()["phase"] == "waiting_human"
def test_resume_human_checkpoint_409(self, route_env):
from src.services.dashboard_testing.execution.lifecycle import suspend_for_human
client = route_env.client()
created = client.post(
"/api/scenario-runs",
headers={"Idempotency-Key": "life-3"},
json=route_env.start_body(),
).json()
session = route_env.session_factory()
try:
suspend_for_human(session, created["id"], "s_human", [])
session.commit()
finally:
session.close()
resp = client.post(
f"/api/scenario-runs/{created['id']}/resume",
json={"resume_token": "x", "resume_reason": "worker_recovered"},
)
assert resp.status_code == 409
assert "human checkpoint" in resp.json()["detail"]["detail"]
def test_retry_step_rejects_legacy_unsafe_plan(self, route_env):
resp = route_env.client().post(f"/api/scenario-runs/{_RUN_1}/steps/s3_export_xlsx/retry")
assert resp.status_code == 409, resp.text
assert resp.json()["detail"]["code"] == "RETRY_CONFLICT"
assert "non-retry-safe action descriptor" in resp.json()["detail"]["detail"]
def test_retry_missing_step_409(self, route_env):
resp = route_env.client().post(f"/api/scenario-runs/{_RUN_1}/steps/nope/retry")
assert resp.status_code == 409
# #endregion Test.ScenarioExecution.Api.TestLifecycleRoutes
# #endregion Test.ScenarioExecution.Api