# #region Test.Api.ReferenceSelection [C:4] [TYPE Module] [SEMANTICS baseline,reference,selection,api,test] # @RELATION VERIFIES -> [Api.DashboardTesting.ReferenceSelection.NativeTable] # @TEST_INVARIANT Current capture binds persisted actor/scenario/environment; authored intent never supplies native evidence. # @RATIONALE The deleted scalar preview capture endpoint cannot authorize current native chart responses. # @REJECTED Restoring its DTO or trusting caller preview digests would bypass owned native evidence. from __future__ import annotations import asyncio import inspect import json from types import SimpleNamespace from unittest.mock import AsyncMock, Mock, patch from fastapi import HTTPException from pydantic import ValidationError import pytest from src.api.routes.dashboard_testing.reference_selection import capture_native_chart_endpoint, router from src.models.auth import Role, User from src.schemas.dashboard_testing.native_capture import NativeChartCaptureRequest from tests.services.dashboard_testing.native_table_fixtures import literal_policy_intent _ACTOR_ID = '11111111-aaaa-4111-8111-111111111111' _HASH = 'sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945' _RESPONSE = {'schema_version': 1, 'kind': 'chart_response', 'scope': 'native_query_result', 'agent_run_id': 'agent-1', 'release_id': 'release-1', 'candidate_ids': ['candidate-1'], 'capture_artifact_ids': ['artifact-1'], 'result_authority_version': 1, 'descriptor_sha256': 'c'*64, 'result_identity_sha256': 'd'*64, 'capture_binding_id': 'binding-1', 'capture_binding_version': 1, 'capture_operation_id': 'operation-1', 'capture_state': 'pending'} def _body(**overrides): data = {'schema_version': 1, 'kind': 'chart_response', 'scope': 'native_query_result', 'scenario_id': 'scenario-1', 'url': 'https://superset.example/dashboard/42/', 'selected': [{'chart_id': 11, 'dataset_id': 7, 'metric': 'sum_sales'}], 'expected_query_model_fingerprint': 'sha256:'+'a'*64, 'expected_filters_hash': _HASH, 'native_filter_context': {'schema_version': 1, 'filters': [], 'filters_hash': _HASH}, 'comparison_policy_intent': literal_policy_intent().model_dump(mode='json'), 'catalog_selection': {'kind': 'revision', 'catalog_id': '11111111-1111-4111-8111-111111111111', 'catalog_revision_id': '22222222-2222-4222-8222-222222222222'}} data.update(overrides) return NativeChartCaptureRequest.model_validate_json(json.dumps(data)) class _DB: def __init__(self, owner=_ACTOR_ID, environments=('preprod',), username='writer'): self.committed = False self.rolled_back = False self.scenario = SimpleNamespace(dashboard_id=42, environment_ids=list(environments), owner_id=owner, owner_username=username) def get(self, model, key): return self.scenario if key == 'scenario-1' else None def commit(self): self.committed = True def rollback(self): self.rolled_back = True def _writer(active=True): return SimpleNamespace(id=_ACTOR_ID, username='writer', is_active=active) # #region Test.Api.ReferenceSelection.Success [C:3] [TYPE Function] # @TEST_INVARIANT Server-owned dashboard and actor reach native capture; response remains pending without publication authority. @pytest.mark.asyncio async def test_route_binds_scenario_dashboard_and_commits(): paths = [route.path for route in router.routes] assert '/api/dashboard-testing/reference-selection/chart-response-capture' in paths assert '/api/dashboard-testing/reference-selection/capture' not in paths db, body = _DB(), _body() environment = SimpleNamespace(id='preprod', url='https://superset.example') with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=environment), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock(return_value='client')), patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock(return_value=_RESPONSE)) as capture, ): result = await capture_native_chart_endpoint(body, _reader=object(), _executor=object(), _writer=_writer(), db=db) assert result.model_dump(mode='json') == _RESPONSE assert db.committed and not db.rolled_back capture.assert_awaited_once_with(db, _ACTOR_ID, 'client', environment, 42, body) # #endregion Test.Api.ReferenceSelection.Success # #region Test.Api.ReferenceSelection.Errors [C:3] [TYPE Function] # @TEST_INVARIANT Service failure or incomplete returned authority rolls back; caller never receives driver/body details. @pytest.mark.asyncio @pytest.mark.parametrize('failure', [LookupError('PRIVATE_RELEASE_SENTINEL'), ValueError('PRIVATE_CONTEXT_SENTINEL'), None]) async def test_typed_errors_rollback(failure): db = _DB() with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=SimpleNamespace(id='preprod')), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock(return_value='client')), patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock(side_effect=failure, return_value={'candidate_ids': ['candidate-1']})), ): with pytest.raises(HTTPException) as caught: await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(), db=db) assert caught.value.status_code == 500 assert caught.value.detail == {'code': 'NATIVE_REFERENCE_CAPTURE_INTERNAL_ERROR'} assert db.rolled_back and not db.committed # #endregion Test.Api.ReferenceSelection.Errors # #region Test.Api.ReferenceSelection.Scope [C:3] [TYPE Function] # @TEST_INVARIANT Foreign owner/inactive actor/unbound environment refuse before client or native capture. @pytest.mark.asyncio @pytest.mark.parametrize('owner,active,environments,code,status', [ ('foreign', True, ('preprod',), 'NATIVE_REFERENCE_SCENARIO_UNAVAILABLE', 404), (_ACTOR_ID, False, ('preprod',), 'NATIVE_REFERENCE_SCENARIO_UNAVAILABLE', 404), (_ACTOR_ID, True, ('dev',), 'NATIVE_REFERENCE_ENVIRONMENT_MISMATCH', 422), ]) async def test_foreign_scope_cannot_capture(owner, active, environments, code, status): db = _DB(owner, environments) with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=SimpleNamespace(id='preprod')), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock()) as client, ): with pytest.raises(HTTPException) as caught: await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(active), db=db) assert caught.value.status_code == status and caught.value.detail == {'code': code} client.assert_not_awaited() assert not db.committed # #endregion Test.Api.ReferenceSelection.Scope # #region Test.Api.ReferenceSelection.Cancellation [C:3] [TYPE Function] # @TEST_INVARIANT Cancellation rolls back and propagates; it cannot become a successful pending response. @pytest.mark.asyncio async def test_cancellation_rolls_back(): db = _DB() with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=SimpleNamespace(id='preprod')), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock(return_value='client')), patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock(side_effect=asyncio.CancelledError)), ): with pytest.raises(asyncio.CancelledError): await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(), db=db) assert db.rolled_back and not db.committed # #endregion Test.Api.ReferenceSelection.Cancellation # #region Test.Api.ReferenceSelection.PublicAuthority [C:2] [TYPE Function] # @TEST_INVARIANT Caller cannot supply dashboard/run/release/oracle or obsolete preview evidence. @pytest.mark.parametrize('overrides', [{'dashboard_id': 999}, {'agent_run_id': 'foreign'}, {'release_id': 'foreign'}, {'selected': [{'chart_id': 11, 'dataset_id': 7, 'metric': 'sum_sales', 'evidence_digest': 'sha256:'+'b'*64}]}, {'expected': 17}]) def test_injected_authority_is_rejected(overrides): with pytest.raises(ValidationError): _body(**overrides) # #endregion Test.Api.ReferenceSelection.PublicAuthority # #region Test.Api.ReferenceSelection.Rbac [C:3] [TYPE Function] # @TEST_INVARIANT The route declares READ, EXECUTE and WRITE guards. def test_capture_requires_read_execute_write(): parameters = inspect.signature(capture_native_chart_endpoint).parameters viewer = User(id='reference-viewer', username='viewer', email='viewer@test.com') viewer.roles = [Role(id='reference-viewer', name='Viewer', is_admin=False)] for name, action in (('_reader', 'READ'), ('_executor', 'EXECUTE'), ('_writer', 'WRITE')): with pytest.raises(HTTPException) as caught: parameters[name].default.dependency(viewer) assert caught.value.status_code == 403 assert action in caught.value.detail # #endregion Test.Api.ReferenceSelection.Rbac # #region Test.Api.ReferenceSelection.RegisteredOwnership [C:3] [TYPE Function] # @TEST_INVARIANT Registered actor ID and username both match before client/native writes; fixed logs expose only failed predicates. @pytest.mark.asyncio @pytest.mark.parametrize('present,owner_id,username,active,expected_facts', [ (False, _ACTOR_ID, 'writer', True, {'scenario_present': False, 'actor_active': True, 'owner_id_matches': False, 'owner_username_matches': False}), (True, '22222222-bbbb-4222-8222-222222222222', 'writer', True, {'scenario_present': True, 'actor_active': True, 'owner_id_matches': False, 'owner_username_matches': True}), (True, _ACTOR_ID, 'PRIVATE_FOREIGN_OWNER_SENTINEL', True, {'scenario_present': True, 'actor_active': True, 'owner_id_matches': True, 'owner_username_matches': False}), (True, _ACTOR_ID, 'writer', False, {'scenario_present': True, 'actor_active': False, 'owner_id_matches': True, 'owner_username_matches': True}), ]) async def test_registered_owner_fields_refuse_independently(present, owner_id, username, active, expected_facts, caplog): import logging caplog.set_level(logging.INFO) from src.core.cot_formatter import CotJsonFormatter from src.core.cot_logger import seed_trace_id seed_trace_id() db = _DB(owner_id, username=username) if not present: db.scenario = None before = None if db.scenario is None else dict(vars(db.scenario)) with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin') as origin, patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock()) as client, patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock()) as capture, ): with pytest.raises(HTTPException) as caught: await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(active), db=db) assert caught.value.status_code == 404 assert caught.value.detail == {'code': 'NATIVE_REFERENCE_SCENARIO_UNAVAILABLE'} origin.assert_not_called() client.assert_not_awaited() capture.assert_not_awaited() assert not db.committed and not db.rolled_back assert (None if db.scenario is None else dict(vars(db.scenario))) == before records = list({id(r): r for r in caplog.records if getattr(r, 'contract_id', None) == 'Api.DashboardTesting.ReferenceSelection.NativeTable'}.values()) events = [json.loads(CotJsonFormatter().format(r)) for r in records] assert [e['marker'] for e in events] == ['REASON', 'EXPLORE'] event = events[-1] assert event['error_code'] == 'NATIVE_REFERENCE_SCENARIO_UNAVAILABLE' assert event['claim'] == 'PRE: canonical scenario and active actor' assert event['payload'] == expected_facts assert event['loc'].startswith('backend/src/api/routes/dashboard_testing/reference_selection.py:') assert 'PRIVATE_FOREIGN_OWNER_SENTINEL' not in json.dumps(events) # #endregion Test.Api.ReferenceSelection.RegisteredOwnership # #region Test.Api.ReferenceSelection.FailureTaxonomy [C:3] [TYPE Function] # @TEST_INVARIANT Only six closed domain refusals from capture execution yield 422; actual formatted logs retain phase/code without exception operands. @pytest.mark.asyncio @pytest.mark.parametrize('code', [ 'NATIVE_REFERENCE_CONTEXT_CHANGED', 'NATIVE_REFERENCE_COORDINATE_UNAVAILABLE', 'NATIVE_FILTER_CONTEXT_EFFECTIVE_CONFLICT', 'NATIVE_REFERENCE_RELEASE_REQUIRED', 'NATIVE_REFERENCE_RELEASE_CHANGED', 'NATIVE_REFERENCE_RELEASE_SCOPE_MISMATCH', ]) async def test_closed_capture_refusals_are_request_errors(code, caplog): from src.core.cot_formatter import CotJsonFormatter from src.core.cot_logger import seed_trace_id from src.services.dashboard_testing.native_reference_capture import NativeReferenceCaptureRefusal trace = seed_trace_id() db = _DB() with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=SimpleNamespace(id='preprod')), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock(return_value='client')), patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock(side_effect=NativeReferenceCaptureRefusal(code))), ): with pytest.raises(HTTPException) as caught: await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(), db=db) assert caught.value.status_code == 422 assert caught.value.detail == {'code': code} assert db.rolled_back and not db.committed events = [json.loads(CotJsonFormatter().format(record)) for record in {id(r): r for r in caplog.records if getattr(r, 'error_code', None) == code}.values()] assert len(events) == 1 assert events[0]['marker'] == 'EXPLORE' and events[0]['trace_id'] == trace assert events[0]['contract_id'] == 'Api.DashboardTesting.ReferenceSelection.NativeTable' assert events[0]['claim'] == 'INVARIANT: typed capture failure taxonomy' assert events[0]['payload'] == {'phase': 'capture'} # #endregion Test.Api.ReferenceSelection.FailureTaxonomy # #region Test.Api.ReferenceSelection.UnexpectedPhases [C:3] [TYPE Function] # @TEST_INVARIANT Unexpected client/capture/result/commit failures, including a domain class outside capture, remain safe500 and roll back. @pytest.mark.asyncio @pytest.mark.parametrize('phase,kind', [ ('client_acquisition', 'runtime'), ('client_acquisition', 'domain'), ('capture', 'key'), ('capture', 'value'), ('capture', 'lookup'), ('capture', 'http'), ('response_validation', 'invalid'), ('commit', 'runtime'), ('commit', 'domain'), ]) async def test_unexpected_capture_failures_keep_server_taxonomy(phase, kind, caplog): from src.core.cot_formatter import CotJsonFormatter from src.core.cot_logger import seed_trace_id from src.services.dashboard_testing.native_reference_capture import NativeReferenceCaptureRefusal trace = seed_trace_id() sentinel = 'PRIVATE_CAPTURE_SQL_URL_CONTEXT_SENTINEL' failures = {'runtime': RuntimeError(sentinel), 'key': KeyError(sentinel), 'value': ValueError('NATIVE_REFERENCE_CONTEXT_CHANGED'), 'lookup': LookupError(sentinel), 'http': HTTPException(status_code=422, detail=sentinel), 'domain': NativeReferenceCaptureRefusal('NATIVE_REFERENCE_CONTEXT_CHANGED')} failure = failures.get(kind) db = _DB() if phase == 'commit': db.commit = Mock(side_effect=failure) with ( patch('src.api.routes.dashboard_testing.reference_selection._resolve_origin', return_value=SimpleNamespace(id='preprod')), patch('src.api.routes.dashboard_testing.reference_selection.get_superset_client', new=AsyncMock(side_effect=failure if phase == 'client_acquisition' else None, return_value='client')), patch('src.services.dashboard_testing.native_reference_capture.capture_native_reference', new=AsyncMock(side_effect=failure if phase == 'capture' else None, return_value={'candidate_ids': [sentinel]} if phase == 'response_validation' else _RESPONSE)) as capture, ): with pytest.raises(HTTPException) as caught: await capture_native_chart_endpoint(_body(), _reader=object(), _executor=object(), _writer=_writer(), db=db) assert caught.value.status_code == 500 assert caught.value.detail == {'code': 'NATIVE_REFERENCE_CAPTURE_INTERNAL_ERROR'} assert db.rolled_back and not db.committed if phase == 'client_acquisition': capture.assert_not_awaited() records = {id(r): r for r in caplog.records if getattr(r, 'contract_id', None) == 'Api.DashboardTesting.ReferenceSelection.NativeTable'} events = [json.loads(CotJsonFormatter().format(r)) for r in records.values()] last = events[-1] assert last['marker'] == 'EXPLORE' and last['trace_id'] == trace assert last['error_code'] == 'NATIVE_REFERENCE_CAPTURE_INTERNAL_ERROR' assert last['payload'] == {'phase': phase} assert last['claim'] == 'INVARIANT: typed capture failure taxonomy' assert sentinel not in json.dumps(events) and sentinel not in str(caught.value.detail) # #endregion Test.Api.ReferenceSelection.UnexpectedPhases # #region Test.Api.ReferenceSelection.OpenApiTaxonomy [C:2] [TYPE Function] # @TEST_INVARIANT Current generated capture operation advertises its success, request, ownership and server-error boundaries. def test_current_capture_openapi_documents_failure_taxonomy(): from fastapi import FastAPI application = FastAPI() application.include_router(router) responses = application.openapi()['paths']['/api/dashboard-testing/reference-selection/chart-response-capture']['post']['responses'] assert {'201', '404', '422', '500'} <= set(responses) assert 'NATIVE_REFERENCE_CAPTURE_INTERNAL_ERROR' in responses['500']['description'] # #endregion Test.Api.ReferenceSelection.OpenApiTaxonomy # #endregion Test.Api.ReferenceSelection