diff --git a/docs/operations.md b/docs/operations.md index fc54ebff0..042396f38 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -448,6 +448,16 @@ including phase, process outcome, cleanup and recording time. A successful read exits 0. Invalid references, archive integrity failures and mismatched revisions exit 2. +The execution view preserves the committed `generation_record_ref` in full. +Reports and Dashboards show its attempt ID, fixed record revision and SHA-256, +without displaying its artifact location. A null reference is shown as +"Not linked"; an older saved view without the field is shown as "Unknown". +Reading the view does not open the referenced generation or resolve a current +record, so it can still present a link whose source is unavailable. This is a +recorded association, not a fresh lineage authorization or an assessment. +A missing or malformed reference field in a v1 committed record is an archive +integrity failure; it is not converted to an unlinked record. + The same read-only view is available through `inferrsi.apps.api.read_attempt_view`. The legacy `status --run-id` form reads the legacy experiment directory. diff --git a/src/inferrsi/apps/views/attempt.py b/src/inferrsi/apps/views/attempt.py index 8759b979a..fe55a84c6 100644 --- a/src/inferrsi/apps/views/attempt.py +++ b/src/inferrsi/apps/views/attempt.py @@ -13,6 +13,7 @@ _EXECUTION_FIELDS = ( "run_id", "attempt_id", "record_version", "phase", "started", "side_effect_unknown", "process_outcome", "exit_code", "recorded_at", "prepared_ref", + "generation_record_ref", ) _CLAIM_FIELDS = ("claim_id", "validation_scope", "verdict", "reasons", "missing_evidence") _TRACE_FIELDS = { @@ -49,6 +50,11 @@ def read_attempt_view( ): raise ValueError("expected a v1 committed record") execution = {field: record[field] for field in _EXECUTION_FIELDS} + generation = execution["generation_record_ref"] + if generation is not None: + _check_ref(generation, "attempt_id", "record_version") + if generation["artifact"]["media_type"] != "application/json": + raise ValueError("expected a JSON generation record reference") execution["cleanup_status"] = record["cleanup"]["status"] candidate = record["candidate"] execution["candidate_id"] = candidate["candidate_id"] if candidate is not None else None diff --git a/src/inferrsi/apps/views/attempt_html.py b/src/inferrsi/apps/views/attempt_html.py index c07c9540b..4190d1c44 100644 --- a/src/inferrsi/apps/views/attempt_html.py +++ b/src/inferrsi/apps/views/attempt_html.py @@ -25,6 +25,20 @@ def _table(rows: list[dict], columns: tuple[tuple[str, str], ...]) -> str: ) +def _generation_facts(execution: dict) -> tuple: + source = execution.get("generation_record_ref") + if "generation_record_ref" not in execution or not isinstance(source, (dict, type(None))): + values = (None, None, None) + elif source is None: + values = ("Not linked", "—", "—") + else: + artifact = source.get("artifact") + values = (source.get("attempt_id"), source.get("record_version"), + artifact.get("sha256") if isinstance(artifact, dict) else None) + return tuple(zip(("Generation attempt", "Generation record revision", "Generation SHA-256"), + values, strict=True)) + + def render_attempt(view: dict, *, title: str) -> str: """Present the shared read model without exposing raw log or artifact paths.""" execution, assessment, trace = view["execution"], view["assessment"], view["trace"] @@ -35,6 +49,7 @@ def render_attempt(view: dict, *, title: str) -> str: ("Record SHA-256", view["record_ref"]["artifact"]["sha256"]), ("Recorded at", execution["recorded_at"]), ("Candidate", execution["candidate_id"]), + *_generation_facts(execution), ("Phase", execution["phase"]), ("Process outcome", execution["process_outcome"]), ("Exit code", execution["exit_code"]), diff --git a/tests/test_apps_assess.py b/tests/test_apps_assess.py index c054bacfc..733e44e5d 100644 --- a/tests/test_apps_assess.py +++ b/tests/test_apps_assess.py @@ -335,6 +335,7 @@ def test_fixed_attempt_view_keeps_process_facts_and_claim_outcomes_separate(offl **{key: record[key] for key in ( "run_id", "attempt_id", "record_version", "phase", "started", "side_effect_unknown", "process_outcome", "exit_code", "recorded_at", "prepared_ref", + "generation_record_ref", )}, "candidate_id": record["candidate"]["candidate_id"], "cleanup_status": record["cleanup"]["status"], diff --git a/tests/test_apps_fixed_cpu_views.py b/tests/test_apps_fixed_cpu_views.py index 7d2e7540a..91172f026 100644 --- a/tests/test_apps_fixed_cpu_views.py +++ b/tests/test_apps_fixed_cpu_views.py @@ -3,28 +3,52 @@ import json import subprocess import sys +from copy import deepcopy from pathlib import Path from threading import Thread from unittest.mock import patch from urllib.request import urlopen +import pytest + from inferrsi.apps import api as apps_api from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard_live import DashboardServer from inferrsi.contracts.json_v1 import encode from inferrsi.harness.api import Harness from inferrsi.harness.generation import prepare_generation -from inferrsi.harness.run_store import Claim, RunStore +from inferrsi.harness.run_store import Claim, RunStore, RunStoreReader from tests import test_harness_generation_seal as seal_tests from tests.test_apps_generation_plan import generation as generation from tests.test_harness_generation_seal import cpu_generation as cpu_generation -def test_real_cpu_record_is_shared_by_all_read_only_surfaces(cpu_generation, tmp_path, capsys): +@pytest.mark.parametrize("linked", [False, True], ids=["unlinked", "controlled-link"]) +def test_real_cpu_record_is_shared_by_all_read_only_surfaces( + cpu_generation, tmp_path, capsys, linked, +): store, target, harness, _, inputs = cpu_generation spec = prepare_generation(store, target, **inputs) record = harness.execute(spec) assert record["exit_code"] == 0 + generation_ref = None + if linked: + generation_ref = deepcopy(record["record_ref"]) + following = deepcopy(spec) + following.update(harness.allocate(**{key: inputs["attempt"][key] for key in ( + "run_id", "owner", "target_request", "deadline_utc", "resources", "budget", + "retry_of", "retry_reason", + )})) + following["output_root"] = "linked-view/" + following["attempt_id"] + commit = Claim.commit + + def controlled_link(claim, payload, artifacts=()): + # Read-side metadata control, not production lineage admission. Both CPU runs are real. + return commit(claim, {**payload, "generation_record_ref": generation_ref}, artifacts) + + with patch.object(Claim, "commit", controlled_link): + record = harness.execute(following) + assert record["exit_code"] == 0 record_ref = record["record_ref"] before = store.committed(record["attempt_id"]) archive_root = tmp_path / "archive" @@ -49,6 +73,14 @@ def test_real_cpu_record_is_shared_by_all_read_only_surfaces(cpu_generation, tmp def forbidden(*args, **kwargs): raise AssertionError("a read-only surface attempted execution, assessment or a write") + committed = RunStoreReader.committed + + def fixed_revision_only(reader, attempt_id, record_version=None): + assert (attempt_id, record_version) == ( + record_ref["attempt_id"], record_ref["record_version"], + ) + return committed(reader, attempt_id, record_version) + with ( patch.object(Harness, "execute", forbidden), patch.object(Harness, "allocate", forbidden), @@ -56,12 +88,14 @@ def forbidden(*args, **kwargs): patch.object(Claim, "commit", forbidden), patch.object(apps_api, "assess", forbidden), patch.object(subprocess, "Popen", forbidden), + patch.object(RunStoreReader, "committed", fixed_revision_only), ): expected = apps_api.read_attempt_view(record_ref, storage_config=config) assert expected["assessment"] is None assert expected["assessment_ref"] is None assert expected["execution"]["attempt_id"] == record["attempt_id"] assert expected["execution"]["exit_code"] == 0 + assert expected["execution"]["generation_record_ref"] == generation_ref assert main(["status", *flags]) == 0 assert json.loads(capsys.readouterr().out) == expected @@ -81,6 +115,12 @@ def forbidden(*args, **kwargs): document = output.read_text(encoding="utf-8") assert record_ref["artifact"]["sha256"] in document assert record["attempt_id"] in document + if generation_ref is not None: + assert generation_ref["attempt_id"] in document + assert generation_ref["artifact"]["sha256"] in document + assert generation_ref["artifact"]["location"] not in document + else: + assert "Not linked" in document documents[command] = document with DashboardServer(None, None, 0, fixed_attempt=traced) as server: thread = Thread(target=server.serve_forever, daemon=True) diff --git a/tests/test_apps_generation_views.py b/tests/test_apps_generation_views.py new file mode 100644 index 000000000..09cdf0328 --- /dev/null +++ b/tests/test_apps_generation_views.py @@ -0,0 +1,148 @@ +"""Presentation of declared generation links, independent of H runtime admission.""" + +from copy import deepcopy +from hashlib import sha256 +from html.parser import HTMLParser + +import pytest + +from inferrsi.apps.api import read_attempt_view +from inferrsi.apps.views.attempt_html import render_attempt +from inferrsi.contracts.json_v1 import encode +from inferrsi.harness.errors import PublicError +from inferrsi.harness.generation import prepare_generation +from tests.test_apps_generation_plan import generation as generation +from tests.test_harness_generation_seal import cpu_generation as cpu_generation + + +@pytest.fixture +def archived_record(cpu_generation, tmp_path): + store, target, harness, _, inputs = cpu_generation + record = harness.execute(prepare_generation(store, target, **inputs)) + original = store.committed(record["attempt_id"]) + directory = tmp_path / "archived-controls" + directory.mkdir() + config = { + "schema_version": 1, "archive_namespace": "fixtures", "harness_namespace": "generation", + "mounts": [ + {"kind": "directory", "namespace": "fixtures", "prefix": "fixtures", + "root": str(directory)}, + {"kind": "harness_sqlite", "namespace": "generation", "prefix": "stores/generation", + "root": str(store.root)}, + ], + } + source = { + "attempt_id": "retired-generation", "record_version": 3, + "artifact": {"location": "unmounted/retired/record-3.json", "sha256": "1" * 64, + "size_bytes": 17, "media_type": "application/json"}, + } + + def archive(payload): + # Explicit archive controls derived from a real record; no lineage execution claim. + data = encode(payload) + digest = sha256(data).hexdigest() + name = f"record-{digest}.json" + (directory / name).write_bytes(data) + ref = deepcopy(original.record_ref) + ref["artifact"] = {"location": "fixtures/" + name, "sha256": digest, + "size_bytes": len(data), "media_type": "application/json"} + return ref, directory / name + + return original.payload, config, source, archive + + +def test_unavailable_generation_is_projected_in_full_without_opening_it(archived_record): + payload, config, source, archive = archived_record + payload["generation_record_ref"] = deepcopy(source) + ref, path = archive(payload) + before = path.read_bytes() + # No configured mount contains the declared retired generation source. + view = read_attempt_view(ref, storage_config=config, include_trace=True) + assert view["execution"]["generation_record_ref"] == source + document = render_attempt(view, title="Report") + assert source["attempt_id"] in document and source["artifact"]["sha256"] in document + assert source["artifact"]["location"] not in document + assert path.read_bytes() == before + view["execution"]["generation_record_ref"]["artifact"]["location"] = "changed-view" + again = read_attempt_view(ref, storage_config=config) + assert again["execution"]["generation_record_ref"] == source + + +@pytest.mark.parametrize("fault", [ + "absent", "list", "empty", "boolean-version", "zero-version", "bad-sha", "bad-media", + "extra-field", "empty-attempt", +]) +def test_malformed_generation_metadata_is_an_integrity_error(archived_record, fault): + payload, config, source, archive = archived_record + payload["generation_record_ref"] = deepcopy(source) + ref = payload["generation_record_ref"] + if fault == "absent": + payload.pop("generation_record_ref") + elif fault == "list": + payload["generation_record_ref"] = [] + elif fault == "empty": + payload["generation_record_ref"] = {} + elif fault == "boolean-version": + ref["record_version"] = True + elif fault == "zero-version": + ref["record_version"] = 0 + elif fault == "bad-sha": + ref["artifact"]["sha256"] = "not-a-sha" + elif fault == "bad-media": + ref["artifact"]["media_type"] = "text/plain" + elif fault == "extra-field": + ref["current"] = True + else: + ref["attempt_id"] = "" + record_ref, _ = archive(payload) + with pytest.raises(PublicError) as caught: + read_attempt_view(record_ref, storage_config=config) + assert (caught.value.code, caught.value.stage) == ("ArtifactIntegrityError", "attempt_view") + + +class _Facts(HTMLParser): + def __init__(self): + super().__init__() + self.facts, self.tag, self.label, self.content = {}, None, None, [] + + def handle_starttag(self, tag, attrs): + if tag in ("dt", "dd"): + self.tag, self.content = tag, [] + + def handle_data(self, data): + if self.tag is not None: + self.content.append(data) + + def handle_endtag(self, tag): + if tag != self.tag: + return + value = "".join(self.content) + if tag == "dt": + self.label = value + else: + self.facts[self.label] = value + self.tag = None + + +@pytest.mark.parametrize("missing,expected", [(False, "Not linked"), (True, "Unknown")]) +def test_null_link_and_an_old_view_snapshot_remain_distinct(archived_record, missing, expected): + payload, config, _, archive = archived_record + record_ref, _ = archive(payload) + view = read_attempt_view(record_ref, storage_config=config, include_trace=True) + assert view["execution"]["generation_record_ref"] is None + if missing: + view["execution"].pop("generation_record_ref") + parsed = _Facts() + parsed.feed(render_attempt(view, title="Dashboard")) + assert parsed.facts["Generation attempt"] == expected + assert parsed.facts["Generation record revision"] == ("Unknown" if missing else "—") + + +def test_generation_fields_are_escaped_in_an_external_snapshot(archived_record): + payload, config, source, archive = archived_record + payload["generation_record_ref"] = source + record_ref, _ = archive(payload) + view = read_attempt_view(record_ref, storage_config=config, include_trace=True) + view["execution"]["generation_record_ref"]["attempt_id"] = "" + document = render_attempt(view, title="Report") + assert "