test(native): restore complete query screenshot and authority invariants

This commit is contained in:
2026-10-10 20:32:10 +03:00
parent ae2e5b5893
commit 1b60a535ef
4 changed files with 352 additions and 431 deletions

View File

@@ -2,12 +2,96 @@
# @RELATION BINDS_TO -> [ScenarioExecution.ScreenshotProvider.ScenarioDirective.Entry]
# @TEST_INVARIANT Exact immutable selection is unique; foreign/duplicate pins never select the first row.
from copy import deepcopy
import asyncio
from dataclasses import replace
from hashlib import sha256
import json
from types import SimpleNamespace
import pytest
from tests.services.dashboard_testing.execution.pg_consumer_fixture import literal_wrapper
from src.services.dashboard_testing.execution.baseline_resolver import _pin_entry
from src.services.dashboard_testing.execution.providers.scenario_screenshot_directive import _pinned_entry, _graph_binding, _profile_snapshot
from src.services.dashboard_testing.execution.providers.scenario_screenshot_directive import ScenarioScreenshotDirective, resolve_scenario_screenshot_directive
def current_case():
# Shared literal current pin supplies setup only; independent assertions/mutations below own the oracle.
from test_scenario_screenshot_directive import _fixture
run, step, binding, source, profile = _fixture()
return run, step, binding, source, profile
def rehash(run, step):
run.target_snapshot['baseline_pin'] = deepcopy(run.runner_plan['baseline_pin'])
step['target_snapshot'] = deepcopy(run.target_snapshot)
body={key:value for key,value in run.runner_plan.items() if key!='plan_hash'}
run.runner_plan['plan_hash']=sha256(json.dumps(body,sort_keys=True,separators=(',',':')).encode()).hexdigest()
# @TEST_INVARIANT [ScenarioExecution.ScreenshotProvider.ScenarioDirective.Resolve] Complete source/selection/pin/filter/profile joins produce one redacted current directive, independently of caller action inputs.
def test_directive_joins_resolver_pin_typed_metric_selection_and_registered_profile(draft_storage):
run, step, binding, source, profile = current_case()
directive=resolve_scenario_screenshot_directive(run,step,binding,attempt=1)
assert isinstance(directive,ScenarioScreenshotDirective)
assert (directive.dashboard_id,directive.chart_id,directive.dataset_id,directive.result_key)==(2,11,4,'selected_value_cents')
control=directive.native_context.filters[0]
assert (control.filter_id,control.column,control.values)==('NATIVE_FILTER-FINANCE-METRIC','metric_selector',('sales_debt',))
assert directive.reference_digest==source['reference_digest']
assert directive.capture_profile_sha256==profile['sha256']
assert 'sales_debt' not in repr(directive)
@pytest.mark.parametrize('change,code',[
('action','screenshot_plan_projection_mismatch'),('run','screenshot_plan_projection_mismatch'),
('case','screenshot_plan_projection_mismatch'),('revision','screenshot_baseline_pin_mismatch'),
('step','screenshot_plan_projection_mismatch')])
def test_changed_step_or_pin_refuses_before_directive(draft_storage,change,code):
run,step,binding,_,_=current_case()
if change=='action':step['action']='foreign'
elif change=='run':step['scenario_run_id']='foreign'
elif change=='case':step['step_meta']['checklist_case_ids']=['M01','M02']
elif change=='step':step['logical_step_id']='foreign'
else:
run.runner_plan['metric_graph']['baseline_bindings'][0]['selection']['baseline_revision_id']='foreign'
rehash(run,step)
with pytest.raises(ValueError,match=f'^{code}$'):
resolve_scenario_screenshot_directive(run,step,binding,attempt=1)
@pytest.mark.parametrize('change',['filter','profile'])
def test_selection_filter_change_and_stale_profile_refuse(draft_storage,change):
run,step,binding,_,_=current_case()
if change=='filter':
selection=run.runner_plan['metric_graph']['baseline_bindings'][0]['selection']
selection['normalized_filters']=deepcopy(selection['normalized_filters'])
selection['normalized_filters']['filters'][0]['value']['values']=['foreign']
code='screenshot_filter_or_reference_mismatch'
else:
run.runner_plan['baseline_pin']['entries'][0]['capture_profile_hash']='0'*64
code='screenshot_profile_stale_or_ambiguous'
rehash(run,step)
with pytest.raises(ValueError,match=f'^{code}$'):
resolve_scenario_screenshot_directive(run,step,binding,attempt=1)
def test_source_query_model_fingerprint_mismatch_refuses_before_directive(draft_storage):
run,step,binding,_,_=current_case()
source=run.runner_plan['baseline_pin']['entries'][0]['reference_source']
source['query_model_fingerprint']='sha256:'+'d'*64
# Recompute only the public source digest so the model disagreement reaches its own contract.
semantics={key:source[key] for key in ('environment_id','dashboard_id','resolved_native_filters','filters_hash','query_model_fingerprint')}
source['reference_digest']=sha256(json.dumps(semantics,sort_keys=True,separators=(',',':')).encode()).hexdigest()
run.runner_plan['metric_graph']['baseline_bindings'][0]['selection']['reference_digest']=source['reference_digest']
rehash(run,step)
with pytest.raises(ValueError,match='^screenshot_filter_or_reference_mismatch$'):
resolve_scenario_screenshot_directive(run,step,binding,attempt=1)
@pytest.mark.parametrize('change,code',[('principal','screenshot_live_binding_mismatch'),('attempt','screenshot_filter_scope_unsupported')])
def test_binding_principal_mismatch_and_boolean_attempt_refuse(draft_storage,change,code):
run,step,binding,_,_=current_case()
if change=='principal':binding=replace(binding,execution_principal_fingerprint='foreign')
with pytest.raises(ValueError,match=f'^{code}$'):
resolve_scenario_screenshot_directive(run,step,binding,attempt=True if change=='attempt' else 1)
def fixture():
@@ -67,4 +151,75 @@ async def test_native_observation_refusal_still_closes_exact_session(monkeypatch
with pytest.raises(ValueError, match="^native_capture_scope_type_unsupported$"):
await observe_scenario_screenshot(Service(), SimpleNamespace(), SimpleNamespace(), directive, timeout_seconds=1)
assert closed == [(session.context, session.browser)]
# #region Test.ScreenshotDirectiveIndependent.StrictSession [C:2] [TYPE Function]
# @TEST_INVARIANT [ScenarioExecution.ScreenshotProvider.ScenarioCapture.Observe] The registered profile launches one strict session; capability and capture share it, target precedes capture, and the original resources close on success or foreign-principal refusal.
@pytest.mark.asyncio
@pytest.mark.parametrize("foreign_principal", [False, True])
async def test_capture_leaf_hands_same_strict_session_to_native_observer_and_closes(monkeypatch, foreign_principal):
import json
import playwright.async_api
from src.plugins.llm_analysis._screenshot_identity import NativeIdentityObservation, StrictScreenshotSession
from src.services.dashboard_testing.execution.providers import scenario_screenshot_capture as owner
from src.services.dashboard_testing.scenario.capture_profile import capture_profile_snapshot
profile = capture_profile_snapshot("default")
directive = SimpleNamespace(scenario_run_id="run", logical_step_id="capture", dashboard_id=2,
chart_id=8, dataset_id=4, capture_profile_sha256=profile["sha256"],
capture_profile_snapshot=json.dumps(profile).encode())
environment, model = object(), object()
original_context, original_browser = object(), object()
session = StrictScreenshotSession(original_browser, original_context, object(),
NativeIdentityObservation(27, "fixture", True, False))
capability, target = object(), object()
observation = SimpleNamespace(query=SimpleNamespace(native_user_id=99 if foreign_principal else 27,
chart_id=8, dataset_id=4), capture_profile_sha256=profile["sha256"])
calls = []
class Playwright:
async def __aenter__(self): return self
async def __aexit__(self, *args): return False
class Service:
async def _launch_and_login_with_native_identity(self, playwright, dashboard_id, **kwargs):
assert dashboard_id == "2" and kwargs == {"capture_profile_snapshot":profile}
calls.append("launch")
return session
async def _close_strict_session(self, context, browser):
assert context is original_context and browser is original_browser
calls.append("close")
service = Service()
async def observe_capability(actual_session, actual_environment, actual_directive, actual_model):
assert actual_session is session and actual_environment is environment
assert actual_directive is directive and actual_model is model
calls.append("capability")
return capability
def resolve_target(actual_directive, actual_model, actual_capability):
assert actual_directive is directive and actual_model is model and actual_capability is capability
calls.append("target")
return target
async def capture(actual_service, actual_session, actual_directive, actual_model, actual_capability, actual_target, **kwargs):
assert actual_service is service and actual_session is session and actual_directive is directive
assert actual_model is model and actual_capability is capability and actual_target is target
assert kwargs == {"timeout_seconds":3}
calls.append("capture")
return observation
monkeypatch.setattr(playwright.async_api, "async_playwright", Playwright)
monkeypatch.setattr(owner, "observe_native_visual_capture_capability", observe_capability)
monkeypatch.setattr(owner, "resolve_scenario_native_chart_query_target", resolve_target)
monkeypatch.setattr(owner, "capture_scenario_native_chart_visual", capture)
if foreign_principal:
with pytest.raises(ValueError, match="^scenario_screenshot_observation_unavailable$"):
await owner.observe_scenario_screenshot(service, environment, model, directive, timeout_seconds=3)
else:
assert await owner.observe_scenario_screenshot(service, environment, model, directive, timeout_seconds=3) is observation
assert calls == ["launch", "capability", "target", "capture", "close"]
# #endregion Test.ScreenshotDirectiveIndependent.StrictSession
# #endregion Test.ScreenshotDirectiveIndependent

View File

@@ -1,336 +1,168 @@
# #region Test.BaselineEngine.NativeChartQueryRowSetProof [C:4] [TYPE Module] [SEMANTICS test,native-query,row-set,proof]
# @BRIEF Pin the descriptor-driven row_set proof of the ScenarioRun screenshot query route.
# @RATIONALE The pinned coordinate publishes a keyed TABLE row_set, so the proof must decide that exact set instead of one scalar.
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetValue] The measured keyed row_set form is proven as the complete
# pinned set, and every divergence stays a fixed typed refusal rather than a rewritten result.
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.MetricValue] A scalar scope keeps the unchanged single-scalar reader.
import asyncio
import json
# #region Test.BaselineEngine.NativeChartQueryRowSetProof [C:3] [TYPE Module] [SEMANTICS test,chart,response,pin,proof]
# @RELATION BINDS_TO -> [BaselineEngine.NativeChartQueryPayload.Pin]
# @RELATION BINDS_TO -> [BaselineEngine.NativeChartQueryProof.Collector]
# @BRIEF Every current query, metric and key belongs to the exact observed request; old scalar routes cannot supply proof.
import copy
from hashlib import sha256
import json
from types import SimpleNamespace
import pytest
from native_table_fixtures import ORIGIN, Request, literal_body, owned_native as owned_native, record_response
from src.schemas.dashboard_testing import ComparisonPolicy, NormalizedValue
from src.schemas.dashboard_testing.native_result import NativePolicySnapshot
from src.schemas.dashboard_testing.result_descriptor import TableResultDescriptor
from src.services.dashboard_testing.native_chart_query_payload import (
metric_value,
pinned_row_set_contract,
row_set_value,
)
from src.services.dashboard_testing.chart_response_descriptor import build_observed_chart_response
from src.services.dashboard_testing.comparison import compare_values
from src.services.dashboard_testing.native_chart_query_payload import chart_query_coverage_scope, chart_response_value, pinned_chart_contract
from src.services.dashboard_testing.native_chart_query_proof import NativeChartQueryCollector
from src.services.dashboard_testing.native_chart_query_target import NativeChartQueryTarget
from src.services.dashboard_testing.native_request_format import decode_body, native_parameters, semantics_sha256
from src.services.dashboard_testing.result_values import (
canonical_json,
descriptor_sha256,
result_identity_sha256,
)
_ORIGIN = "http://fixture.invalid:80"
_KEY_COLUMN = "business_entity"
_METRIC = "selected_value_cents"
_UNITS = ("unit-a", "unit-b", "unit-c", "unit-d")
_OWNER_ID = "00000000-0000-4000-8000-000000000000"
from src.services.dashboard_testing.native_request_ownership import mint_observed_native_request, request_content
from src.services.dashboard_testing.result_values import canonical_json, descriptor_sha256, result_identity_sha256
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Fixture [C:4] [TYPE Function]
# @BRIEF Build the measured request/response/contract fixture of the pinned keyed TABLE coordinate.
# @POST The fixture mirrors the persisted shapes; only the grouping values are synthetic.
def _request_body(filters=None, columns=("business_entity",)):
return json.dumps({"datasource": {"id": 4, "type": "table"},
"form_data": {"slice_id": 8, "datasource": "4__table"},
"queries": [{"columns": list(columns), "metrics": [_METRIC],
"filters": filters if filters is not None else
[{"col": "metric_selector", "op": "IN", "val": ["sales_debt"]}]}],
"result_format": "json", "result_type": "full", "force": False},
sort_keys=True, separators=(",", ":"))
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Payload [C:1] [TYPE Function]
def payload():
return {'result': [
{'status':'success','query':'synthetic detail','colnames':['business_entity','region','selected_value_cents','cost'],
'coltypes':[1,1,0,0],'rowcount':2,'from_dttm':None,'to_dttm':None,
'data':[{'business_entity':'A','region':'N','selected_value_cents':17,'cost':4},
{'business_entity':'A','region':'S','selected_value_cents':29,'cost':9}]},
{'status':'success','query':'synthetic total','colnames':['selected_value_cents','cost'],
'coltypes':[0,0],'rowcount':1,'from_dttm':None,'to_dttm':None,
'data':[{'selected_value_cents':46,'cost':13}]}]}
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof.Payload
def _request_url():
return _ORIGIN + "/api/v1/chart/data?form_data=%7B%22slice_id%22%3A8%7D&dashboard_id=2"
_PINNED_SEMANTICS = semantics_sha256(decode_body(_request_body()), native_parameters(_request_url(), _ORIGIN, 2, 8))
def _response_bytes(units=_UNITS, metric_values=(1, 2, 3, 4)):
return json.dumps({"result": [{
"status": "success", "error": None, "rowcount": len(units),
"colnames": [_KEY_COLUMN, _METRIC], "coltypes": [1, 0],
"data": [{_KEY_COLUMN: unit, _METRIC: value} for unit, value in zip(units, metric_values, strict=True)],
"query": "SELECT 1",
}]}, sort_keys=True, separators=(",", ":")).encode()
def _descriptor(*, key_columns=(_KEY_COLUMN,), semantics=_PINNED_SEMANTICS):
extra = [{"name": name, "generic_type_code": 1, "nullable": True}
for name in key_columns if name != _KEY_COLUMN]
return TableResultDescriptor.model_validate({
"schema_version": 1, "canonicalization_version": 1, "kind": "table", "scope": "native_query_result",
"query_semantics_sha256": semantics, "chart_id": 8, "dataset_id": 4, "selected_metric": _METRIC,
"columns": ({"name": _KEY_COLUMN, "generic_type_code": 1, "nullable": True}, *extra,
{"name": _METRIC, "generic_type_code": 0, "nullable": True}),
"key_columns": key_columns,
"native_request": {"content_ref": "draft:" + _OWNER_ID + ":" + "1" * 64, "sha256": "1" * 64},
})
def _scalar_policy(kind="exact"):
return {"type": kind, "amount": None, "ratio": "0.1" if kind == "relative_tolerance" else None,
"min": None, "max": None,
"min_inclusive": True, "max_inclusive": True, "keys": None,
"order_sensitive": True, "allow_extra_rows": False, "per_column": None}
def _policy_snapshot(*, keys=(_KEY_COLUMN,), allow_extra_rows=False, order_sensitive=False,
policy_type="row_set", per_column=None):
policy = {"type": policy_type, "amount": None, "ratio": None, "min": None, "max": None,
"min_inclusive": True, "max_inclusive": True, "keys": list(keys),
"order_sensitive": order_sensitive, "allow_extra_rows": allow_extra_rows,
"per_column": per_column if per_column is not None else {_METRIC: _scalar_policy()}}
descriptor = _descriptor()
return NativePolicySnapshot.model_validate({
"schema_version": 1, "result_identity_sha256": result_identity_sha256(descriptor), "comparison_policy": policy,
})
def _binding(*, descriptor=None, snapshot=None, descriptor_digest=None, policy_digest=None,
expected_keys=_UNITS, identity=None):
descriptor = descriptor or _descriptor()
snapshot = snapshot or _policy_snapshot()
descriptor_bytes = canonical_json(descriptor.model_dump(mode="json"))
policy_bytes = canonical_json(snapshot.model_dump(mode="json"))
return SimpleNamespace(
result_descriptor=descriptor_bytes,
result_descriptor_sha256=descriptor_digest or descriptor_sha256(descriptor),
result_policy=policy_bytes,
result_policy_sha256=policy_digest or sha256(policy_bytes).hexdigest(),
result_identity_sha256=identity if identity is not None else result_identity_sha256(descriptor),
result_expected_keys=expected_keys,
)
def _target():
return NativeChartQueryTarget(chart_id=8, chart_uuid="chart-fixture", dataset_id=4, result_key=_METRIC,
filter_id="NATIVE_FILTER-FINANCE-METRIC", filter_column="metric_selector",
filter_values=("sales_debt",), filters_hash="f" * 64,
query_model_fingerprint="m" * 64, reference_digest="r" * 64)
class _Request:
method = "POST"
def __init__(self, body=None, url=None):
self.post_data = body if body is not None else _request_body()
self.url = url or _request_url()
self.post_data_json = json.loads(self.post_data)
class _Response:
status = 200
headers = {"content-type": "application/json"}
def __init__(self, request, raw):
self.request, self.url, self._raw = request, request.url, raw
async def body(self):
return self._raw
def _collect(contract, response_bytes, request=None):
request = request or _Request()
collector = NativeChartQueryCollector(page=object(), target=_target(), contract=contract,
service=SimpleNamespace(env=SimpleNamespace(url=_ORIGIN)), dashboard_id=2)
collector.on_request(request)
asyncio.run(collector.read_response(_Response(request, response_bytes)))
return collector
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Fixture [C:2] [TYPE Function]
@pytest.fixture
def chart(owned_native):
owned=owned_native
model=owned['model']
model.charts[0].metrics.append(type(model.charts[0].metrics[0])(metric_name='cost',label='Cost',expression_type='SAVED_METRIC'))
model.datasets[0].columns.append(type(model.datasets[0].columns[0])(column_name='region',type='STRING',groupby=True))
body=literal_body()
body['queries'][0].update(columns=['business_entity','region'],metrics=['selected_value_cents','cost'])
total=copy.deepcopy(body['queries'][0]);total.update(columns=[],row_limit=0)
body['queries'].append(total)
request=Request('POST',owned['request'].url,json.dumps(body),body)
owned['collector'].on_request(request)
record_response(owned['collector'],request,payload())
handle=mint_observed_native_request(owned['collector'],owned['session'],model,owned['capability'],owned['target'],ORIGIN,committed_state_sha256='a'*64)
content=request_content(handle);ref=owned['storage'].store(owned['run_id'],sha256(content).hexdigest(),content)
descriptor,envelope=build_observed_chart_response(handle,model,ref)
policy=ComparisonPolicy(type='chart_response',query_policies=[
{'query_index':0,'query_sha256':descriptor.queries[0].query_sha256,'key_columns':['business_entity','region'],
'per_column':{'business_entity':{'type':'exact'},'region':{'type':'exact'},'selected_value_cents':{'type':'exact'},'cost':{'type':'exact'}}},
{'query_index':1,'query_sha256':descriptor.queries[1].query_sha256,'key_columns':[],
'per_column':{'selected_value_cents':{'type':'exact'},'cost':{'type':'exact'}}}])
snapshot=NativePolicySnapshot(schema_version=1,result_identity_sha256=result_identity_sha256(descriptor),comparison_policy=policy)
policy_bytes=canonical_json(snapshot.model_dump(mode='json'))
binding=SimpleNamespace(result_descriptor=canonical_json(descriptor.model_dump(mode='json')),
result_policy=policy_bytes,result_descriptor_sha256=descriptor_sha256(descriptor),
result_policy_sha256=sha256(policy_bytes).hexdigest(),result_identity_sha256=result_identity_sha256(descriptor),
result_chart_scope=chart_query_coverage_scope(descriptor))
return SimpleNamespace(owned=owned,body=body,request=request,binding=binding,
descriptor=descriptor,expected=envelope.normalized_value,policy=policy,contract=pinned_chart_contract(binding))
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof.Fixture
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Pin [C:3] [TYPE Function]
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetPin] The published table pin resolves into one bound contract.
def test_published_table_pin_resolves_into_a_bound_row_set_contract():
binding = _binding()
contract = pinned_row_set_contract(binding)
assert contract.descriptor.kind == "table"
assert contract.key_column() == _KEY_COLUMN
assert (contract.policy.type.value, tuple(contract.policy.keys), contract.policy.allow_extra_rows) == (
"row_set", (_KEY_COLUMN,), False)
assert contract.descriptor_sha256 == binding.result_descriptor_sha256
assert contract.policy_sha256 == binding.result_policy_sha256
assert contract.expected_keys == _UNITS
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Pin [C:2] [TYPE Function]
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.Pin] Complete descriptor/policy/identity/coverage bind exactly; no scalar/default contract survives a missing pin.
@pytest.mark.parametrize('field',['result_descriptor','result_policy','result_descriptor_sha256','result_policy_sha256','result_identity_sha256','result_chart_scope'])
def test_missing_or_conflicting_pin_refuses(chart,field):
binding=copy.copy(chart.binding)
setattr(binding,field,None if field in {'result_descriptor','result_policy','result_chart_scope'} else 'f'*64)
with pytest.raises(ValueError,match='^CHART_RESPONSE_PIN_(REQUIRED|CONFLICT)$'):
pinned_chart_contract(binding)
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetPin] A scope that pins no table contract keeps the scalar reader.
def test_scope_without_a_table_pin_keeps_the_scalar_path():
assert pinned_row_set_contract(SimpleNamespace()) is None
scalar_form = json.dumps({"result": [{"data": [{_METRIC: 4}], "query": "SELECT 1"}]}).encode()
assert metric_value(json.loads(scalar_form), _target()) == ("integer", "4")
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.Value] Both composite-key detail and keyless total retain every literal metric.
def test_complete_chart_receipt_keeps_all_queries_metrics_and_keys(chart):
kind,canonical=chart_response_value(json.dumps(payload()).encode(),chart.contract)
queries=json.loads(canonical)['queries']
assert kind=='chart_response'
assert queries[0]['columns']==['business_entity','region','selected_value_cents','cost']
assert queries[0]['rows']==[['A','N','17','4'],['A','S','29','9']]
assert queries[1]['rows']==[['46','13']]
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.MetricValue] The scalar reader still refuses a multi-row answer.
def test_scalar_reader_still_refuses_the_measured_multi_row_form():
assert metric_value(json.loads(_response_bytes()), _target()) is None
# @TEST_INVARIANT [BaselineEngine.ChartResponseComparison.Compare] Data changes are named comparison failures; valid changed cardinality cannot be rewritten into a receipt error.
@pytest.mark.parametrize('query_index,column',[(0,'selected_value_cents'),(0,'cost'),(1,'selected_value_cents'),(1,'cost')])
def test_every_query_metric_has_named_failure(chart,query_index,column):
changed=payload();changed['result'][query_index]['data'][0][column]+=1
kind,canonical=chart_response_value(json.dumps(changed).encode(),chart.contract)
result=compare_values(NormalizedValue(kind=kind,canonical_value=canonical),chart.expected,chart.policy)
assert result.status=='fail' and len(result.changed_cells)==1
cell=result.changed_cells[0]
assert cell.column==column and json.loads(cell.key)[0]==f'query:{query_index}'
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetPin] A carried contract is never partially trusted.
@pytest.mark.parametrize("binding", [
SimpleNamespace(result_descriptor=b"{}"),
_binding(descriptor_digest="0" * 64),
_binding(identity="0" * 64),
_binding(policy_digest="0" * 64),
_binding(snapshot=_policy_snapshot(allow_extra_rows=True)),
_binding(snapshot=_policy_snapshot(keys=("party_status",))),
_binding(snapshot=_policy_snapshot(per_column={_KEY_COLUMN: _scalar_policy("relative_tolerance")})),
_binding(snapshot=_policy_snapshot(per_column={"unknown_column": _scalar_policy()})),
_binding(expected_keys=()),
_binding(expected_keys=("unit-a", "unit-a")),
])
def test_pin_that_disagrees_with_its_own_digests_or_policy_refuses(binding):
with pytest.raises(ValueError) as refused:
pinned_row_set_contract(binding)
@pytest.mark.parametrize('change',['missing','extra','key'])
def test_changed_row_membership_is_comparison_failure(chart,change):
changed=payload();entry=changed['result'][0]
if change=='missing': entry['data'].pop()
elif change=='extra': entry['data'].append({'business_entity':'B','region':'N','selected_value_cents':7,'cost':2})
else: entry['data'][0]['business_entity']='B'
entry['rowcount']=len(entry['data'])
kind,canonical=chart_response_value(json.dumps(changed).encode(),chart.contract)
assert compare_values(NormalizedValue(kind=kind,canonical_value=canonical),chart.expected,chart.policy).status=='fail'
assert refused.value.args[0] in {
"native_query_row_set_contract_unavailable", "native_query_row_set_descriptor_conflict",
"native_query_row_set_policy_conflict",
}
def test_fixed_key_order_is_canonical_and_composite_keys_are_supported(chart):
changed=payload();changed['result'][0]['data'].reverse()
kind,canonical=chart_response_value(json.dumps(changed).encode(),chart.contract)
assert compare_values(NormalizedValue(kind=kind,canonical_value=canonical),chart.expected,chart.policy).status=='pass'
@pytest.mark.parametrize('change',['missing_query','extra_query','duplicate_key','missing_column','extra_column','metric_text','non_success','scalar'])
def test_malformed_or_partial_result_never_supplies_receipt(chart,change):
changed=payload();entry=changed['result'][0]
if change=='missing_query':changed['result'].pop()
elif change=='extra_query':changed['result'].append(copy.deepcopy(changed['result'][1]))
elif change=='duplicate_key':entry['data'][1]['region']='N'
elif change=='missing_column':del entry['data'][0]['cost']
elif change=='extra_column':entry['data'][0]['foreign']=1
elif change=='metric_text':entry['data'][0]['cost']='not-a-number'
elif change=='non_success':entry['status']='failed'
else:changed={'result':[{'status':'success','colnames':['selected_value_cents'],'coltypes':[0], 'rowcount':1,'data':[{'selected_value_cents':17}]}]}
with pytest.raises(ValueError): chart_response_value(json.dumps(changed).encode(),chart.contract)
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof.Pin
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.RowSet [C:4] [TYPE Function]
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetValue] The measured keyed form is proven as the complete pinned set.
def test_measured_keyed_row_set_form_is_proven():
contract = pinned_row_set_contract(_binding())
kind, canonical = row_set_value(_response_bytes(), contract)
decoded = json.loads(canonical)
assert kind == "table"
assert decoded["columns"] == [_KEY_COLUMN, _METRIC]
assert tuple(row[0] for row in decoded["rows"]) == _UNITS
assert tuple(row[1] for row in decoded["rows"]) == ("1", "2", "3", "4")
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Collector [C:2] [TYPE Function]
def collect(chart,wire,body=None):
request=chart.request if body is None else Request('POST',chart.request.url,json.dumps(body),body)
collector=NativeChartQueryCollector(object(),chart.owned['target'],contract=chart.contract,
service=SimpleNamespace(env=SimpleNamespace(url=ORIGIN)),dashboard_id=2)
collector.on_request(request)
raw=json.dumps(wire).encode()
response=SimpleNamespace(request=request,url=request.url,status=200,headers={'content-type':'application/json'})
collector.record_success(collector.requests[request],response,wire,raw)
return collector
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetValue] Row order follows the pinned policy, never a silent re-sort.
def test_row_order_matters_only_when_the_pinned_policy_declares_it():
reordered = _response_bytes(units=tuple(reversed(_UNITS)), metric_values=(4, 3, 2, 1))
assert row_set_value(reordered, pinned_row_set_contract(_binding()))[0] == "table"
ordered_binding = _binding(snapshot=_policy_snapshot(order_sensitive=True))
with pytest.raises(ValueError) as refused:
row_set_value(reordered, pinned_row_set_contract(ordered_binding))
assert refused.value.args[0] == "native_query_row_set_keys_changed"
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] Current receipt binds exact owned request and all query counts, never a scalar or old load.
def test_collector_issues_current_complete_chart_receipt(chart):
collector=collect(chart,payload())
assert collector.refusal_code is None and collector.proof_value[0]=='chart_response'
assert collector.chart_receipt.wire_row_counts==(2,1)
assert collector.chart_receipt.canonical_row_counts==(2,1)
next_request=Request('POST',chart.request.url,json.dumps(chart.body),copy.deepcopy(chart.body))
collector.on_request(next_request)
assert collector.proof_value is None and collector.chart_receipt is None
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetValue] Every divergence from the pinned set is a fixed typed refusal.
@pytest.mark.parametrize(("label", "mutate", "code"), [
("missing row", lambda data: data.pop(), "native_query_row_set_keys_changed"),
("extra unknown row", lambda data: data.append({_KEY_COLUMN: "unit-extra", _METRIC: 5}),
"native_query_row_set_keys_changed"),
("foreign key", lambda data: data[0].__setitem__(_KEY_COLUMN, "unit-foreign"), "native_query_row_set_keys_changed"),
("renamed key on the last row", lambda data: data[3].__setitem__(_KEY_COLUMN, "unit-z"),
"native_query_row_set_keys_changed"),
("duplicated row", lambda data: data.append(dict(data[0])), "native_query_row_set_key_unsupported"),
("empty key", lambda data: data[0].__setitem__(_KEY_COLUMN, ""), "native_query_row_set_key_unsupported"),
("extra column", lambda data: data[0].__setitem__("extra", "x"), "native_query_row_set_result_unsupported"),
("missing column", lambda data: data[0].pop(_METRIC), "native_query_row_set_result_unsupported"),
("string metric cell", lambda data: data[0].__setitem__(_METRIC, "1"), "RESULT_VALUE_INVALID"),
("bool metric cell", lambda data: data[0].__setitem__(_METRIC, True), "RESULT_VALUE_INVALID"),
("infinite metric cell", lambda data: data[0].__setitem__(_METRIC, float("inf")), "RESULT_VALUE_INVALID"),
])
def test_every_row_set_divergence_stays_a_fixed_refusal(label, mutate, code):
contract = pinned_row_set_contract(_binding())
payload = json.loads(_response_bytes())
mutate(payload["result"][0]["data"])
with pytest.raises(ValueError) as refused:
row_set_value(json.dumps(payload).encode(), contract)
assert refused.value.args[0] == code, label
@pytest.mark.parametrize('query_index',[0,1])
def test_changed_owned_request_semantics_refuses_before_value(chart,query_index):
body=copy.deepcopy(chart.body);body['queries'][query_index]['row_limit']=99
collector=collect(chart,payload(),body)
assert collector.proof_value is None and collector.chart_receipt is None
assert collector.refusal_code=='CHART_RESPONSE_REQUEST_CHANGED'
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetValue] A non-single-entry envelope never becomes a row_set.
@pytest.mark.parametrize("payload", [
{"result": []},
{"result": [{"data": []}, {"data": []}]},
{"result": "not-a-list"},
{"result": [{"data": []}]},
])
def test_non_single_entry_envelope_is_refused(payload):
with pytest.raises(ValueError) as refused:
row_set_value(json.dumps(payload).encode(), pinned_row_set_contract(_binding()))
assert refused.value.args[0] == "native_query_row_set_result_unsupported"
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryPayload.RowSetContract.KeyColumn] A pinned multi-key row_set is not approximated.
def test_multi_key_pinned_row_set_refuses_instead_of_picking_one_key():
two_keys = (_KEY_COLUMN, "party_status")
contract = pinned_row_set_contract(_binding(descriptor=_descriptor(key_columns=two_keys),
snapshot=_policy_snapshot(keys=two_keys)))
with pytest.raises(ValueError) as refused:
contract.key_column()
assert refused.value.args[0] == "native_query_row_set_key_unsupported"
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof.RowSet
# #region Test.BaselineEngine.NativeChartQueryRowSetProof.Collector [C:4] [TYPE Function]
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] The collector proves the row_set of the pinned request.
def test_collector_proves_the_row_set_of_the_pinned_request():
collector = _collect(pinned_row_set_contract(_binding()), _response_bytes())
assert collector.refusal_code is None
assert collector.proof_value is not None and collector.proof_value[0] == "table"
assert collector.current_success(8).row_counts == (4,)
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] A foreign request semantics digest never proves the pin.
def test_collector_refuses_a_request_whose_semantics_differ_from_the_pin():
foreign = _Request(body=_request_body(columns=("party_status",)))
collector = _collect(pinned_row_set_contract(_binding()), _response_bytes(), request=foreign)
assert collector.proof_value is None
assert collector.refusal_code == "native_query_row_set_semantics_changed"
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] A table contract never falls back to a scalar read.
def test_collector_refuses_the_scalar_form_under_a_table_contract():
scalar_form = json.dumps({"result": [{"status": "success", "rowcount": 1, "colnames": [_KEY_COLUMN, _METRIC],
"coltypes": [1, 0], "data": [{_KEY_COLUMN: "unit-a", _METRIC: 1}],
"query": "SELECT 1"}]}).encode()
collector = _collect(pinned_row_set_contract(_binding()), scalar_form)
assert collector.proof_value is None
assert collector.refusal_code == "native_query_row_set_keys_changed"
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] A scalar scope never reads a multi-row answer.
def test_collector_scalar_scope_refuses_the_multi_row_form():
collector = _collect(None, _response_bytes())
assert collector.proof_value is None
assert collector.refusal_code == "native_query_result_shape_unsupported"
# @TEST_INVARIANT [BaselineEngine.NativeChartQueryProof.Collector.PinnedResult] A scalar scope keeps reading its single-row form.
def test_collector_scalar_scope_still_reads_the_single_row_form():
scalar_form = json.dumps({"result": [{"status": "success", "rowcount": 1, "colnames": [_METRIC], "coltypes": [0],
"data": [{_METRIC: 4}], "query": "SELECT 1"}]}).encode()
collector = _collect(None, scalar_form)
assert collector.refusal_code is None
assert collector.proof_value == ("integer", "4")
def test_partial_response_has_no_collector_proof(chart):
wire=payload();wire['result'].pop()
collector=collect(chart,wire)
assert collector.proof_value is None and collector.chart_receipt is None
assert collector.refusal_code=='CHART_RESPONSE_QUERY_COUNT_INVALID'
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof.Collector
# #endregion Test.BaselineEngine.NativeChartQueryRowSetProof

View File

@@ -4,18 +4,13 @@ from hashlib import sha256
from types import SimpleNamespace
import pytest
from test_native_result_leaf4 import issued as issued, prepared_entry
from admitted_metric_fixture import literal_graph
from src.services.dashboard_testing.result_values import canonical_json
from src.services.dashboard_testing.fingerprints import compute_sha256
from src.services.dashboard_testing.catalog_revision_wiring import build_entry_revisions
from src.services.dashboard_testing.execution.baseline_resolver import _pin_entry
from src.services.dashboard_testing.execution.live_binding import LiveExecutionBinding
from src.services.dashboard_testing.execution.native_metric_inputs import validate_native_metric_inputs, resolve_native_metric_inputs
from src.services.dashboard_testing.scenario.native_metric_contract import native_coordinate_id
from src.services.dashboard_testing.scenario.native_metric_contract import NativeMetricCoordinate, NativeMetricResultSchemaAuthority
from src.services.dashboard_testing.scenario.profile_baseline_snapshot import ProfileBaselineSelection
from src.services.dashboard_testing.scenario.metric_compiler import compile_metric_baseline_scenario
from src.schemas.dashboard_testing import DashboardQueryModel
from src.services.dashboard_testing.scenario.native_metric_contract import NativeMetricCoordinate
# #region Test.NativeMetricInputs.Digest [C:1] [TYPE Function]
@@ -26,38 +21,12 @@ def digest(value):
# #region Test.NativeMetricInputs.Scope [C:3] [TYPE Function]
@pytest.fixture
def scope(issued):
entry, meta = prepared_entry(issued)
wrapper = build_entry_revisions(entry, meta)[0]
def scope():
# Explicit structural input to a pure immutable-plan validator, not persisted PG admission.
fixture = literal_graph()
wrapper, graph = fixture.wrapper, fixture.scenario
pin_row = _pin_entry(wrapper)
source = pin_row['reference_source']
coordinate = dict(coordinate_id=native_coordinate_id(8, 4, 'selected_value_cents',
issued['record'].result_identity_sha256), environment_id=source['environment_id'],
reference_environment_id=source['environment_id'], dashboard_id=2, chart_id=8, dataset_id=4,
metric_name='selected_value_cents', value_type='table',
query_model_fingerprint=source['query_model_fingerprint'],
normalized_filters=entry.normalized_filters.model_dump(mode='json'),
native_result=entry.native_result.model_dump(mode='json'))
selection = dict(selection_version=1, unresolved_id='literal-question', coordinate_id=coordinate['coordinate_id'],
normalized_filters=coordinate['normalized_filters'], baseline_set='literal', baseline_set_version='1',
baseline_id=wrapper['baseline_id'], baseline_revision_id=wrapper['baseline_revision_id'],
entry_digest=wrapper['entry_digest'], coordinate_hash=wrapper['coordinate_hash'],
catalog_revision_id='literal-revision', catalog_digest='a'*64, release_id='literal-release',
release_version='v1.2.3', release_commit_hash='a'*40, publication_commit_hash='b'*40,
reference_digest=source['reference_digest'])
selection['selection_digest'] = digest(selection)
model = DashboardQueryModel(environment_id=source['environment_id'], dashboard_id=2, title='Literal',
query_model_fingerprint=source['query_model_fingerprint'], charts=[dict(chart_id=8, slice_name='Literal',
viz_type='table', dataset_id=4, dataset_name='Literal', metrics=[dict(metric_name='selected_value_cents',
label='Literal', expression_type='SAVED_METRIC')])])
authority = dict(schema_version=1, coordinate=coordinate, value_type='table',
execution_principal_fingerprint='p'*64, rls_security_fingerprint='r'*64)
authority['authority_digest'] = digest(authority)
graph = compile_metric_baseline_scenario(query_model=model,
coordinate=NativeMetricCoordinate.model_validate_json(canonical_json(coordinate), strict=True),
selection=ProfileBaselineSelection.model_validate_json(canonical_json(selection), strict=True),
objective='Literal native TABLE', inspected_value_type='table',
schema_authority=NativeMetricResultSchemaAuthority.model_validate_json(canonical_json(authority), strict=True))
binding_model = graph.baseline_bindings[0]
binding = binding_model.model_dump(mode='json')
producer_id = graph.steps[0].id
@@ -69,10 +38,10 @@ def scope(issued):
_freeze_binding({producer_id: producer_meta, binding_model.comparison_step_id: comparator_meta},
binding_model, wrapper)
meta = producer_meta
live = LiveExecutionBinding('literal-binding-ref', source['environment_id'], 'literal-release', 'a'*64,
2, source['query_model_fingerprint'], 'p'*64, 'r'*64, None, None,
live = LiveExecutionBinding('literal-binding-ref', source['environment_id'], fixture.selection.release_id, 'a'*64,
10, source['query_model_fingerprint'], 'p'*64, 'r'*64, None, None,
'scenario_run', 'draft_storage_raw_response')
pin = dict(entries=[pin_row], release_id='literal-release', release_version='v1.2.3', release_commit_hash='a'*40)
pin = dict(entries=[pin_row], release_id=fixture.selection.release_id, release_version=fixture.selection.release_version, release_commit_hash=fixture.selection.release_commit_hash)
plan = dict(metric_admission_version=1, steps=[meta], scenario_revision_id='literal-revision',
scenario_content_hash=graph.revision_hash, baseline_pin=pin,
metric_graph=graph.model_dump(mode='json'), metric_binding_digests=[binding['binding_digest']])
@@ -94,13 +63,13 @@ def scope(issued):
# #region Test.NativeMetricInputs.Positive [C:1] [TYPE Function]
# @TEST_INVARIANT [ScenarioExecution.NativeMetricInputs.Validate] Original published policy and exact committed attempt survive mutable manual root loss.
def test_frozen_native_inputs(scope, issued):
def test_frozen_native_inputs(scope):
step, run, child = scope
issued['run'].context_snapshot = {}
result = validate_native_metric_inputs(step, run, child)
assert result.attempt == 3 and result.coordinate.chart_id == 8
assert result.native_result.policy_snapshot.comparison_policy.order_sensitive is False
assert result.native_result.policy_snapshot.comparison_policy.keys == ['unit_key']
assert result.attempt == 3 and result.coordinate.chart_id == 79
assert result.native_result.policy_snapshot.comparison_policy.type == 'chart_response'
assert result.native_result.policy_snapshot.comparison_policy.query_policies[0].key_columns == []
assert set(result.native_result.policy_snapshot.comparison_policy.query_policies[0].per_column) == {'row_id','event_date','region','product','revenue','cost','units','debt','overdue'}
# #endregion Test.NativeMetricInputs.Positive
@@ -254,15 +223,15 @@ def test_nonempty_filter_changes_refuse(scope, change):
step, run, child = scope
bound = PublishedComparisonBinding.model_validate_json(canonical_json(step['step_meta']['metric_baseline_binding']), strict=True)
item = NormalizedFilter(filter_id='literal-filter', dataset_id=4, column='unit_key',
operator='IN', value={'values':['unit-a']}, target_chart_ids=[8])
filters = NormalizedFilterContext(filters=[item], filters_hash=_compute_filters_hash([item]))
operator='IN', value={'state':'selected','values':['unit-a']}, target_chart_ids=[8])
filters = NormalizedFilterContext(schema_version=1, filters=[item], filters_hash=_compute_filters_hash([item]))
coordinate = bound.coordinate.model_copy(update={'normalized_filters':filters})
source = build_reference_source(url='https://fixture.invalid/superset/dashboard/2/', url_kind='dashboard',
source_url_ref='draft:00000000-0000-0000-0000-000000000071:'+'a'*64,
environment_id=coordinate.environment_id, dashboard_id=2, filters=filters.model_dump(mode='json'),
query_model_fingerprint=coordinate.query_model_fingerprint)
binding = SimpleNamespace(coordinate=coordinate, producer_step_id=child.logical_step_id,
selection=SimpleNamespace(reference_digest=source['reference_digest'], release_id='literal-release'))
selection=SimpleNamespace(reference_digest=source['reference_digest'], release_id=bound.selection.release_id))
if change == 'value':
source['resolved_native_filters'][0]['value']['values'] = ['foreign-unit']
elif change == 'operator':

View File

@@ -5,23 +5,21 @@
import copy
from hashlib import sha256
import json
from pathlib import Path
from uuid import uuid4
import jsonschema
import pytest
from src.models.agent_run import DraftArtifact
from src.schemas.dashboard_testing.catalog import BaselineEntry
from src.services.storage_holds import load_index
from src.services.dashboard_testing.result_values import canonical_json, descriptor_sha256, result_identity_sha256
from src.services.dashboard_testing.native_reference_policy import native_policy_snapshot, native_table_policy
from native_table_fixtures import literal_policy
from src.schemas.dashboard_testing.catalog_revision import CatalogEntryRevision
from src.services.dashboard_testing.native_result_catalog import require_entry_native_result
from src.services.dashboard_testing.native_result_publication import prepare_native_candidate
from src.services.dashboard_testing.candidate_helpers import _meta_to_entry
from src.services.dashboard_testing.catalog_revision_wiring import coordinate_identity, build_entry_revisions
from src.services.dashboard_testing.execution.baseline_resolver import _pin_entry
from src.services.dashboard_testing.reconciliation import _reconcile_entry, _reconcile_from_schema_entry
from src.services.dashboard_testing.result_authority import capture_context_sha256
from test_result_authority import capture as primary_capture, issue
@@ -30,7 +28,6 @@ from test_result_authority import capture as primary_capture, issue
def issued(db_session, draft_storage, user_id):
fixture = primary_capture.__wrapped__(db_session, draft_storage, user_id)
run = fixture['run']
run.context_snapshot = {**run.context_snapshot, 'native_result_policy': native_policy_snapshot(fixture['descriptor'])}
fixture['context_sha'] = capture_context_sha256(run, user_id)
record = issue(fixture)
value = fixture['envelope'].normalized_value.model_dump(mode='json')
@@ -38,9 +35,10 @@ def issued(db_session, draft_storage, user_id):
'release_id': run.context_snapshot['release_id'], 'result_key':'selected_value_cents', 'label':'Literal offline',
'candidate_value':value, 'source_response_hash':record.source_response_hash,
'capture_artifact_ref':record.capture_artifact_id,
'comparison_policy':native_table_policy(record.descriptor).model_dump(mode='json'),
'comparison_policy':literal_policy().model_dump(mode='json'),
'normalized_filters':fixture['request'].normalized_filters.model_dump(mode='json'),
'reference_source':run.context_snapshot['reference_source'],
'catalog_binding':run.context_snapshot['catalog_binding'],
'provenance':{'environment':run.environment_id, 'actor':user_id, 'agent_run_id':run.id}}
candidate = DraftArtifact(id=str(uuid4()), run_id=run.id, kind='baseline_candidate', name='Literal',
intended_path='literal.yaml', content_ref=record.capture_content_ref, sha256=record.source_response_hash,
@@ -55,7 +53,7 @@ def issued(db_session, draft_storage, user_id):
def prepared_entry(issued):
meta = dict(issued['meta'])
prepare_native_candidate(issued['db'], issued['candidate'], meta, issued['owner'])
meta['capture_profile_sha256'] = 'f'*64
meta['capture_profile_sha256'] = issued['run'].context_snapshot['capture_profile']['sha256']
return _meta_to_entry(meta, 'v1.2.3', 'a'*40), meta
# #endregion Test.NativeResultLeaf4.Entry
@@ -63,21 +61,15 @@ def prepared_entry(issued):
def test_lossless_entry_schema_roundtrip_and_pin(issued):
entry, meta = prepared_entry(issued)
payload = entry.model_dump(mode='json')
canonical = _reconcile_entry(payload)
schema = json.loads(Path('specs/037-superset-baseline-engine/contracts/baseline-catalog.schema.json').read_text())
jsonschema.Draft202012Validator(schema).validate({'schema_version':1, 'dashboard':{'id':2, 'title':'Literal'}, 'entries':[canonical]})
invalidated = copy.deepcopy(canonical)
invalidated['status'] = 'invalidated'
invalidated['policy']['zero_absolute_fallback'] = None
jsonschema.Draft202012Validator(schema).validate({'schema_version':1, 'dashboard':{'id':2, 'title':'Literal'}, 'entries':[invalidated]})
loaded = BaselineEntry.model_validate(_reconcile_from_schema_entry(canonical))
loaded = BaselineEntry.model_validate_json(canonical_json(payload))
assert loaded.native_result == entry.native_result
assert loaded.source_response_hash == entry.native_result.authority_record.source_response_hash
assert require_entry_native_result(loaded.model_dump(mode="json")) is not None
wrapper = build_entry_revisions(entry, meta)[0]
old_pin = _pin_entry(wrapper)
typed = CatalogEntryRevision.model_validate_json(canonical_json(wrapper))
old_pin = _pin_entry(typed.model_dump(mode='json'))
assert old_pin['native_result'] == payload['native_result']
assert json.loads(entry.expected.canonical_value)['rows'] == [['unit-a','100'],['unit-b','200']]
assert json.loads(entry.expected.canonical_value)['queries'][0]['rows'] == [['A','17'],['B','29'],['C','31'],['D','43']]
frozen = canonical_json(old_pin)
issued['run'].context_snapshot = {'foreign_latest_context':True}
assert canonical_json(_pin_entry(wrapper)) == frozen
@@ -86,51 +78,22 @@ def test_lossless_entry_schema_roundtrip_and_pin(issued):
# #region Test.NativeResultLeaf4.OptionalFallback [C:2] [TYPE Function]
# @TEST_INVARIANT BaselineEngine.NativeResultPolicy.OptionalOperand: absent fallback preserves native policy identity bytes.
def test_optional_zero_fallback_preserves_native_policy_bytes(issued):
from src.schemas.dashboard_testing import ComparisonPolicy
descriptor = issued['record'].descriptor
snapshot = native_policy_snapshot(descriptor)
policy = snapshot['comparison_policy']
assert 'zero_absolute_fallback' not in policy
expected = {
'type': 'row_set', 'amount': None, 'ratio': None, 'min': None, 'max': None,
'min_inclusive': True, 'max_inclusive': True,
'keys': list(descriptor.key_columns), 'order_sensitive': False,
'allow_extra_rows': False,
'per_column': {descriptor.selected_metric: {
'type': 'exact', 'amount': None, 'ratio': None, 'min': None, 'max': None,
'min_inclusive': True, 'max_inclusive': True, 'keys': None,
'order_sensitive': True, 'allow_extra_rows': False, 'per_column': None,
}},
}
assert policy == expected
legacy_snapshot = {
'schema_version': 1, 'result_identity_sha256': 'a' * 64,
'comparison_policy': expected,
}
assert sha256(canonical_json(legacy_snapshot)).hexdigest() == (
'f3531a61f99fe5998826e38f442d99128476d7cc191d3e0e60f176de5cf362a1'
)
assert canonical_json(snapshot['comparison_policy']) == canonical_json(expected)
assert 'zero_absolute_fallback' in ComparisonPolicy(
type='relative_tolerance', ratio='0.01', zero_absolute_fallback=None,
).model_dump(mode='json')
assert ComparisonPolicy(
type='relative_tolerance', ratio='0.01', zero_absolute_fallback='2.5',
).model_dump(mode='json')['zero_absolute_fallback'] == '2.5'
with pytest.raises(ValueError):
ComparisonPolicy(type='exact', zero_absolute_fallback='1')
with pytest.raises(ValueError):
ComparisonPolicy(type='relative_tolerance', ratio='0.1', zero_absolute_fallback='-1')
with pytest.raises(ValueError):
ComparisonPolicy(type='exact', unexpected_policy_field=True)
from src.schemas.dashboard_testing.results import ScalarComparisonPolicy
from src.services.dashboard_testing.native_reference_policy import require_native_result_policy
policy = require_native_result_policy(issued['run'].context_snapshot, issued['descriptor'])
assert policy.type == 'chart_response'
assert policy.query_policies[0].key_columns == ['business_entity']
for column in ('business_entity','selected_value_cents'):
assert 'zero_absolute_fallback' not in policy.query_policies[0].per_column[column].model_dump(mode='json')
assert 'zero_absolute_fallback' in ScalarComparisonPolicy(type='relative_tolerance',ratio='0.01',zero_absolute_fallback=None).model_dump(mode='json')
assert ScalarComparisonPolicy(type='relative_tolerance',ratio='0.01',zero_absolute_fallback='2.5').zero_absolute_fallback == '2.5'
with pytest.raises(ValueError): ScalarComparisonPolicy(type='exact',zero_absolute_fallback='1')
with pytest.raises(ValueError): ScalarComparisonPolicy(type='relative_tolerance',ratio='0.1',zero_absolute_fallback='-1')
with pytest.raises(ValueError): ScalarComparisonPolicy(type='exact',unexpected_policy_field=True)
entry, _ = prepared_entry(issued)
invalid = _reconcile_entry(entry.model_dump(mode='json'))
invalid['policy'].update(type='exact', zero_absolute_fallback='1')
schema = json.loads(Path('specs/037-superset-baseline-engine/contracts/baseline-catalog.schema.json').read_text())
assert list(jsonschema.Draft202012Validator(schema).iter_errors({
'schema_version': 1, 'dashboard': {'id': 2, 'title': 'Literal'}, 'entries': [invalid],
}))
invalid = entry.model_dump(mode='json')
invalid['comparison_policy']['query_policies'][0]['per_column']['selected_value_cents']['zero_absolute_fallback'] = '1'
with pytest.raises(ValueError): BaselineEntry.model_validate_json(canonical_json(invalid))
# #endregion Test.NativeResultLeaf4.OptionalFallback
# #region Test.NativeResultLeaf4.Missing [C:2] [TYPE Function]
@@ -146,10 +109,10 @@ def test_runtime_malformed_or_mixed_representation_refuses(issued, change):
'mixed_policy': (('policy',), 'set', payload['comparison_policy']),
'missing_canonical': (('expected','canonical_value'), 'delete', None),
'missing_snapshot': (('native_result','policy_snapshot'), 'delete', None),
'changed_snapshot': (('native_result','policy_snapshot','comparison_policy','allow_extra_rows'), 'set', True),
'changed_snapshot': (('native_result','policy_snapshot','comparison_policy','query_policies',0,'per_column','selected_value_cents','type'), 'set', 'relative_tolerance'),
'policy_hash': (('native_result','policy_sha256'), 'set', '0'*64),
'snapshot_identity': (('native_result','policy_snapshot','result_identity_sha256'), 'set', '0'*64),
'missing_policy_operand': (('native_result','policy_snapshot','comparison_policy','order_sensitive'), 'delete', None),
'missing_policy_operand': (('native_result','policy_snapshot','comparison_policy','query_policies',0,'per_column','selected_value_cents','type'), 'delete', None),
}
keys, operation, value = mutations[change]
target = payload
@@ -171,7 +134,7 @@ def test_same_semantics_new_artifact_release_value_keeps_family(issued):
before = entry.model_dump(mode='json')
after = copy.deepcopy(before)
after.update(release_version='v2.0.0', release_commit_hash='b'*40)
after['expected']['canonical_value'] = '{"columns":["unit_key","selected_value_cents"],"rows":[["unit-a","123"],["unit-b","456"]]}'
after['expected']['canonical_value'] = after['expected']['canonical_value'].replace('\"17\"','\"123\"')
record = after['native_result']['authority_record']
descriptor = record['descriptor']
descriptor['native_request']['content_ref'] = 'draft:00000000-0000-0000-0000-000000000009:' + descriptor['native_request']['sha256']
@@ -197,15 +160,19 @@ def test_changed_semantics_different_family(issued, change):
record = after['native_result']['authority_record']
descriptor = record['descriptor']
if change == 'query':
descriptor['query_semantics_sha256'] = 'e'*64
descriptor['queries'][0]['query_sha256'] = 'e'*64
value=json.loads(after['expected']['canonical_value']);value['queries'][0]['query_sha256']='e'*64
after['expected']['canonical_value']=canonical_json(value).decode()
else:
descriptor['columns'][0]['nullable'] = True
descriptor['queries'][0]['columns'][0]['nullable'] = True
record['descriptor_sha256'] = descriptor_sha256(descriptor)
record['result_identity_sha256'] = result_identity_sha256(descriptor)
record['canonical_value_digest'] = validate_result_value(descriptor, NormalizedValue.model_validate(after['expected']))
after['native_result']['authority_record_sha256'] = sha256(canonical_json(record)).hexdigest()
from src.services.dashboard_testing.result_values import require_result_descriptor
snapshot = native_policy_snapshot(require_result_descriptor(descriptor))
snapshot = copy.deepcopy(issued['run'].context_snapshot['native_result_policy'])
snapshot['result_identity_sha256'] = result_identity_sha256(require_result_descriptor(descriptor))
snapshot['comparison_policy']['query_policies'][0]['query_sha256'] = descriptor['queries'][0]['query_sha256']
after['native_result']['policy_snapshot'] = snapshot
after['native_result']['policy_sha256'] = sha256(canonical_json(snapshot)).hexdigest()
assert coordinate_identity(before,'f'*64) != coordinate_identity(after,'f'*64)
@@ -223,7 +190,7 @@ def test_primary_authority_refuses_forgery(issued, change):
elif change == 'value':
meta['candidate_value']['canonical_value'] = '{"columns":[],"rows":[]}'
elif change == 'policy':
meta['comparison_policy']['allow_extra_rows'] = True
meta['comparison_policy']['query_policies'][0]['per_column']['selected_value_cents']['type'] = 'relative_tolerance'
else:
issued['run'].context_snapshot = {key:value for key,value in issued['run'].context_snapshot.items() if key!='result_authority'}
issued['candidate'].capture_meta = meta
@@ -305,27 +272,25 @@ def test_publication_attestation_refuses_missing_hold_without_promotion(issued,
# #region Test.NativeResultLeaf4.VisualRoundtrip [C:2] [TYPE Function]
# @TEST_INVARIANT DashboardTesting.Schemas.VisualBaselineEntry: linked native descriptor/policy survives canonical serialization and pin.
def test_linked_visual_current_schema_roundtrip_and_pin(issued):
from src.schemas.dashboard_testing import ComparisonPolicy, VisualBaselineEntry
from src.services.dashboard_testing.reconciliation_visual import _reconcile_visual_entry, _reconcile_visual_entry_to_schema
from src.schemas.dashboard_testing import VisualBaselineEntry
from src.schemas.dashboard_testing.results import VisualComparisonPolicy
entry, meta = prepared_entry(issued)
payload = entry.model_dump(mode='json')
image_sha = 'd'*64
visual = VisualBaselineEntry(native_result=payload['native_result'], baseline_id=entry.baseline_id,
visual = VisualBaselineEntry(schema_version=1, native_result=payload['native_result'], baseline_id=entry.baseline_id,
release_version='v1.2.3', release_commit_hash='a'*40, dashboard_id=2,
normalized_filters=entry.normalized_filters, tab_identifier='tab-literal',
expected_image_sha256=image_sha, expected_image_content_ref=f"draft:{issued['run'].id}:{image_sha}",
source_response_hash='e'*64, captured_at=entry.captured_at,
policy=ComparisonPolicy(type='visual_exact'), fingerprints={'query':'a'*64,'dataset':'b'*64,'filter':'c'*64,'layout':'d'*64},
policy=VisualComparisonPolicy(type='visual_exact'), fingerprints={'query':'a'*64,'dataset':'b'*64,'filter':'c'*64,'layout':'d'*64},
provenance=entry.provenance, approval={'by':issued['owner'],'at':entry.created_at},
visual_review_disposition_id='00000000-0000-0000-0000-000000000091', visual_review_disposition_sha256='f'*64,
created_at=entry.created_at)
canonical = _reconcile_visual_entry_to_schema(visual.model_dump(mode='json'))
schema = json.loads(Path('specs/037-superset-baseline-engine/contracts/baseline-catalog.schema.json').read_text())
jsonschema.Draft202012Validator(schema).validate({'schema_version':1,'dashboard':{'id':2,'title':'Literal'},'entries':[canonical]})
canonical = visual.model_dump(mode='json')
invalidated = copy.deepcopy(canonical)
invalidated['status'] = 'invalidated'
jsonschema.Draft202012Validator(schema).validate({'schema_version':1,'dashboard':{'id':2,'title':'Literal'},'entries':[invalidated]})
loaded = VisualBaselineEntry.model_validate(_reconcile_visual_entry(canonical))
VisualBaselineEntry.model_validate_json(canonical_json(invalidated))
loaded = VisualBaselineEntry.model_validate_json(canonical_json(canonical))
assert loaded.native_result == visual.native_result
visual_meta = {**meta, 'review_disposition_id': visual.visual_review_disposition_id,
'review_disposition_sha256': visual.visual_review_disposition_sha256, 'review_status': 'confirmed'}