Files
ss-tools/backend/tests/services/dashboard_testing/registry/conftest.py

484 lines
21 KiB
Python

# #region Test.ScenarioRegistry.Conftest [C:3] [TYPE Module] [SEMANTICS testing,scenario,registry,fixtures]
# @defgroup Shared deterministic fixtures for Scenario Registry service tests.
# @LAYER Test
# @RELATION BINDS_TO -> [ScenarioRegistry.List]
# @RELATION BINDS_TO -> [ScenarioRegistry.Get]
# @RATIONALE The registry service tests need a real SQLAlchemy session over the scenario registry
# tables. The canonical fixture (specs/042-.../fixtures/registry.json, materialized under
# tests/fixtures/scenario_registry/) is loaded by seed_registry() so service and API tests
# share one source of truth for registry rows, revision chains, and staleness signals.
from __future__ import annotations
from datetime import datetime
import json
from pathlib import Path
import pytest
from types import SimpleNamespace
from uuid import uuid4
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from dashboard_candidate_fixture_requests import (
_CONSUME_REL as _CONSUME_REL,
_CONSUME_COMMIT as _CONSUME_COMMIT,
_TEST_SOURCE_RESPONSE_HASH as _TEST_SOURCE_RESPONSE_HASH,
_make_request as _make_request,
_make_request_with_capture as _make_request_with_capture,
_make_gate_request as _make_gate_request,
)
from src.schemas.dashboard_testing import (
ApprovalGateRequest,
CandidateRequest,
ComparisonPolicy,
ComparisonPolicyType,
NormalizedFilterContext,
NormalizedValue,
Provenance,
ValueKind,
)
# #region Test.ScenarioRegistry.Conftest.EnvironmentPolicy [C:2] [TYPE Function] [SEMANTICS test,scenario,execution,environment,prod,fixture]
# @BRIEF Provide only explicit server-owned environment records to 044 persisted fixtures.
# @TEST_FIXTURE preprod/prod/env-preprod-02/env-preprod-044 -> INLINE_CONFIG_MANAGER
# @TEST_INVARIANT ScenarioExecution.EnvironmentPolicy: fixture run bodies cannot classify an
# environment; only this hardcoded ConfigManager mapping may select PROD.
@pytest.fixture(autouse=True)
def configured_scenario_execution_environments(monkeypatch):
environments = {
"preprod": SimpleNamespace(stage="PREPROD", is_production=False),
"prod": SimpleNamespace(stage="PROD", is_production=True),
"env-preprod-02": SimpleNamespace(stage="PREPROD", is_production=False),
"env-preprod-044": SimpleNamespace(stage="PREPROD", is_production=False),
"env-preprod-manual-only": SimpleNamespace(
stage="PREPROD", is_production=False
),
}
config_manager = SimpleNamespace(
get_environment=lambda environment_id: environments.get(environment_id)
)
monkeypatch.setattr(
"src.dependencies.get_config_manager", lambda: config_manager
)
return config_manager
# #endregion Test.ScenarioRegistry.Conftest.EnvironmentPolicy
# #region Test.ScenarioRegistry.Conftest.PublishedCatalog [C:3] [TYPE Function] [SEMANTICS test,postgresql,registry,explicit,receipt]
# @BRIEF Explicit baseline tests use actual retained DB revisions/receipts; ordinary registry tests receive no synthetic pin.
# @PRE PG_CONSUMER_CONNECTION_FILE names the exact isolated migrated test database.
# @POST Fixture returns the real Session and explicit selector; production resolver/admission remain unpatched.
# @REJECTED Autouse resolver/source patches invented baseline authority even for baseline-free graphs.
@pytest.fixture
def registry_catalog():
import importlib.util
source = Path(__file__).parents[1] / "execution" / "pg_consumer_fixture.py"
spec = importlib.util.spec_from_file_location("registry_pg_fixture", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
db, selector, operation = module.database()
try:
yield SimpleNamespace(db=db, selector=selector, operation=operation, fixture=module)
finally:
module.close_database(db)
# #endregion Test.ScenarioRegistry.Conftest.PublishedCatalog
_FIXTURE_PATH = (
Path(__file__).resolve().parents[3] / "fixtures" / "scenario_registry" / "registry.json"
)
_ANALYTICS_FIXTURE_PATH = (
Path(__file__).resolve().parents[3] / "fixtures" / "scenario_analytics" / "analytics.json"
)
def _parse_ts(value: str | None) -> datetime | None:
if not value:
return None
return datetime.fromisoformat(value.replace("Z", "+00:00"))
# #region Test.ScenarioRegistry.Conftest.SeedRegistry [C:2] [TYPE Function] [SEMANTICS testing,scenario,registry,seed]
# @BRIEF Load the canonical registry fixture JSON and persist it through the session.
# @POST Creates ScenarioRegistryEntry/ScenarioRevision/ScenarioStalenessSignal rows; commits.
def seed_registry(db: Session) -> None:
from src.models.scenario_registry import (
ScenarioLifecycleAudit,
ScenarioRegistryEntry,
ScenarioRevision,
ScenarioStalenessSignal,
)
data = json.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))
entries: dict[str, ScenarioRegistryEntry] = {}
for row in data["entries"]:
entry = 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"]),
)
db.add(entry)
entries[entry.scenario_id] = entry
revisions_by_id: dict[str, ScenarioRevision] = {}
for row in data["revisions"]:
revision = 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"),
)
db.add(revision)
revisions_by_id[revision.revision_id] = revision
for row in data["staleness_signals"]:
signal = 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")),
)
db.add(signal)
# One lifecycle audit row per seeded entry — the audit log table must be exercised too.
for entry_id, entry in entries.items():
db.add(ScenarioLifecycleAudit(
scenario_id=entry_id,
from_state=None,
to_state=entry.lifecycle_status,
actor_id=entry.owner_id,
actor_type="user",
reason="fixture seed",
created_at=entry.created_at,
))
db.commit()
return None
# #endregion Test.ScenarioRegistry.Conftest.SeedRegistry
# #region Test.ScenarioRegistry.Conftest.PgEngine [C:2] [TYPE Function]
# @PRE PG_CONSUMER_CONNECTION_FILE explicitly names the final migrated isolated database.
# @POST No SQLite fallback, schema creation or migration is attempted.
@pytest.fixture
def registry_engine():
from tests.services.dashboard_testing.execution.pg_consumer_fixture import connection_url
engine = create_engine(connection_url())
try:
yield engine
finally:
engine.dispose()
# #endregion Test.ScenarioRegistry.Conftest.PgEngine
# #region Test.ScenarioRegistry.Conftest.RollbackSession [C:2] [TYPE Function]
# @POST Ordinary service commits stay inside an outer rollback; independent visibility requires the explicit committed fixture.
@pytest.fixture
def registry_session(registry_engine) -> Session:
with registry_engine.connect() as connection:
transaction = connection.begin()
db = Session(bind=connection, join_transaction_mode='create_savepoint')
try:
yield db
finally:
db.close()
if transaction.is_active:
transaction.rollback()
# #endregion Test.ScenarioRegistry.Conftest.RollbackSession
# #region Test.ScenarioRegistry.Conftest.CommittedExecution [C:3] [TYPE Function]
# @PRE Explicit final migrated PG engine; this fixture deliberately commits only its unique scenario/run rows.
# @POST A Session bound to the Engine permits a genuinely independent committed observer; teardown deletes only its exact scenario tree.
# @REJECTED A savepoint on the same connection cannot prove independent committed visibility.
@pytest.fixture
def committed_execution(registry_engine):
from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision
from src.models.scenario_run import ScenarioRun
scenario_id, revision_id, run_id = (str(uuid4()) for _ in range(3))
db = Session(bind=registry_engine)
try:
db.add(ScenarioRegistryEntry(scenario_id=scenario_id, scenario_key='committed-native-attempt:' + scenario_id,
name='Independent committed attempt fixture', dashboard_id=2, environment_ids=['preprod'],
owner_id='fixture', owner_username='fixture', current_revision_id=revision_id))
db.flush()
db.add(ScenarioRevision(revision_id=revision_id, scenario_id=scenario_id, content_hash='a'*64,
graph_snapshot={}, execution_template_hash='', template_version='v2', schema_version=2,
change_summary={}, created_by='fixture', activation_status='current'))
db.add(ScenarioRun(id=run_id, scenario_id=scenario_id, scenario_revision_id=revision_id,
scenario_content_hash='a'*64, environment_id='preprod', status='running', phase='executing',
parameter_bindings={}, target_snapshot={}, runner_plan={}, trigger_source='manual',
idempotency_key='committed-native-attempt:' + run_id))
db.commit()
yield SimpleNamespace(db=db, run_id=run_id)
finally:
db.rollback()
db.query(ScenarioRegistryEntry).filter_by(scenario_id=scenario_id).delete(synchronize_session=False)
db.commit()
db.close()
# #endregion Test.ScenarioRegistry.Conftest.CommittedExecution
@pytest.fixture
def seeded_registry(registry_session: Session) -> Session:
"""Session pre-seeded with the canonical registry fixture."""
seed_registry(registry_session)
return registry_session
# #region Test.ScenarioRegistry.Conftest.SeedAnalytics [C:3] [TYPE Function] [SEMANTICS testing,scenario,analytics,seed]
# @BRIEF Materialize the canonical 047 analytics fixture: queue items, cases, agent actions,
# recurring episodes and immutable run history rows.
# @PRE db has the registry fixture already seeded (cases/queue reference its scenario ids).
# @POST Creates InvestigationQueueItem/InvestigationCase/AgentAction/RecurringFailureEpisode
# and ScenarioRun/ScenarioStepRun rows; commits.
def seed_analytics(db: Session) -> None:
from src.models.scenario_investigation import (
AgentAction,
InvestigationCase,
InvestigationQueueItem,
RecurringFailureEpisode,
)
from src.models.scenario_run import ScenarioRun, ScenarioStepRun
data = json.loads(_ANALYTICS_FIXTURE_PATH.read_text(encoding="utf-8"))
# SQLAlchemy sorts inserts by mapper dependencies only when ORM relationships
# exist; these tables are FK-only, so parents MUST be flushed before children.
for row in data["queue_items"]:
db.add(InvestigationQueueItem(
id=row["id"],
fingerprint=row["fingerprint"],
scenario_id=row["scenario_id"],
run_id=row.get("run_id"),
severity=row["severity"],
status=row["status"],
occurrence_count=row["occurrence_count"],
evidence_snapshot=row.get("evidence_snapshot", {}),
created_at=_parse_ts(row["created_at"]),
))
db.flush()
for row in data["cases"]:
db.add(InvestigationCase(
id=row["id"],
fingerprint=row["fingerprint"],
scenario_id=row["scenario_id"],
status=row["status"],
disposition=row.get("disposition"),
decision_version=row["decision_version"],
evidence_snapshot=row.get("evidence_snapshot", {}),
linked_run_ids=row.get("linked_run_ids", []),
created_at=_parse_ts(row["created_at"]),
))
db.flush()
for row in data["actions"]:
db.add(AgentAction(
id=row["id"],
case_id=row["case_id"],
action_type=row["action_type"],
payload=row.get("payload", {}),
created_at=_parse_ts(row["created_at"]),
))
db.flush()
for row in data["episodes"]:
db.add(RecurringFailureEpisode(
id=row["id"],
fingerprint=row["fingerprint"],
scenario_id=row["scenario_id"],
status=row["status"],
occurrence_count=row["occurrence_count"],
first_seen_at=_parse_ts(row["first_seen_at"]),
last_seen_at=_parse_ts(row["last_seen_at"]),
))
db.flush()
for run_row in data["run_history"]:
run = 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"],
trigger_source=run_row["trigger_source"],
idempotency_key=run_row["idempotency_key"],
created_at=_parse_ts(run_row["created_at"]),
)
db.add(run)
db.flush()
for step_row in run_row.get("steps", []):
db.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"],
progress=step_row["progress"],
artifact_refs=step_row.get("artifact_refs", []),
error_code=step_row.get("error_code"),
started_at=_parse_ts(run_row.get("created_at")),
finished_at=_parse_ts(run_row.get("created_at")),
))
db.flush()
db.commit()
return None
# #endregion Test.ScenarioRegistry.Conftest.SeedAnalytics
@pytest.fixture
def analytics_seeded_registry(registry_session: Session) -> Session:
"""Session pre-seeded with canonical registry + 047 analytics fixtures."""
seed_registry(registry_session)
seed_analytics(registry_session)
return registry_session
# #endregion Test.ScenarioRegistry.Conftest
# ── 044 execution fixture (T002/T003 materialized from specs/044-.../fixtures) ──
_EXEC_FIXTURE_DIR = Path(__file__).resolve().parents[3] / "fixtures" / "scenario_execution"
_EXEC_SCENARIO_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1"
_EXEC_REVISION_CURRENT = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1"
_EXEC_REVISION_STALE = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2"
_EXEC_CONTENT_HASH_CURRENT = "d" * 64
_EXEC_CONTENT_HASH_STALE = "e" * 64
# #region Test.ScenarioExecution.Conftest.SeedExecutionFixture [C:3] [TYPE Function] [SEMANTICS testing,scenario,execution,fixture,seed]
# @BRIEF Persist the canonical 044 execution fixture: executable graph revisions + run states.
# @POST Creates one ScenarioRegistryEntry, current + stale revisions, and the fixture runs/steps; commits.
def seed_execution_fixture(db: Session) -> None:
from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision
from src.models.scenario_run import ScenarioRun, ScenarioStepRun
graph = json.loads((_EXEC_FIXTURE_DIR / "graph.json").read_text(encoding="utf-8"))
run_states = json.loads((_EXEC_FIXTURE_DIR / "run_states.json").read_text(encoding="utf-8"))
entry = ScenarioRegistryEntry(
scenario_id=_EXEC_SCENARIO_ID,
scenario_key="fi-0080_execution-fixture", # gitleaks:allow
name="FI-0080 Execution fixture",
description="Canonical 044 executable graph + run states",
dashboard_id=80,
environment_ids=["env-preprod-02"],
owner_id="user-qa-1",
owner_username="qa.analyst",
tags=["execution", "fixture"],
metadata_version="etag-exec-001",
lifecycle_status="READY",
validation_status="valid",
current_revision_id=_EXEC_REVISION_CURRENT,
last_modified_at=_parse_ts("2026-08-05T08:00:00+00:00"),
created_at=_parse_ts("2026-08-01T08:00:00+00:00"),
)
db.add(entry)
db.add(ScenarioRevision(
revision_id=_EXEC_REVISION_CURRENT, scenario_id=_EXEC_SCENARIO_ID,
content_hash=_EXEC_CONTENT_HASH_CURRENT, graph_snapshot=graph,
execution_template_hash="", template_version="v1", schema_version=1,
change_summary={"fixture": "current"}, created_by="fixture",
created_at=_parse_ts("2026-08-05T08:00:00+00:00"), activation_status="current",
))
db.add(ScenarioRevision(
revision_id=_EXEC_REVISION_STALE, scenario_id=_EXEC_SCENARIO_ID,
content_hash=_EXEC_CONTENT_HASH_STALE, graph_snapshot=graph,
execution_template_hash="", template_version="v1", schema_version=1,
change_summary={"fixture": "stale"}, created_by="fixture",
created_at=_parse_ts("2026-08-04T08:00:00+00:00"), activation_status="candidate",
))
for run_row in run_states["runs"]:
run = 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=_parse_ts(run_row["created_at"]),
started_at=_parse_ts(run_row.get("started_at")),
finished_at=_parse_ts(run_row.get("finished_at")),
)
db.add(run)
for step_row in run_row.get("steps", []):
db.add(ScenarioStepRun(
id=step_row["id"],
run_id=run.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", {}),
))
db.commit()
# #endregion Test.ScenarioExecution.Conftest.SeedExecutionFixture
# #region Test.ScenarioExecution.Conftest.SeedingFixture [C:2] [TYPE Function] [SEMANTICS testing,scenario,execution,fixture,seeding]
# @ingroup Test.ScenarioExecution.Conftest
# @BRIEF Session pre-seeded with the canonical 044 execution fixture.
@pytest.fixture
def seeded_execution(registry_session: Session) -> Session:
"""Session pre-seeded with the canonical 044 execution fixture."""
seed_execution_fixture(registry_session)
return registry_session
# #endregion Test.ScenarioExecution.Conftest.SeedingFixture