diff --git a/backend/tests/test_dashboard_testing_lab_reset_contract.py b/backend/tests/test_dashboard_testing_lab_reset_contract.py new file mode 100644 index 000000000..dd8463d63 --- /dev/null +++ b/backend/tests/test_dashboard_testing_lab_reset_contract.py @@ -0,0 +1,350 @@ +# #region Test.LabReset.Contract [C:3] [TYPE Module] [SEMANTICS test,maintenance,offline,ownership] +# @BRIEF Independent literal guards for reset preconditions, reversible values and row-level FK ownership. +# @TEST_INVARIANT No test connects to Docker/PostgreSQL or executes an operational reset phase. +from datetime import UTC, date, datetime, time, timedelta +from decimal import Decimal +from hashlib import sha256 +import json +from pathlib import Path +import sys +from types import SimpleNamespace +from uuid import UUID + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) +import dashboard_testing_lab_reset as cli # noqa: E402 +import dashboard_testing_lab_reset_archive as archive # noqa: E402 +import dashboard_testing_lab_reset_db as database # noqa: E402 + + +# #region Test.LabReset.Contract.Codec [C:2] [TYPE Function] +# @TEST_INVARIANT Explicit independent typed encodings preserve exact SQL values without str fallback/pickle. +@pytest.mark.parametrize("value,expected", [ + (None, ["NoneType", None]), (True, ["bool", True]), (7, ["int", 7]), + ("秘密", ["str", "秘密"]), (1.25, ["float", "0x1.4000000000000p+0"]), + (b"\x00\xff", ["bytes", "AP8="]), (Decimal("17.2300"), ["Decimal", "17.2300"]), + (UUID("11111111-1111-4111-8111-111111111111"), ["UUID", "11111111-1111-4111-8111-111111111111"]), + (datetime(2026, 10, 11, tzinfo=UTC), ["datetime", "2026-10-11T00:00:00+00:00"]), + (date(2026, 10, 11), ["date", "2026-10-11"]), (time(3, 4, 5), ["time", "03:04:05"]), + (timedelta(days=-1, seconds=3, microseconds=7), ["timedelta", [-1, 3, 7]]), + ({"b": [None], "a": (True, 7)}, + ["dict", [["a", ["tuple", [["bool", True], ["int", 7]]]], ["b", ["list", [["NoneType", None]]]]]]), +]) +def test_typed_archive_has_literal_reversible_encoding(value, expected): + assert archive.encode(value) == expected + assert archive.decode(expected) == value +# #endregion Test.LabReset.Contract.Codec + + +# #region Test.LabReset.Contract.UnsupportedCodec [C:2] [TYPE Function] +@pytest.mark.parametrize("value", [object(), {1: "not-string"}, float("nan"), float("inf"), Decimal("NaN")]) +def test_unsupported_values_cannot_be_stringified(value): + with pytest.raises(archive.Stop, match="^LAB_RESET_CODEC_UNSUPPORTED$"): + archive.encode(value) +# #endregion Test.LabReset.Contract.UnsupportedCodec + + +# #region Test.LabReset.Contract.MalformedCodec [C:2] [TYPE Function] +@pytest.mark.parametrize("value", [["bool", "false"], ["NoneType", 1], ["unknown", "private"], + ["dict", [["x", ["int", 1]], ["x", ["int", 2]]]]]) +def test_noncanonical_archive_encoding_refuses(value): + with pytest.raises(archive.Stop, match="^LAB_RESET_ARCHIVE_INVALID$"): + archive.decode(value) +# #endregion Test.LabReset.Contract.MalformedCodec + + +# #region Test.LabReset.Contract.SelfFk [C:2] [TYPE Function] +# @TEST_INVARIANT scenario revision parent self-edge orders selected children first rather than ignoring the edge. +def test_self_foreign_key_uses_row_order(): + a, b, c = ("scenario_revisions", "a"), ("scenario_revisions", "b"), ("scenario_revisions", "c") + assert database.child_first([a, b, c], [(b, a), (c, b)]) == [c, b, a] + with pytest.raises(archive.Stop, match="^LAB_RESET_FK_CYCLE$"): + database.child_first([a, b], [(a, b), (b, a)]) + with pytest.raises(archive.Stop, match="^LAB_RESET_FK_CYCLE$"): + database.child_first([a], [(a, a)]) +# #endregion Test.LabReset.Contract.SelfFk + + +# #region Test.LabReset.Contract.PreservedChild [C:2] [TYPE Function] +@pytest.mark.parametrize("ondelete", ["CASCADE", "SET NULL", "RESTRICT"]) +def test_preserved_child_cannot_be_mutated_by_selected_parent(ondelete): + rows = {"parent": [{"id": 1}], "child": [{"id": 2, "parent": 1}]} + keys = {"parent": ["id"], "child": ["id"]} + chosen = {database.node("parent", rows["parent"][0], ["id"])} + fks = {"parent": [], "child": [{"constrained_columns": ["parent"], "referred_table": "parent", + "referred_columns": ["id"], "options": {"ondelete": ondelete, "deferrable": True}}]} + with pytest.raises(archive.Stop, match="^LAB_RESET_PRESERVED_CHILD_REFERENCE$"): + database.foreign_edges(rows, keys, chosen, fks) + chosen.add(database.node("child", rows["child"][0], ["id"])) + edges = database.foreign_edges(rows, keys, chosen, fks) + assert database.child_first(chosen, edges)[0][0] == "child" +# #endregion Test.LabReset.Contract.PreservedChild + + +# #region Test.LabReset.Contract.PrimaryKeys [C:2] [TYPE Function] +def test_exact_primary_keys_cannot_expand(): + scope = {"database_tables": [{"table": "t", "primary_key_columns": ["id"], + "selected_primary_keys": [{"id": 1}], "preserve_primary_keys": [{"id": 2}], + "selected_count": 1, "preserved_count": 1, "total": 2}]} + assert len(database.selected_nodes(scope, {"t": [{"id": 2}, {"id": 1}]}, {"t": ["id"]})) == 1 + with pytest.raises(archive.Stop, match="^LAB_RESET_PRIMARY_KEY_SET_CHANGED$"): + database.selected_nodes(scope, {"t": [{"id": 1}, {"id": 3}]}, {"t": ["id"]}) +# #endregion Test.LabReset.Contract.PrimaryKeys + + +# #region Test.LabReset.Contract.SelectedOnly [C:2] [TYPE Function] +def test_archive_contains_only_selected_row_bodies(): + from sqlalchemy import Column, Integer, MetaData, String, Table + table = Table("t", MetaData(), Column("id", Integer, primary_key=True), Column("body", String)) + rows = {"t": [{"id": 1, "body": "selected"}, {"id": 2, "body": "protected-secret"}]} + chosen = {database.node("t", rows["t"][0], ["id"])} + result = database.archive_rows(({"t": table}, {"t": ["id"]}, rows, chosen, [])) + assert [archive.decode(row) for row in result["t"]["rows"]] == [{"id": 1, "body": "selected"}] + assert "protected-secret" not in json.dumps(result) +# #endregion Test.LabReset.Contract.SelectedOnly + + +# #region Test.LabReset.Contract.ContainerFixture [C:1] [TYPE Function] +def container_fixture(): + return {"id": "a" * 64, "name": "/" + cli.ROLES["stage1_candidate"], "image": cli.IMAGE, + "mounts": [], "state": {"running": False, "paused": False, "restarting": False, + "dead": False, "pid": 0, "status": "exited", "finished_at": "2026-10-11T00:00:00Z"}} +# #endregion Test.LabReset.Contract.ContainerFixture + + +# #region Test.LabReset.Contract.ContainerRefusal [C:2] [TYPE Function] +@pytest.mark.parametrize("field,value,code", [("running", True, "APPLICATION_NOT_STOPPED"), + ("pid", 73, "APPLICATION_NOT_STOPPED"), ("finished_at", "0001-01-01T00:00:00Z", "STOP_TIME_REQUIRED")]) +def test_live_process_or_missing_stop_time_cannot_issue_receipt(field, value, code): + observed = container_fixture() + observed["state"][field] = value + with pytest.raises(archive.Stop, match=f"^LAB_RESET_{code}$"): + cli.validate_container(observed, {"container": cli.ROLES["stage1_candidate"], "mounts": []}) +# #endregion Test.LabReset.Contract.ContainerRefusal + + +# #region Test.LabReset.Contract.ReceiptFreshness [C:2] [TYPE Function] +def test_receipt_binds_source_and_expires(monkeypatch): + args = SimpleNamespace(source_sha="a" * 40) + hashes = {"tools": {"x": "b" * 64}} + containers = {} + scopes = {} + for role, name in cli.ROLES.items(): + scopes[role] = {"container": name, "mounts": []} + containers[role] = {**container_fixture(), "name": "/" + name} + receipt = {"schema_version": 1, "inert": True, "source_sha": "a" * 40, + "allowlist_sha256": cli.ALLOWLIST_SHA, "created_at": "2026-10-11T00:00:00+00:00", + "source_hashes": hashes, "containers": containers} + monkeypatch.setattr(cli, "source_hashes", lambda args: hashes) + cli.validate_receipt(args, {"roles": scopes}, receipt, datetime(2026, 10, 11, 0, 14, tzinfo=UTC)) + with pytest.raises(archive.Stop, match="^LAB_RESET_RECEIPT_EXPIRED$"): + cli.validate_receipt(args, {"roles": scopes}, receipt, datetime(2026, 10, 11, 0, 16, tzinfo=UTC)) + args.source_sha = "c" * 40 + with pytest.raises(archive.Stop, match="^LAB_RESET_RECEIPT_CONFLICT$"): + cli.validate_receipt(args, {"roles": scopes}, receipt) +# #endregion Test.LabReset.Contract.ReceiptFreshness + + +# #region Test.LabReset.Contract.DbIdentity [C:2] [TYPE Function] +def test_database_identity_has_independent_literal_encoding(): + body = {"database": "fixture", "address": None, "port": None, "oid": 17} + literal = b'{"address":null,"database":"fixture","oid":17,"port":null}' + assert archive.json_bytes(body) == literal + assert archive.digest(body) == sha256(literal).hexdigest() +# #endregion Test.LabReset.Contract.DbIdentity + + +# #region Test.LabReset.Contract.DbSessionRefusal [C:2] [TYPE Function] +def test_foreign_session_refuses_without_termination(): + statements = [] + class Connection: + def execute(self, statement): + statements.append(str(statement)) + return SimpleNamespace(scalar_one=lambda: 1) + with pytest.raises(archive.Stop, match="^LAB_RESET_FOREIGN_DATABASE_SESSION$"): + database.no_foreign_sessions(Connection()) + assert len(statements) == 1 and "pid<>pg_backend_pid()" in statements[0] + assert "pg_terminate_backend" not in statements[0] +# #endregion Test.LabReset.Contract.DbSessionRefusal + + +# #region Test.LabReset.Contract.HostProjection [C:3] [TYPE Function] +# @TEST_INVARIANT Host inspection reads only explicit nonsecret fields for the exact two owned container names. +def test_host_check_projects_fields_without_reading_environment(monkeypatch): + calls = [] + args = SimpleNamespace(source_root="/reviewed", source_sha="a" * 40) + scopes = {role: {"container": name, "mounts": []} for role, name in cli.ROLES.items()} + def run(argv, **kwargs): + calls.append(argv) + assert kwargs == {"capture_output": True, "text": True, "timeout": 15, "check": False} + if argv[0] == "git": + output = "a" * 40 if "rev-parse" in argv else "" + else: + assert argv[:3] == ["docker", "inspect", "--format"] + assert "Config.Env" not in argv[3] and "{{json .}}" not in argv[3] + assert ".State.FinishedAt" in argv[3] and ".Mounts" in argv[3] + output = json.dumps({**container_fixture(), "name": "/" + argv[-1]}) + return SimpleNamespace(returncode=0, stdout=output) + monkeypatch.setattr(cli.subprocess, "run", run) + monkeypatch.setattr(cli, "source_hashes", lambda args: {"literal": "b" * 64}) + result = cli.host_check(args, {"roles": scopes}) + assert result["inert"] is True and set(result["containers"]) == set(cli.ROLES) + assert [argv[-1] for argv in calls if argv[0] == "docker"] == list(cli.ROLES.values()) + assert all("exec" not in argv and "stop" not in argv and "start" not in argv for argv in calls) +# #endregion Test.LabReset.Contract.HostProjection + + +# #region Test.LabReset.Contract.ForeignIdentity [C:2] [TYPE Function] +@pytest.mark.parametrize("field,value", [("id", "foreign"), ("image", "sha256:" + "f" * 64), + ("name", "/foreign")]) +def test_foreign_container_identity_refuses(field, value): + observed = container_fixture() + observed[field] = value + with pytest.raises(archive.Stop, match="^LAB_RESET_CONTAINER_IDENTITY_CONFLICT$"): + cli.validate_container(observed, {"container": cli.ROLES["stage1_candidate"], "mounts": []}) +# #endregion Test.LabReset.Contract.ForeignIdentity + + +# #region Test.LabReset.Contract.Mounts [C:2] [TYPE Function] +@pytest.mark.parametrize("field,value", [("Source", "/foreign"), ("RW", False), ("Type", "bind")]) +def test_mount_order_is_inert_but_each_mount_field_is_exact(field, value): + one = {"Destination": "/one", "Source": "/owned-one", "RW": True, "Type": "volume"} + two = {"Destination": "/two", "Source": "/owned-two", "RW": True, "Type": "volume"} + observed = {**container_fixture(), "mounts": [two, one]} + scope = {"container": cli.ROLES["stage1_candidate"], "mounts": [one, two]} + cli.validate_container(observed, scope) + observed["mounts"] = [two, {**one, field: value}] + with pytest.raises(archive.Stop, match="^LAB_RESET_CONTAINER_MOUNTS_CHANGED$"): + cli.validate_container(observed, scope) + with pytest.raises(archive.Stop, match="^LAB_RESET_CONTAINER_MOUNTS_CHANGED$"): + cli.canonical_mounts([one, one]) +# #endregion Test.LabReset.Contract.Mounts + + +# #region Test.LabReset.Contract.UnapprovedDigest [C:2] [TYPE Function] +def test_unapproved_allowlist_digest_refuses_before_read(monkeypatch): + monkeypatch.setattr(cli, "read_json", lambda *args: pytest.fail("must not read unapproved authority")) + with pytest.raises(archive.Stop, match="^LAB_RESET_ALLOWLIST_NOT_APPROVED$"): + cli.allowlist_input(SimpleNamespace(expected_allowlist_sha256="a" * 64)) +# #endregion Test.LabReset.Contract.UnapprovedDigest + + +# #region Test.LabReset.Contract.LockOrder [C:2] [TYPE Function] +def test_table_locks_are_deterministic_before_root(monkeypatch): + calls = [] + class Connection: + dialect = SimpleNamespace(identifier_preparer=SimpleNamespace(quote=lambda name: '"' + name + '"')) + def execute(self, statement): + calls.append(str(statement)) + monkeypatch.setattr(database, "table_names", lambda *args: ["a", "z"]) + monkeypatch.setattr(database, "no_foreign_sessions", lambda *args: calls.append("foreign-session-check")) + database.lock_tables(Connection(), {}) + assert calls == ["SET LOCAL lock_timeout = '5s'", "SET LOCAL statement_timeout = '60s'", + 'LOCK TABLE public."a" IN SHARE ROW EXCLUSIVE MODE', + 'LOCK TABLE public."z" IN SHARE ROW EXCLUSIVE MODE', "foreign-session-check"] +# #endregion Test.LabReset.Contract.LockOrder + + +# #region Test.LabReset.Contract.DeleteCount [C:2] [TYPE Function] +def test_unexpected_delete_count_refuses_exact_predicate(): + from sqlalchemy import Column, Integer, MetaData, Table + table = Table("owned", MetaData(), Column("id", Integer, primary_key=True)) + row = {"id": 17} + item = database.node("owned", row, ["id"]) + statements = [] + class Connection: + def execute(self, statement): + statements.append(str(statement)) + return SimpleNamespace(rowcount=0) + with pytest.raises(archive.Stop, match="^LAB_RESET_DELETE_COUNT_CONFLICT$"): + database.delete_rows(Connection(), ({"owned": table}, {"owned": ["id"]}, + {"owned": [row]}, {item}, [item])) + assert statements == ["DELETE FROM owned WHERE owned.id = :id_1"] +# #endregion Test.LabReset.Contract.DeleteCount + + +# #region Test.LabReset.Contract.ProtectedBody [C:2] [TYPE Function] +def test_changed_protected_body_refuses_before_commit(monkeypatch): + from sqlalchemy import Column, Integer, MetaData, String, Table + table = Table("protected", MetaData(), Column("id", Integer, primary_key=True), Column("body", String)) + original = {"protected": [{"id": 1, "body": "original-private"}]} + changed = [{"id": 1, "body": "changed-private"}] + connection = SimpleNamespace(execute=lambda statement: SimpleNamespace(mappings=lambda: changed)) + monkeypatch.setattr(database, "table_names", lambda *args: ["protected"]) + monkeypatch.setattr(database, "no_foreign_sessions", lambda *args: None) + with pytest.raises(archive.Stop, match="^LAB_RESET_POST_DELETE_STATE_CONFLICT$"): + database.verify_deleted(connection, {}, {"tables": {"protected": {"preserved_count": 1}}}, + ({"protected": table}, {"protected": ["id"]}, original, set(), [])) +# #endregion Test.LabReset.Contract.ProtectedBody +# #region Test.LabReset.Contract.ProducerOwners [C:2] [TYPE Function] +# @TEST_INVARIANT Row PK membership and actual run ownership are independent; approved standalone verification never expands selection. +@pytest.mark.parametrize("change", [None, "foreign_owner", "owner_as_pk", "intent", "duplicate_run", "missing_run"]) +def test_shared_row_primary_key_and_actual_run_owner_are_distinct(change): + rows = {"agent_runs": [{"id": "run-1", "intent": "manual_reference_capture"}], + "scenario_runs": [{"id": "scenario-1"}], + "agent_run_events": [{"id": "event-1", "run_id": "run-1"}], + "provider_operation_receipts": [{"operation_id": "operation-1", "run_id": "scenario-1"}]} + keys = {name: ["operation_id" if name == "provider_operation_receipts" else "id"] for name in rows} + selected = {database.node(name, row, keys[name]) for name, values in rows.items() for row in values} + scope = {"module_agent_run_ids": ["run-1"], "module_scenario_run_ids": ["scenario-1"], + "shared_ownership": { + "agent_run_events": {"owner_column": "run_id", "linked_module_ids": ["event-1"]}, + "provider_operation_receipts": {"owner_column": "run_id", "linked_module_ids": ["operation-1"]}}} + if change == "foreign_owner": + rows["agent_run_events"][0]["run_id"] = "foreign-run" + elif change == "owner_as_pk": + scope["shared_ownership"]["agent_run_events"]["linked_module_ids"] = ["run-1"] + elif change == "intent": + rows["agent_runs"][0]["intent"] = "foreign-intent" + elif change == "duplicate_run": + scope["module_agent_run_ids"].append("run-1") + elif change == "missing_run": + scope["module_scenario_run_ids"] = [] + if change is None: + database.shared_ownership(scope, rows, keys, selected) + else: + with pytest.raises(archive.Stop, match="^LAB_RESET_OWNER_CONFLICT$"): + database.shared_ownership(scope, rows, keys, selected) +# #endregion Test.LabReset.Contract.ProducerOwners + + +# #region Test.LabReset.Contract.StandaloneVerification [C:2] [TYPE Function] +@pytest.mark.parametrize("change", [None, "category", "empty_categories", "trigger", "foreign_owner", "unselected"]) +def test_standalone_verification_requires_exact_selection_and_reviewed_intent(change): + row = {"id": "verify-1", "agent_run_id": None, "categories_run": ["metric", "structure"], "trigger": "scheduled"} + rows = {"agent_runs": [], "scenario_runs": [], "verification_runs": [row]} + keys = {name: ["id"] for name in rows} + selected = {database.node("verification_runs", row, ["id"])} + scope = {"module_agent_run_ids": [], "module_scenario_run_ids": [], "shared_ownership": { + "verification_runs": {"owner_column": "agent_run_id", "linked_module_ids": [], + "unmatched_preserve_ids": ["verify-1"]}}} + if change == "category": + row["categories_run"] = ["visual"] + elif change == "empty_categories": + row["categories_run"] = [] + elif change == "trigger": + row["trigger"] = "manual" + elif change == "foreign_owner": + row["agent_run_id"] = "foreign-run" + elif change == "unselected": + selected.clear() + row["categories_run"] = ["visual"] + if change in (None, "unselected"): + database.shared_ownership(scope, rows, keys, selected) + assert len(selected) == (0 if change == "unselected" else 1) + else: + with pytest.raises(archive.Stop, match="^LAB_RESET_OWNER_CONFLICT$"): + database.shared_ownership(scope, rows, keys, selected) +# #endregion Test.LabReset.Contract.StandaloneVerification + + +# #region Test.LabReset.Contract.DuplicatePk [C:2] [TYPE Function] +def test_duplicate_allowlist_primary_keys_cannot_collapse_into_selection(): + scope = {"database_tables": [{"table": "t", "primary_key_columns": ["id"], + "selected_primary_keys": [{"id": 1}, {"id": 1}], "preserve_primary_keys": [], + "selected_count": 2, "preserved_count": 0, "total": 2}]} + with pytest.raises(archive.Stop, match="^LAB_RESET_ALLOWLIST_INVALID$"): + database.selected_nodes(scope, {"t": [{"id": 1}, {"id": 2}]}, {"t": ["id"]}) +# #endregion Test.LabReset.Contract.DuplicatePk +# #endregion Test.LabReset.Contract diff --git a/backend/tests/test_dashboard_testing_lab_reset_storage.py b/backend/tests/test_dashboard_testing_lab_reset_storage.py new file mode 100644 index 000000000..88c8f5696 --- /dev/null +++ b/backend/tests/test_dashboard_testing_lab_reset_storage.py @@ -0,0 +1,310 @@ +# #region Test.LabReset.Storage [C:3] [TYPE Module] [SEMANTICS test,maintenance,archive,holds,offline] +# @BRIEF Offline private-file, exact-state and non-atomic failure guards; no live container or database access. +# @TEST_INVARIANT Unexpected bytes/paths/ownership/holds refuse before deletion; post-commit file failure never retries or implies rollback. +from hashlib import sha256 +import json +import os +from pathlib import Path +import sys +from types import SimpleNamespace + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) +import dashboard_testing_lab_reset as cli # noqa: E402 +import dashboard_testing_lab_reset_archive as archive # noqa: E402 +import dashboard_testing_lab_reset_db as database # noqa: E402 +import dashboard_testing_lab_reset_files as files # noqa: E402 + + +# #region Test.LabReset.Storage.PrivateWrites [C:2] [TYPE Function] +def test_private_archive_is_exclusive_and_reread(tmp_path): + tmp_path.chmod(0o700) + hashed = archive.write_bytes(tmp_path, "selected.bin", b"literal-selected-bytes") + path = tmp_path / "selected.bin" + assert path.stat().st_mode & 0o777 == 0o600 + assert archive.read_bytes(path, private=True) == b"literal-selected-bytes" + assert hashed == sha256(b"literal-selected-bytes").hexdigest() + with pytest.raises(FileExistsError): + archive.write_bytes(tmp_path, "selected.bin", b"replacement") + assert path.read_bytes() == b"literal-selected-bytes" +# #endregion Test.LabReset.Storage.PrivateWrites + + +# #region Test.LabReset.Storage.PrivateOwner [C:2] [TYPE Function] +def test_exact_input_owner_and_private_modes_are_required(tmp_path): + tmp_path.chmod(0o700) + hashed = archive.write_bytes(tmp_path, "input.json", b"{}") + path = tmp_path / "input.json" + with pytest.raises(archive.Stop, match="^LAB_RESET_PRIVATE_MODE_INVALID$"): + archive.read_json(path, hashed, private=True, owner_uid=os.geteuid() + 1) + path.chmod(0o644) + with pytest.raises(archive.Stop, match="^LAB_RESET_PRIVATE_MODE_INVALID$"): + archive.read_json(path, hashed, private=True) + tmp_path.chmod(0o755) + with pytest.raises(archive.Stop, match="^LAB_RESET_PRIVATE_MODE_INVALID$"): + archive.write_bytes(tmp_path, "other", b"x") +# #endregion Test.LabReset.Storage.PrivateOwner + + +# #region Test.LabReset.Storage.Paths [C:2] [TYPE Function] +@pytest.mark.parametrize("relative", ["../escape", "/absolute", "sub/../../escape"]) +def test_archive_path_cannot_escape(tmp_path, relative): + with pytest.raises(archive.Stop, match="^LAB_RESET_PATH_INVALID$"): + archive.safe_path(tmp_path, relative) +# #endregion Test.LabReset.Storage.Paths + + +# #region Test.LabReset.Storage.Symlink [C:2] [TYPE Function] +def test_symlink_refuses_before_any_bytes_are_read(tmp_path, monkeypatch): + target = tmp_path / "protected" + target.write_bytes(b"protected") + link = tmp_path / "link" + link.symlink_to(target) + monkeypatch.setattr(files, "read_bytes", lambda *args, **kwargs: pytest.fail("alternate read")) + with pytest.raises(archive.Stop, match="^LAB_RESET_SYMLINK_REFUSED$"): + files.member(str(tmp_path), {"path": str(link), "bytes": 9, "sha256": "a" * 64}) + assert target.read_bytes() == b"protected" +# #endregion Test.LabReset.Storage.Symlink + + +# #region Test.LabReset.Storage.ExactMember [C:2] [TYPE Function] +def test_changed_selected_bytes_cannot_be_archived_or_deleted(tmp_path): + path = tmp_path / "selected" + path.write_bytes(b"old") + expected = {"path": str(path), "bytes": 3, "sha256": sha256(b"old").hexdigest()} + assert files.member(str(tmp_path), expected) == b"old" + path.write_bytes(b"new") + with pytest.raises(archive.Stop, match="^LAB_RESET_FILE_CHANGED$"): + files.member(str(tmp_path), expected) + assert path.read_bytes() == b"new" +# #endregion Test.LabReset.Storage.ExactMember + + +# #region Test.LabReset.Storage.ArchiveReadback [C:2] [TYPE Function] +def test_archive_readback_refuses_corruption_and_scope_expansion(tmp_path): + tmp_path.chmod(0o700) + raw = b"selected-content" + hashed = sha256(raw).hexdigest() + live = tmp_path / "live-selected" + live.write_bytes(raw) + info = live.stat() + metadata = {"mode": info.st_mode & 0o777, "uid": info.st_uid, "gid": info.st_gid, "mtime_ns": info.st_mtime_ns} + item = {"path": str(live), "bytes": len(raw), "sha256": hashed} + scope = {"files": {"/app/storage": {"selected": [item]}}} + archived = [{**item, "member": "bytes-" + hashed, "file_metadata": metadata}] + archive.write_bytes(tmp_path, "bytes-" + hashed, raw) + files.verify_archive_files(scope, tmp_path, archived) + with pytest.raises(archive.Stop, match="^LAB_RESET_ARCHIVE_SCOPE_CONFLICT$"): + files.verify_archive_files(scope, tmp_path, archived + archived) + (tmp_path / ("bytes-" + hashed)).write_bytes(b"corrupt") + with pytest.raises(archive.Stop, match="^LAB_RESET_ARCHIVE_READBACK_FAILED$"): + files.verify_archive_files(scope, tmp_path, archived) +# #endregion Test.LabReset.Storage.ArchiveReadback + + +# #region Test.LabReset.Storage.JournalPrivacy [C:2] [TYPE Function] +def test_real_molecular_journal_keeps_original_cause_private(tmp_path, capsys): + tmp_path.chmod(0o700) + journal = archive.Journal(tmp_path, "archive") + journal.event("REASON", "Reviewed laboratory phase preconditions begin") + journal.failure(RuntimeError("PRIVATE-original-connection-sentinel")) + journal.close() + public = capsys.readouterr().out + assert "PRIVATE-original-connection-sentinel" not in public + events = [json.loads(line) for line in public.splitlines()] + assert [event["marker"] for event in events] == ["REASON", "EXPLORE"] + assert events[1]["error_code"] == "LAB_RESET_PRIVATE_CAUSE" + assert events[0]["trace_id"] == events[1]["trace_id"] == journal.trace + cause = tmp_path / f"cause-{journal.trace}.txt" + assert "PRIVATE-original-connection-sentinel" in cause.read_text() + assert cause.stat().st_mode & 0o777 == 0o600 +# #endregion Test.LabReset.Storage.JournalPrivacy + + +# #region Test.LabReset.Storage.ResetBoundary [C:3] [TYPE Function] +# @TEST_INVARIANT A concrete file-phase failure after DB commit is exposed once; no retry or fictitious DB rollback. +def test_file_failure_after_commit_stops_without_retry(tmp_path, monkeypatch): + args = SimpleNamespace(phase="reset", role="stage1_candidate", source_sha="a" * 40, + database_identity_sha256="b" * 64, expected_inventory_sha256="c" * 64, + expected_archive_sha256="d" * 64, evidence_dir=str(tmp_path), inventory="inventory", archive="archive") + receipt = {"source_hashes": {}, "containers": {}} + current = cli.inventory_record(args, receipt, {"tables": {}}, {}, "e" * 64) + calls = [] + monkeypatch.setattr(files, "checkpoint", lambda scope: {}) + monkeypatch.setattr(files, "validate_holds", lambda scope, state: "e" * 64) + monkeypatch.setattr(cli, "private_input", lambda args, path, sha: current) + monkeypatch.setattr(cli, "archive_check", lambda *args: None) + monkeypatch.setattr(database, "delete_rows", lambda *args: calls.append("delete")) + monkeypatch.setattr(database, "verify_deleted", lambda *args: calls.append("verify")) + def fail_files(*args): + calls.append("files") + raise archive.Stop("LAB_RESET_FILE_CHANGED") + monkeypatch.setattr(files, "reset_files", fail_files) + connection = SimpleNamespace(commit=lambda: calls.append("commit")) + journal = SimpleNamespace(event=lambda *args, **kwargs: None) + with pytest.raises(archive.Stop, match="^LAB_RESET_FILE_CHANGED$"): + cli.locked_phase(args, receipt, {}, connection, {"tables": {}}, ({}, {}, {}, set(), []), journal) + assert calls == ["delete", "verify", "commit", "files"] +# #endregion Test.LabReset.Storage.ResetBoundary + + +# #region Test.LabReset.Storage.HoldSelectedOwner [C:2] [TYPE Function] +def test_hold_owner_must_be_selected_not_merely_present(): + state = ({}, {"agent_runs": ["id"]}, {"agent_runs": [{"id": "owned"}]}, set(), []) + with pytest.raises(archive.Stop, match="^LAB_RESET_HOLD_OWNER_CONFLICT$"): + files.selected_owner(state, "agent_runs", "owned") + with pytest.raises(archive.Stop, match="^LAB_RESET_HOLD_OWNER_CONFLICT$"): + files.selected_owner(state, "agent_runs", "foreign") +# #endregion Test.LabReset.Storage.HoldSelectedOwner + + +# #region Test.LabReset.Storage.RootScope [C:2] [TYPE Function] +def test_unlisted_file_is_not_silently_adopted(tmp_path, monkeypatch): + root = str(tmp_path) + monkeypatch.setattr(files, "ROOTS", (root,)) + (tmp_path / "new").write_bytes(b"unexpected") + scope = {"files": {root: {"selected": [], "preserve": []}}} + with pytest.raises(archive.Stop, match="^LAB_RESET_FILE_SET_CHANGED$"): + files.checkpoint(scope) +# #endregion Test.LabReset.Storage.RootScope + + +# #region Test.LabReset.Storage.InputClasses [C:2] [TYPE Function] +def test_host_inputs_and_worker_outputs_have_distinct_exact_owners(tmp_path, monkeypatch): + args = SimpleNamespace(evidence_dir=str(tmp_path), input_owner_uid="1000") + calls = [] + monkeypatch.setattr(cli.os, "geteuid", lambda: 0) + monkeypatch.setattr(cli, "read_json", lambda path, sha, **kwargs: calls.append(kwargs)) + cli.private_input(args, tmp_path / "quiescence.json", "a" * 64, host=True) + cli.private_input(args, tmp_path / "inventory.json", "b" * 64) + cli.private_input(args, tmp_path / "archive.json", "c" * 64) + assert calls == [{"private": True, "owner_uid": 1000}, {"private": True, "owner_uid": 0}, + {"private": True, "owner_uid": 0}] +# #endregion Test.LabReset.Storage.InputClasses + + +# #region Test.LabReset.Storage.DigestRefusal [C:2] [TYPE Function] +def test_changed_private_receipt_digest_refuses(tmp_path): + tmp_path.chmod(0o700) + archive.write_bytes(tmp_path, "receipt", b"{}") + with pytest.raises(archive.Stop, match="^LAB_RESET_DIGEST_CONFLICT$"): + archive.read_json(tmp_path / "receipt", "a" * 64, private=True) +# #endregion Test.LabReset.Storage.DigestRefusal + + +# #region Test.LabReset.Storage.MissingPhaseInput [C:2] [TYPE Function] +def test_missing_phase_receipt_refuses_before_database(monkeypatch, tmp_path): + args = SimpleNamespace(role="stage1_candidate", database_identity_sha256="a" * 64, + quiescence_receipt=None, expected_quiescence_sha256=None) + monkeypatch.setenv("STORAGE_ROOT_PATH", "/app/storage") + monkeypatch.setattr(database, "locked_database", lambda *args: pytest.fail("must not connect")) + with pytest.raises(archive.Stop, match="^LAB_RESET_PHASE_INPUT_REQUIRED$"): + cli.worker(args, {}, SimpleNamespace()) +# #endregion Test.LabReset.Storage.MissingPhaseInput + + +# #region Test.LabReset.Storage.OriginalCommandCause [C:2] [TYPE Function] +def test_original_host_command_cause_stays_private(tmp_path, monkeypatch, capsys): + tmp_path.chmod(0o700) + monkeypatch.setattr(cli.subprocess, "run", lambda *args, **kwargs: + SimpleNamespace(returncode=1, stdout="private-original-stdout", stderr="private-original-stderr")) + journal = archive.Journal(tmp_path, "host-check") + try: + cli.command(["git", "-C", "/literal", "rev-parse", "HEAD"]) + except archive.Stop as exc: + journal.failure(exc) + journal.close() + output = capsys.readouterr().out + assert "private-original" not in output + assert json.loads(output)["error_code"] == "LAB_RESET_HOST_CHECK_FAILED" + cause = (tmp_path / f"cause-{journal.trace}.txt").read_text() + assert "private-original-stdout" in cause and "private-original-stderr" in cause +# #endregion Test.LabReset.Storage.OriginalCommandCause + + +# #region Test.LabReset.Storage.CommitOutcome [C:3] [TYPE Function] +@pytest.mark.parametrize("failure,status", [("commit", "requested_outcome_unknown"), ("journal", "confirmed")]) +def test_commit_and_postcommit_journal_failures_keep_honest_effect(tmp_path, monkeypatch, capsys, failure, status): + tmp_path.chmod(0o700) + args = SimpleNamespace(phase="reset", role="stage1_candidate", source_sha="a" * 40, + database_identity_sha256="b" * 64, expected_inventory_sha256="c" * 64, + expected_archive_sha256="d" * 64, evidence_dir=str(tmp_path), inventory="inventory", archive="archive") + receipt = {"source_hashes": {}, "containers": {}} + current = cli.inventory_record(args, receipt, {"tables": {}}, {}, "e" * 64) + calls = [] + monkeypatch.setattr(files, "checkpoint", lambda scope: {}) + monkeypatch.setattr(files, "validate_holds", lambda *args: "e" * 64) + monkeypatch.setattr(cli, "private_input", lambda *args: current) + monkeypatch.setattr(cli, "archive_check", lambda *args: None) + monkeypatch.setattr(database, "delete_rows", lambda *args: calls.append("delete")) + monkeypatch.setattr(database, "verify_deleted", lambda *args: None) + monkeypatch.setattr(files, "reset_files", lambda *args: pytest.fail("no file phase after unknown/failed journal")) + journal = archive.Journal(tmp_path, "reset") + event = journal.event + def guarded_event(marker, intent, **facts): + if failure == "journal" and facts.get("database_committed"): + raise OSError("private-journal-sentinel") + return event(marker, intent, **facts) + journal.event = guarded_event + def commit(): + calls.append("commit") + if failure == "commit": + raise OSError("private-commit-sentinel") + try: + cli.locked_phase(args, receipt, {}, SimpleNamespace(commit=commit), {"tables": {}}, + ({}, {}, {}, set(), []), journal) + except OSError as exc: + journal.failure(exc) + journal.close() + assert calls == ["delete", "commit"] + assert journal.database_commit_status == status + public = capsys.readouterr().out + assert "private-" not in public + events = [json.loads(line) for line in public.splitlines()] + assert events[-1]["payload"]["database_commit_status"] == status + assert any(event["marker"] == "REASON" and event["payload"].get("database_commit_status") + == "requested_outcome_unknown" for event in events) + assert f"database_commit_status={status}" in (tmp_path / f"cause-{journal.trace}.txt").read_text() +# #endregion Test.LabReset.Storage.CommitOutcome +# #region Test.LabReset.Storage.DraftCategory [C:2] [TYPE Function] +def test_held_bytes_use_actual_draft_category(): + ref = SimpleNamespace(content_ref="draft:11111111-1111-4111-8111-111111111111:" + "a" * 64, + sha256="a" * 64) + assert files.held_path(ref) == Path("/app/storage/drafts/11111111-1111-4111-8111-111111111111/" + "a" * 64) +# #endregion Test.LabReset.Storage.DraftCategory + + +# #region Test.LabReset.Storage.ShortJournal [C:2] [TYPE Function] +# @TEST_INVARIANT Short journal writes retain private original cause and emit one fixed public refusal without leaking it. +def test_short_journal_write_keeps_private_cause_and_safe_public_receipt(tmp_path, monkeypatch, capsys): + tmp_path.chmod(0o700) + journal = archive.Journal(tmp_path, "reset") + monkeypatch.setattr(archive.os, "write", lambda *args: 0) + journal.failure(RuntimeError("PRIVATE-short-write-original")) + journal.close() + public = capsys.readouterr().out + assert "PRIVATE-short-write-original" not in public + event = json.loads(public) + assert event["marker"] == "EXPLORE" + assert event["trace_id"] == journal.trace + assert event["error_code"] == "LAB_RESET_JOURNAL_WRITE_FAILED" + assert event["payload"]["database_commit_status"] == "not_requested" + cause = tmp_path / f"cause-{journal.trace}.txt" + assert "PRIVATE-short-write-original" in cause.read_text() + assert cause.stat().st_mode & 0o777 == 0o600 +# #endregion Test.LabReset.Storage.ShortJournal + + +# #region Test.LabReset.Storage.UnrelatedJournalStop [C:2] [TYPE Function] +def test_journal_fallback_does_not_swallow_unrelated_domain_stop(tmp_path, monkeypatch): + tmp_path.chmod(0o700) + journal = archive.Journal(tmp_path, "reset") + def fail_domain(*args, **kwargs): + raise archive.Stop("LAB_RESET_OWNER_CONFLICT") + monkeypatch.setattr(journal, "event", fail_domain) + with pytest.raises(archive.Stop, match="^LAB_RESET_OWNER_CONFLICT$"): + journal.failure(RuntimeError("private-original")) + journal.close() +# #endregion Test.LabReset.Storage.UnrelatedJournalStop +# #endregion Test.LabReset.Storage diff --git a/scripts/dashboard_testing_lab_reset.py b/scripts/dashboard_testing_lab_reset.py new file mode 100644 index 000000000..2676a6852 --- /dev/null +++ b/scripts/dashboard_testing_lab_reset.py @@ -0,0 +1,308 @@ +# #region Tooling.LabReset [C:5] [TYPE Module] [SEMANTICS laboratory,maintenance,reset,quiescence] +# @BRIEF Separate inert host receipt and explicitly invoked inventory/archive/reset for two exact owned laboratories. +# @PRE Root reviews every phase digest; caller supplies private connection and stopped-app receipt; no live operation is implied by preparation. +# @POST Any discrepancy STOPs without retry; DB commit and file reset have distinct durable journal boundaries. +# @INVARIANT No container start/stop/create, migration, app import, secret extraction, fallback selection or automatic recovery. +# @RATIONALE Root invocation separates authority review from destructive execution; current storage owner preserves DB→root order. +# @REJECTED A combined DB/files atomicity claim or a successful inventory as implicit reset authorization. +import argparse +from datetime import UTC, datetime +from hashlib import sha256 +import os +from pathlib import Path +import re +import signal +import subprocess +import sys + +from dashboard_testing_lab_reset_archive import ( + Journal, Stop, decode, digest, json_bytes, private_directory, read_json, require, write_bytes, +) + +ALLOWLIST_SHA = "7c6b5140ff3ea42e9e56a6a7e20ee0cfec0b2ab8493410855925a161b90d7a08" +IMAGE = "sha256:13834a9b54d4dd4397aa713b56087e4a28170cb8d31deb1bd51ac425b2861933" +ROLES = {"stage1_candidate": "ss-tools-stage1-backend-durable-candidate", + "own_synthetic_candidate": "ss-tools-chart-response-verify-backend-20261010"} +TOOLS = [f"dashboard_testing_lab_reset{suffix}.py" for suffix in ("", "_db", "_files", "_archive")] + + +# #region Tooling.LabReset.Arguments [C:2] [TYPE Function] +def arguments(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group(required=True) + modes.add_argument("--host-check", action="store_true") + modes.add_argument("--phase", choices=("inventory", "archive", "reset")) + parser.add_argument("--role", choices=tuple(ROLES)) + for flag in ("allowlist", "expected-allowlist-sha256", "source-sha", "source-root", "backend-root", + "specs-root", "evidence-dir", "evidence-owner-uid", "input-owner-uid"): + parser.add_argument(f"--{flag}", required=True) + for flag in ("quiescence-receipt", "expected-quiescence-sha256", "database-identity-sha256", + "inventory", "expected-inventory-sha256", "archive", "expected-archive-sha256"): + parser.add_argument(f"--{flag}") + return parser.parse_args(argv) +# #endregion Tooling.LabReset.Arguments + + +# #region Tooling.LabReset.SourceTree [C:2] [TYPE Function] +def tree_hash(root): + root = Path(root) + require(root.is_dir() and not root.is_symlink(), "LAB_RESET_SOURCE_CONFLICT") + result = [] + for path in sorted(root.rglob("*")): + if "__pycache__" in path.parts or path.suffix == ".pyc": + continue + require(not path.is_symlink(), "LAB_RESET_SOURCE_CONFLICT") + if path.is_file(): + result.append([str(path.relative_to(root)), sha256(path.read_bytes()).hexdigest()]) + return digest(result) +# #endregion Tooling.LabReset.SourceTree + + +# #region Tooling.LabReset.Source [C:2] [TYPE Function] +def source_hashes(args): + scripts = Path(args.source_root) / "scripts" + tools = {name: sha256((scripts / name).read_bytes()).hexdigest() for name in TOOLS} + return {"tools": tools, "backend_src": tree_hash(Path(args.backend_root) / "src"), + "specs": tree_hash(args.specs_root)} +# #endregion Tooling.LabReset.Source + + +# #region Tooling.LabReset.Command [C:2] [TYPE Function] +# @INVARIANT Only fixed read-only git/docker commands are reachable; stderr stays private on failure. +def command(argv): + result = subprocess.run(argv, capture_output=True, text=True, timeout=15, check=False) + if result.returncode != 0: + raise Stop("LAB_RESET_HOST_CHECK_FAILED") from subprocess.CalledProcessError( + result.returncode, argv, output=result.stdout, stderr=result.stderr) + return result.stdout.strip() +# #endregion Tooling.LabReset.Command + + +# #region Tooling.LabReset.Mounts [C:2] [TYPE Function] +def canonical_mounts(mounts): + destinations = [mount["Destination"] for mount in mounts] + require(all(isinstance(value, str) and value.startswith("/") for value in destinations) + and len(set(destinations)) == len(destinations), "LAB_RESET_CONTAINER_MOUNTS_CHANGED") + return sorted(mounts, key=lambda mount: mount["Destination"]) +# #endregion Tooling.LabReset.Mounts + + +# #region Tooling.LabReset.Container [C:3] [TYPE Function] +def validate_container(observed, scope): + require(observed["name"] == "/" + scope["container"] and observed["image"] == IMAGE + and re.fullmatch(r"[0-9a-f]{64}", observed["id"]), "LAB_RESET_CONTAINER_IDENTITY_CONFLICT") + state = observed["state"] + require(not any(state[key] for key in ("running", "paused", "restarting", "dead")) + and state["pid"] == 0 and state["status"] == "exited", "LAB_RESET_APPLICATION_NOT_STOPPED") + require(not state["finished_at"].startswith("0001-"), "LAB_RESET_STOP_TIME_REQUIRED") + require(digest(canonical_mounts(observed["mounts"])) == digest(canonical_mounts(scope["mounts"])), + "LAB_RESET_CONTAINER_MOUNTS_CHANGED") +# #endregion Tooling.LabReset.Container + + +# #region Tooling.LabReset.Host [C:3] [TYPE Function] +# @POST Receipt contains actual narrowly inspected stopped-container fields and source hashes; no worker action follows. +def host_check(args, allowlist): + require(command(["git", "-C", args.source_root, "rev-parse", "HEAD"]) == args.source_sha, + "LAB_RESET_SOURCE_CONFLICT") + require(not command(["git", "-C", args.source_root, "status", "--porcelain"]), "LAB_RESET_SOURCE_DIRTY") + template = ('{"id":{{json .Id}},"name":{{json .Name}},"image":{{json .Image}},' + '"mounts":{{json .Mounts}},"state":{"running":{{json .State.Running}},' + '"paused":{{json .State.Paused}},"restarting":{{json .State.Restarting}},' + '"dead":{{json .State.Dead}},"pid":{{json .State.Pid}},"status":{{json .State.Status}},' + '"finished_at":{{json .State.FinishedAt}}}}') + import json + containers = {} + for role, name in ROLES.items(): + observed = json.loads(command(["docker", "inspect", "--format", template, name])) + validate_container(observed, allowlist["roles"][role]) + observed["mounts"] = canonical_mounts(observed["mounts"]) + containers[role] = observed + return {"schema_version": 1, "created_at": datetime.now(UTC).isoformat(), + "allowlist_sha256": ALLOWLIST_SHA, "source_sha": args.source_sha, + "source_hashes": source_hashes(args), "containers": containers, "inert": True} +# #endregion Tooling.LabReset.Host + + +# #region Tooling.LabReset.Receipt [C:3] [TYPE Function] +def validate_receipt(args, allowlist, receipt, now=None): + require(receipt["schema_version"] == 1 and receipt["inert"] is True + and receipt["source_sha"] == args.source_sha + and receipt["allowlist_sha256"] == ALLOWLIST_SHA, "LAB_RESET_RECEIPT_CONFLICT") + age = ((now or datetime.now(UTC)) - datetime.fromisoformat(receipt["created_at"])).total_seconds() + require(0 <= age <= 900, "LAB_RESET_RECEIPT_EXPIRED") + require(set(receipt["containers"]) == set(ROLES), "LAB_RESET_RECEIPT_CONFLICT") + for role in ROLES: + validate_container(receipt["containers"][role], allowlist["roles"][role]) + stopped = datetime.fromisoformat(receipt["containers"][role]["state"]["finished_at"]) + require(stopped <= datetime.fromisoformat(receipt["created_at"]), "LAB_RESET_RECEIPT_CONFLICT") + require(receipt["source_hashes"] == source_hashes(args), "LAB_RESET_SOURCE_CONFLICT") +# #endregion Tooling.LabReset.Receipt + + +# #region Tooling.LabReset.Allowlist [C:2] [TYPE Function] +def allowlist_input(args): + require(args.expected_allowlist_sha256 == ALLOWLIST_SHA, "LAB_RESET_ALLOWLIST_NOT_APPROVED") + value = read_json(args.allowlist, ALLOWLIST_SHA, private=True, owner_uid=int(args.input_owner_uid)) + require(set(value["roles"]) == set(ROLES), "LAB_RESET_ALLOWLIST_INVALID") + for role, name in ROLES.items(): + require(value["roles"][role]["container"] == name, "LAB_RESET_ALLOWLIST_INVALID") + return value +# #endregion Tooling.LabReset.Allowlist + + +# #region Tooling.LabReset.PrivateInput [C:3] [TYPE Function] +def private_input(args, path, expected, *, host=False): + require(path and expected, "LAB_RESET_PHASE_INPUT_REQUIRED") + path = Path(path) + require(path.parent == Path(args.evidence_dir), "LAB_RESET_PRIVATE_INPUT_LOCATION") + # Exact source classes: reviewed host receipt vs prior-phase worker output. + owner = int(args.input_owner_uid) if host else os.geteuid() + return read_json(path, expected, private=True, owner_uid=owner) +# #endregion Tooling.LabReset.PrivateInput + + +# #region Tooling.LabReset.Binding [C:1] [TYPE Function] +def binding(args, receipt): + return {"role": args.role, "allowlist_sha256": ALLOWLIST_SHA, "source_sha": args.source_sha, + "source_hashes": receipt["source_hashes"], "database_identity_sha256": args.database_identity_sha256, + "containers": receipt["containers"]} +# #endregion Tooling.LabReset.Binding + + +# #region Tooling.LabReset.Inventory [C:2] [TYPE Function] +def inventory_record(args, receipt, database, files, holds): + return {"schema_version": 1, "binding": binding(args, receipt), "database": database, + "files": files, "holds_sha256": holds} +# #endregion Tooling.LabReset.Inventory + + +# #region Tooling.LabReset.ArchiveCheck [C:3] [TYPE Function] +def archive_check(args, scope, archive, inventory, state): + from dashboard_testing_lab_reset_db import archive_rows + from dashboard_testing_lab_reset_files import verify_archive_files + require(archive["inventory_sha256"] == args.expected_inventory_sha256 + and archive["binding"] == inventory["binding"], "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + require(archive["database_rows"] == archive_rows(state), "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + for table in archive["database_rows"].values(): + for row in table["rows"]: + decode(row) + verify_archive_files(scope, args.evidence_dir, archive["files"]) +# #endregion Tooling.LabReset.ArchiveCheck + + +# #region Tooling.LabReset.LockDeadline [C:2] [TYPE Function] +def lock_deadline(signum, frame): + raise Stop("LAB_RESET_ROOT_LOCK_TIMEOUT") +# #endregion Tooling.LabReset.LockDeadline + + +# #region Tooling.LabReset.LockedPhase [C:4] [TYPE Function] +# @PRE Rows/schema/ref-probes and selected row locks acquired already; root-held path takes no new DB locks. +def locked_phase(args, receipt, scope, connection, database, state, journal): + from dashboard_testing_lab_reset_db import archive_rows, delete_rows, verify_deleted + from dashboard_testing_lab_reset_files import ( + archive_files, checkpoint, reset_files, validate_holds, verify_reset, + ) + files = checkpoint(scope) + current = inventory_record(args, receipt, database, files, validate_holds(scope, state)) + journal.event("REFLECT", "Exact laboratory inventory verified under database and root locks", + selected_rows=len(state[3]), tables=len(database["tables"]), holds_sha256=current["holds_sha256"]) + if args.phase == "inventory": + return write_bytes(args.evidence_dir, "inventory.json", json_bytes(current)) + reviewed = private_input(args, args.inventory, args.expected_inventory_sha256) + require(current == reviewed, "LAB_RESET_INVENTORY_CHANGED") + if args.phase == "archive": + archive = {"schema_version": 1, "inventory_sha256": args.expected_inventory_sha256, + "binding": current["binding"], "database_rows": archive_rows(state), + "files": archive_files(scope, args.evidence_dir)} + archive_check(args, scope, archive, reviewed, state) + return write_bytes(args.evidence_dir, "archive.json", json_bytes(archive)) + archive = private_input(args, args.archive, args.expected_archive_sha256) + archive_check(args, scope, archive, reviewed, state) + journal.event("REASON", "Exact archived primary-key deletion begins") + delete_rows(connection, state) + verify_deleted(connection, scope, database, state) + journal.event("REFLECT", "Protected database contents verified before commit") + journal.event("REASON", "Database commit requested; exception leaves outcome unknown", + database_commit_status="requested_outcome_unknown") + journal.database_commit_status = "requested_outcome_unknown" + connection.commit() + journal.database_commit_status = "confirmed" + journal.event("REFLECT", "Database committed; filesystem boundary remains separate", database_committed=True) + reset_files(scope, journal) + verify_reset(scope, files) + return args.expected_archive_sha256 +# #endregion Tooling.LabReset.LockedPhase + + +# #region Tooling.LabReset.Worker [C:4] [TYPE Function] +def worker(args, allowlist, journal): + from dashboard_testing_lab_reset_db import locked_database, lock_selected, snapshot, verify_deleted + from dashboard_testing_lab_reset_files import root_lock, verify_reset + require(args.role in ROLES and args.database_identity_sha256, "LAB_RESET_PHASE_INPUT_REQUIRED") + require(os.environ["STORAGE_ROOT_PATH"] == "/app/storage", "LAB_RESET_ROOT_INVALID") + receipt = private_input(args, args.quiescence_receipt, args.expected_quiescence_sha256, host=True) + validate_receipt(args, allowlist, receipt) + if args.phase in ("archive", "reset"): + private_input(args, args.inventory, args.expected_inventory_sha256) + if args.phase == "reset": + private_input(args, args.archive, args.expected_archive_sha256) + scope = allowlist["roles"][args.role] + with locked_database(os.environ["DATABASE_URL"], scope, args.database_identity_sha256) as connection: + database, state = snapshot(connection, scope) + lock_selected(connection, state) + lock = root_lock(scope) + previous = signal.signal(signal.SIGALRM, lock_deadline) + try: + signal.alarm(5) + lock.__enter__() + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, previous) + try: + result = locked_phase(args, receipt, scope, connection, database, state, journal) + finally: + lock.__exit__(None, None, None) + if args.phase == "reset": + # A new verification transaction acquires all DB locks before reentering root. + with locked_database(os.environ["DATABASE_URL"], scope, args.database_identity_sha256) as connection: + verify_deleted(connection, scope, database, state) + with root_lock(scope): + reviewed = private_input(args, args.inventory, args.expected_inventory_sha256) + verify_reset(scope, reviewed["files"]) + return result +# #endregion Tooling.LabReset.Worker + + +# #region Tooling.LabReset.Main [C:3] [TYPE Function] +def main(argv=None): + args = arguments(argv) + for value in (args.evidence_dir, args.source_root, args.backend_root, args.specs_root): + require(Path(value).is_absolute(), "LAB_RESET_PATH_INVALID") + for root in ("/app/storage", "/app/backend/git_repos", "/app/backend/data/dashboard_testing"): + require(not Path(args.evidence_dir).is_relative_to(root), "LAB_RESET_PRIVATE_INPUT_LOCATION") + private_directory(args.evidence_dir, int(args.evidence_owner_uid)) + require(re.fullmatch(r"[0-9a-f]{40}", args.source_sha), "LAB_RESET_SOURCE_CONFLICT") + sys.path.insert(0, str(Path(args.backend_root))) + journal = Journal(args.evidence_dir, "host-check" if args.host_check else args.phase) + try: + journal.event("REASON", "Reviewed laboratory phase preconditions begin") + allowlist = allowlist_input(args) + if args.host_check: + result = write_bytes(args.evidence_dir, "quiescence.json", json_bytes(host_check(args, allowlist))) + else: + result = worker(args, allowlist, journal) + journal.event("REFLECT", "Laboratory phase completed; next phase requires review", result_sha256=result) + return 0 + except Exception as exc: + journal.failure(exc) + return 2 + finally: + journal.close() +# #endregion Tooling.LabReset.Main + + +if __name__ == "__main__": + raise SystemExit(main()) +# #endregion Tooling.LabReset diff --git a/scripts/dashboard_testing_lab_reset_archive.py b/scripts/dashboard_testing_lab_reset_archive.py new file mode 100644 index 000000000..8e8e3eb61 --- /dev/null +++ b/scripts/dashboard_testing_lab_reset_archive.py @@ -0,0 +1,230 @@ +# #region Tooling.LabReset.Archive [C:4] [TYPE Module] [SEMANTICS maintenance,archive,private,typed] +# @BRIEF Private reversible selected-state archives and safe phase receipts for the two reviewed laboratories. +# @INVARIANT Protected row bodies never enter an archive; unsupported values refuse rather than stringify. +# @RATIONALE Separate reviewed phase digests prevent inventory from authorizing deletion or automatic recovery. +# @REJECTED Pickle, whole database dumps, public exception strings and implicit archive overwrite. +import base64 +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from hashlib import sha256 +import json +import math +import os +from pathlib import Path +import stat +import traceback +from uuid import UUID, uuid4 + + +# #region Tooling.LabReset.Archive.Stop [C:1] [TYPE Class] +class Stop(RuntimeError): + """Fixed public cause; the original exception is retained only privately.""" +# #endregion Tooling.LabReset.Archive.Stop + + +# #region Tooling.LabReset.Archive.Require [C:1] [TYPE Function] +def require(condition, code): + if not condition: + raise Stop(code) +# #endregion Tooling.LabReset.Archive.Require + + +# #region Tooling.LabReset.Archive.Json [C:1] [TYPE Function] +def json_bytes(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, + allow_nan=False).encode("utf-8") +# #endregion Tooling.LabReset.Archive.Json + + +# #region Tooling.LabReset.Archive.Digest [C:1] [TYPE Function] +def digest(value): + return sha256(json_bytes(value)).hexdigest() +# #endregion Tooling.LabReset.Archive.Digest + + +# #region Tooling.LabReset.Archive.EncodeScalar [C:2] [TYPE Function] +def scalar(value): + converters = {bytes: lambda v: base64.b64encode(v).decode("ascii"), + UUID: str, Decimal: str, datetime: lambda v: v.isoformat(), + date: lambda v: v.isoformat(), time: lambda v: v.isoformat(), + timedelta: lambda v: [v.days, v.seconds, v.microseconds]} + converter = converters.get(type(value)) + require(converter is not None, "LAB_RESET_CODEC_UNSUPPORTED") + if isinstance(value, Decimal): + require(value.is_finite(), "LAB_RESET_CODEC_UNSUPPORTED") + return [type(value).__name__, converter(value)] +# #endregion Tooling.LabReset.Archive.EncodeScalar + + +# #region Tooling.LabReset.Archive.Encode [C:3] [TYPE Function] +# @POST Every supported SQL value has a reversible tagged representation; dict keys remain exact strings. +def encode(value): + if value is None or type(value) in (str, bool, int): + return [type(value).__name__, value] + if type(value) is float: + require(math.isfinite(value), "LAB_RESET_CODEC_UNSUPPORTED") + return ["float", value.hex()] + if type(value) in (list, tuple): + return [type(value).__name__, [encode(item) for item in value]] + if type(value) is dict: + require(all(type(key) is str for key in value), "LAB_RESET_CODEC_UNSUPPORTED") + return ["dict", [[key, encode(value[key])] for key in sorted(value)]] + return scalar(value) +# #endregion Tooling.LabReset.Archive.Encode + + +# #region Tooling.LabReset.Archive.Decode [C:3] [TYPE Function] +def decode(value): + require(isinstance(value, list) and len(value) == 2, "LAB_RESET_ARCHIVE_INVALID") + tag, body = value + converters = {"NoneType": lambda v: None, "str": str, "bool": bool, "int": int, + "float": float.fromhex, "bytes": lambda v: base64.b64decode(v, validate=True), + "UUID": UUID, "Decimal": Decimal, "datetime": datetime.fromisoformat, + "date": date.fromisoformat, "time": time.fromisoformat, + "timedelta": lambda v: timedelta(days=v[0], seconds=v[1], microseconds=v[2]), + "list": lambda v: [decode(item) for item in v], + "tuple": lambda v: tuple(decode(item) for item in v), + "dict": lambda v: {key: decode(item) for key, item in v}} + require(tag in converters, "LAB_RESET_ARCHIVE_INVALID") + result = converters[tag](body) + require(encode(result) == value, "LAB_RESET_ARCHIVE_INVALID") + return result +# #endregion Tooling.LabReset.Archive.Decode + + +# #region Tooling.LabReset.Archive.SafePath [C:3] [TYPE Function] +# @POST Every existing ancestor is a real directory; no symlink or lexical traversal is adopted. +def safe_path(root, relative): + root, relative = Path(root), Path(relative) + require(root.is_absolute() and not relative.is_absolute() and relative.parts + and all(part not in (".", "..") for part in relative.parts), "LAB_RESET_PATH_INVALID") + for current in [root, *root.parents]: + require(not current.is_symlink(), "LAB_RESET_SYMLINK_REFUSED") + current = root + for part in relative.parts: + current = current / part + require(not current.is_symlink(), "LAB_RESET_SYMLINK_REFUSED") + return current +# #endregion Tooling.LabReset.Archive.SafePath + + +# #region Tooling.LabReset.Archive.Read [C:3] [TYPE Function] +def read_bytes(path, private=False, owner_uid=None): + path = safe_path(Path(path).parent, Path(path).name) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + require(stat.S_ISREG(info.st_mode), "LAB_RESET_FILE_INVALID") + if private: + expected = os.geteuid() if owner_uid is None else owner_uid + require(stat.S_IMODE(info.st_mode) == 0o600 and info.st_uid == expected, + "LAB_RESET_PRIVATE_MODE_INVALID") + return stream.read() +# #endregion Tooling.LabReset.Archive.Read + + +# #region Tooling.LabReset.Archive.ReadJson [C:2] [TYPE Function] +def read_json(path, expected_sha, private=False, owner_uid=None): + raw = read_bytes(path, private, owner_uid) + require(len(expected_sha) == 64 and sha256(raw).hexdigest() == expected_sha, + "LAB_RESET_DIGEST_CONFLICT") + return json.loads(raw) +# #endregion Tooling.LabReset.Archive.ReadJson + + +# #region Tooling.LabReset.Archive.PrivateDirectory [C:2] [TYPE Function] +def private_directory(path, owner_uid=None): + path = Path(path) + require(path.is_absolute() and path.is_dir() and not path.is_symlink(), + "LAB_RESET_PRIVATE_MODE_INVALID") + require(stat.S_IMODE(path.stat().st_mode) == 0o700, "LAB_RESET_PRIVATE_MODE_INVALID") + if owner_uid is not None: + require(path.stat().st_uid == owner_uid, "LAB_RESET_PRIVATE_MODE_INVALID") + for ancestor in path.parents: + require(not ancestor.is_symlink(), "LAB_RESET_SYMLINK_REFUSED") + return path +# #endregion Tooling.LabReset.Archive.PrivateDirectory + + +# #region Tooling.LabReset.Archive.Sync [C:1] [TYPE Function] +def sync_directory(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) +# #endregion Tooling.LabReset.Archive.Sync + + +# #region Tooling.LabReset.Archive.Write [C:2] [TYPE Function] +# @POST Exclusive private durable member is reread byte-for-byte before its digest is returned. +def write_bytes(root, name, raw): + root = private_directory(root) + target = safe_path(root, name) + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + sync_directory(root) + require(read_bytes(target, private=True) == raw, "LAB_RESET_ARCHIVE_READBACK_FAILED") + return sha256(raw).hexdigest() +# #endregion Tooling.LabReset.Archive.Write + + +# #region Tooling.LabReset.Archive.Journal [C:4] [TYPE Class] +# @RELATION DEPENDS_ON -> [Std.Semantics.MolecularCoTLogging] +# @INVARIANT Public events contain only fixed causes, phase/count/hash facts; original causes stay in a separate 0600 file. +class Journal: + # #region Tooling.LabReset.Archive.Journal.Init [C:1] [TYPE Function] + def __init__(self, root, phase): + self.root, self.phase, self.trace = private_directory(root), phase, uuid4().hex + self.database_commit_status = "not_requested" + self.name = f"journal-{self.trace}.jsonl" + self.fd = os.open(self.root / self.name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + # #endregion Tooling.LabReset.Archive.Journal.Init + + # #region Tooling.LabReset.Archive.Journal.Event [C:2] [TYPE Function] + def event(self, marker, intent, *, code=None, loc=None, **facts): + from src.core.cot_logger import build_cot_event + record = build_cot_event(src="Tooling.LabReset", marker=marker, intent=intent, + trace_id=self.trace, claim="PRE: exact reviewed laboratory state", + error_code=code, loc=loc, payload={"phase": self.phase, **facts}) + raw = json_bytes(record) + b"\n" + require(os.write(self.fd, raw) == len(raw), "LAB_RESET_JOURNAL_WRITE_FAILED") + os.fsync(self.fd) + print(raw.decode("utf-8"), end="", flush=True) + # #endregion Tooling.LabReset.Archive.Journal.Event + + # #region Tooling.LabReset.Archive.Journal.Failure [C:2] [TYPE Function] + def failure(self, exc): + cause = exc.__cause__ + details = f"database_commit_status={self.database_commit_status}\n" + "".join(traceback.format_exception(exc)) + if cause is not None and hasattr(cause, "stderr"): + details += f"\nstdout:\n{cause.stdout}\nstderr:\n{cause.stderr}" + write_bytes(self.root, f"cause-{self.trace}.txt", + details.encode("utf-8")) + code = str(exc) if isinstance(exc, Stop) else "LAB_RESET_PRIVATE_CAUSE" + frames = traceback.extract_tb(exc.__traceback__) + loc = f"{Path(frames[-1].filename).name}:{frames[-1].lineno}" if frames else None + try: + self.event("EXPLORE", "Laboratory phase stopped; reviewed recovery required", + code=code, loc=loc, failure_type=type(exc).__name__, + database_commit_status=self.database_commit_status) + except (OSError, Stop) as journal_error: + if isinstance(journal_error, Stop) and str(journal_error) != "LAB_RESET_JOURNAL_WRITE_FAILED": + raise + from src.core.cot_logger import build_cot_event + print(json_bytes(build_cot_event(src="Tooling.LabReset", marker="EXPLORE", + intent="Private cause retained; phase journal unavailable", trace_id=self.trace, + error_code="LAB_RESET_JOURNAL_WRITE_FAILED", payload={"phase": self.phase, + "database_commit_status": self.database_commit_status})).decode(), flush=True) + # #endregion Tooling.LabReset.Archive.Journal.Failure + + # #region Tooling.LabReset.Archive.Journal.Close [C:1] [TYPE Function] + def close(self): + os.close(self.fd) + sync_directory(self.root) + # #endregion Tooling.LabReset.Archive.Journal.Close +# #endregion Tooling.LabReset.Archive.Journal +# #endregion Tooling.LabReset.Archive diff --git a/scripts/dashboard_testing_lab_reset_db.py b/scripts/dashboard_testing_lab_reset_db.py new file mode 100644 index 000000000..18573922b --- /dev/null +++ b/scripts/dashboard_testing_lab_reset_db.py @@ -0,0 +1,309 @@ +# #region Tooling.LabReset.Database [C:5] [TYPE Module] [SEMANTICS maintenance,postgresql,ownership,fk] +# @BRIEF Lock, inventory and delete only reviewed exact laboratory primary keys. +# @PRE Both applications stopped; explicit connection; no other client sessions; READ COMMITTED. +# @INVARIANT All database locks and reference probes precede the storage root lock; preserved rows never become delete targets. +from collections import defaultdict +from contextlib import contextmanager +from uuid import UUID + +from sqlalchemy import MetaData, and_, create_engine, inspect, select, text +from sqlalchemy.pool import NullPool + +from dashboard_testing_lab_reset_archive import digest, encode, require + + +# #region Tooling.LabReset.Database.PrimaryKey [C:2] [TYPE Function] +def primary_key(row, columns): + result = {name: row[name] for name in columns} + return {key: str(value) if isinstance(value, UUID) else value for key, value in result.items()} +# #endregion Tooling.LabReset.Database.PrimaryKey + + +# #region Tooling.LabReset.Database.Node [C:1] [TYPE Function] +def node(table, row, columns): + return table, digest(primary_key(row, columns)) +# #endregion Tooling.LabReset.Database.Node + + +# #region Tooling.LabReset.Database.Order [C:3] [TYPE Function] +# @POST Child-before-parent row order includes self-FKs; every genuine cycle refuses. +def child_first(nodes, edges): + remaining = set(nodes) + parents = defaultdict(set) + children = defaultdict(set) + for child, parent in edges: + require(child in remaining and parent in remaining, "LAB_RESET_FK_PLAN_INVALID") + parents[child].add(parent) + children[parent].add(child) + result = [] + ready = sorted(item for item in remaining if not children[item]) + while ready: + current = ready.pop(0) + remaining.remove(current) + result.append(current) + for parent in sorted(parents[current]): + children[parent].discard(current) + if not children[parent] and parent in remaining and parent not in ready: + ready.append(parent) + ready.sort() + require(not remaining, "LAB_RESET_FK_CYCLE") + return result +# #endregion Tooling.LabReset.Database.Order + + +# #region Tooling.LabReset.Database.ForeignEdges [C:4] [TYPE Function] +# @POST Actual preserved-child references refuse even for CASCADE/SET NULL/deferrable constraints. +def foreign_edges(rows, keys, selected, foreign_keys): + edges = [] + for table, fks in foreign_keys.items(): + for fk in fks: + require(fk.get("referred_schema") in (None, "public"), "LAB_RESET_FOREIGN_SCHEMA") + parent = fk["referred_table"] + require(parent in rows, "LAB_RESET_FOREIGN_TABLE") + lookup = {tuple(row[col] for col in fk["referred_columns"]): row for row in rows[parent]} + for row in rows[table]: + values = tuple(row[col] for col in fk["constrained_columns"]) + if any(value is None for value in values) or values not in lookup: + continue + target = node(parent, lookup[values], keys[parent]) + if target not in selected: + continue + child = node(table, row, keys[table]) + require(child in selected, "LAB_RESET_PRESERVED_CHILD_REFERENCE") + edges.append((child, target)) + return edges +# #endregion Tooling.LabReset.Database.ForeignEdges + + +# #region Tooling.LabReset.Database.Quiescence [C:2] [TYPE Function] +def no_foreign_sessions(connection): + count = connection.execute(text("SELECT count(*) FROM pg_stat_activity " + "WHERE datname=current_database() AND pid<>pg_backend_pid()")).scalar_one() + require(count == 0, "LAB_RESET_FOREIGN_DATABASE_SESSION") +# #endregion Tooling.LabReset.Database.Quiescence + + +# #region Tooling.LabReset.Database.Identity [C:2] [TYPE Function] +def identity(connection, expected): + row = connection.execute(text("SELECT current_database() AS database, " + "inet_server_addr()::text AS address, inet_server_port() AS port, " + "(SELECT oid FROM pg_database WHERE datname=current_database()) AS oid")).mappings().one() + require(digest(dict(row)) == expected, "LAB_RESET_DATABASE_IDENTITY_CONFLICT") +# #endregion Tooling.LabReset.Database.Identity + + +# #region Tooling.LabReset.Database.TableNames [C:2] [TYPE Function] +def table_names(connection, scope): + expected = {item["table"] for item in scope["database_tables"]} | set(scope["protected_tables"]) + inspector = inspect(connection) + require(set(inspector.get_table_names(schema="public")) == expected, + "LAB_RESET_TABLE_SET_CHANGED") + require(not inspector.get_view_names(schema="public"), "LAB_RESET_UNREVIEWED_VIEW") + return sorted(expected) +# #endregion Tooling.LabReset.Database.TableNames + + +# #region Tooling.LabReset.Database.Lock [C:3] [TYPE Function] +# @POST Every known table is write-locked in deterministic order before any root lock; no catalog/global lock. +def lock_tables(connection, scope): + names = table_names(connection, scope) + connection.execute(text("SET LOCAL lock_timeout = '5s'")) + connection.execute(text("SET LOCAL statement_timeout = '60s'")) + quote = connection.dialect.identifier_preparer.quote + for name in names: + connection.execute(text(f"LOCK TABLE public.{quote(name)} IN SHARE ROW EXCLUSIVE MODE")) + no_foreign_sessions(connection) + require(table_names(connection, scope) == names, "LAB_RESET_TABLE_SET_CHANGED") +# #endregion Tooling.LabReset.Database.Lock + + +# #region Tooling.LabReset.Database.Transaction [C:3] [TYPE Function] +@contextmanager +def locked_database(url, scope, expected_identity): + engine = create_engine(url, poolclass=NullPool, echo=False, hide_parameters=True) + try: + require(engine.dialect.name == "postgresql", "LAB_RESET_POSTGRESQL_REQUIRED") + with engine.connect().execution_options(isolation_level="READ COMMITTED") as connection: + with connection.begin(): + identity(connection, expected_identity) + no_foreign_sessions(connection) + lock_tables(connection, scope) + yield connection + finally: + engine.dispose() +# #endregion Tooling.LabReset.Database.Transaction + + +# #region Tooling.LabReset.Database.Reflection [C:3] [TYPE Function] +def reflect(connection, scope): + metadata = MetaData(schema="public") + metadata.reflect(bind=connection, only=table_names(connection, scope), resolve_fks=False) + tables = {table.name: table for table in metadata.tables.values()} + inspector = inspect(connection) + keys = {name: [column.name for column in table.primary_key] for name, table in tables.items()} + require(all(keys.values()), "LAB_RESET_PRIMARY_KEY_REQUIRED") + fks = {name: inspector.get_foreign_keys(name, schema="public") for name in tables} + rows = {name: [dict(row) for row in connection.execute(select(table)).mappings()] + for name, table in tables.items()} + return tables, keys, fks, rows +# #endregion Tooling.LabReset.Database.Reflection + + +# #region Tooling.LabReset.Database.Selected [C:3] [TYPE Function] +def selected_nodes(scope, rows, keys): + selected = set() + for item in scope["database_tables"]: + name = item["table"] + require(keys[name] == item["primary_key_columns"], "LAB_RESET_PRIMARY_KEY_CHANGED") + expected = item["selected_primary_keys"] + item["preserve_primary_keys"] + actual = [primary_key(row, keys[name]) for row in rows[name]] + require(len(expected) == len(set(map(digest, expected))), "LAB_RESET_ALLOWLIST_INVALID") + require(len(actual) == item["total"] and sorted(map(digest, actual)) == sorted(map(digest, expected)), + "LAB_RESET_PRIMARY_KEY_SET_CHANGED") + require(len(item["selected_primary_keys"]) == item["selected_count"] + and len(item["preserve_primary_keys"]) == item["preserved_count"], + "LAB_RESET_ALLOWLIST_INVALID") + for key in item["selected_primary_keys"]: + selected.add((name, digest(key))) + return selected +# #endregion Tooling.LabReset.Database.Selected + + +# #region Tooling.LabReset.Database.ModuleRunOwners [C:3] [TYPE Function] +# @POST Revalidate the producer's exact run PK sets and AgentRun intents; never discover or expand selection. +def module_run_owners(scope, rows, keys, selected): + for table, field in (("agent_runs", "module_agent_run_ids"), ("scenario_runs", "module_scenario_run_ids")): + expected = scope[field] + chosen = [row for row in rows[table] if node(table, row, keys[table]) in selected] + require(len(expected) == len(set(expected)) and set(expected) == {str(row["id"]) for row in chosen}, + "LAB_RESET_OWNER_CONFLICT") + if table == "agent_runs": + require(all(row["intent"] in ("manual_reference_capture", "build_dashboard_test_scenario") + for row in chosen), "LAB_RESET_OWNER_CONFLICT") +# #endregion Tooling.LabReset.Database.ModuleRunOwners + + +# #region Tooling.LabReset.Database.SharedRowOwner [C:3] [TYPE Function] +# @INVARIANT linked_module_ids names row PKs; run-owner identity is independently checked against the producer run sets. +def shared_row_owner(scope, name, row, keys): + owner = scope["shared_ownership"][name] + require(len(keys[name]) == 1, "LAB_RESET_OWNER_CONFLICT") + identity = str(row[keys[name][0]]) + agents, scenarios = set(scope["module_agent_run_ids"]), set(scope["module_scenario_run_ids"]) + if name == "verification_runs": + categories = row["categories_run"] + require(isinstance(categories, list) and categories and all(type(value) is str for value in categories) + and set(categories).issubset({"metric", "structure"}) + and row["trigger"] in ("release_create", "release_publish", "scheduled"), "LAB_RESET_OWNER_CONFLICT") + # Reviewed database_tables selection explicitly includes standalone NULL-owner verification rows. + if row["agent_run_id"] is None: + return + require(identity in owner["linked_module_ids"], "LAB_RESET_OWNER_CONFLICT") + if name == "scenario_artifacts": + require(row["owner_type"] == "scenario_run" and row["owner_id"] in scenarios, "LAB_RESET_OWNER_CONFLICT") + return + allowed = agents | scenarios if name in ("provider_capacity_leases", "provider_operation_receipts") else agents + require(row[owner["owner_column"]] in allowed, "LAB_RESET_OWNER_CONFLICT") +# #endregion Tooling.LabReset.Database.SharedRowOwner + + +# #region Tooling.LabReset.Database.SharedOwnership [C:3] [TYPE Function] +def shared_ownership(scope, rows, keys, selected): + module_run_owners(scope, rows, keys, selected) + for name in scope["shared_ownership"]: + for row in rows[name]: + if node(name, row, keys[name]) not in selected: + continue + shared_row_owner(scope, name, row, keys) +# #endregion Tooling.LabReset.Database.SharedOwnership + + +# #region Tooling.LabReset.Database.Protected [C:3] [TYPE Function] +def protected_checkpoint(scope, rows, keys, tables): + for name, expected in scope["protected_tables"].items(): + actual = [primary_key(row, keys[name]) for row in rows[name]] + require([column.name for column in tables[name].columns] == expected["columns"] + and keys[name] == expected["primary_key_columns"] and len(actual) == expected["count"], + "LAB_RESET_PROTECTED_SCHEMA_CHANGED") + # Historical inventory sorts compact JSON primary-key dictionaries, then hashes the list. + from dashboard_testing_lab_reset_archive import json_bytes + ordered = sorted(actual, key=lambda value: json_bytes(value).decode()) + require(digest(ordered) == expected["primary_key_set_sha256"], + "LAB_RESET_PROTECTED_PRIMARY_KEYS_CHANGED") +# #endregion Tooling.LabReset.Database.Protected + + +# #region Tooling.LabReset.Database.Snapshot [C:4] [TYPE Function] +# @POST Public snapshot contains hashes/counts/schema only; selected row bodies remain in memory for private archive. +def snapshot(connection, scope): + tables, keys, fks, rows = reflect(connection, scope) + selected = selected_nodes(scope, rows, keys) + shared_ownership(scope, rows, keys, selected) + protected_checkpoint(scope, rows, keys, tables) + order = child_first(selected, foreign_edges(rows, keys, selected, fks)) + summary = {} + for name, table in tables.items(): + keep = [encode(row) for row in rows[name] if node(name, row, keys[name]) not in selected] + chosen = [encode(row) for row in rows[name] if node(name, row, keys[name]) in selected] + summary[name] = {"columns": [[column.name, str(column.type)] for column in table.columns], + "keys": keys[name], "foreign_keys": fks[name], "preserved_count": len(keep), + "preserved_sha256": digest(sorted(keep, key=digest)), "selected_count": len(chosen), + "selected_sha256": digest(sorted(chosen, key=digest))} + return {"tables": summary, "delete_order_sha256": digest(order)}, (tables, keys, rows, selected, order) +# #endregion Tooling.LabReset.Database.Snapshot + + +# #region Tooling.LabReset.Database.ArchiveRows [C:2] [TYPE Function] +def archive_rows(state): + tables, keys, rows, selected, _ = state + return {name: {"columns": [[column.name, str(column.type)] for column in table.columns], + "primary_key_columns": keys[name], + "rows": [encode(row) for row in sorted(rows[name], key=lambda row: node(name, row, keys[name])) + if node(name, row, keys[name]) in selected]} + for name, table in tables.items() if any(node(name, row, keys[name]) in selected for row in rows[name])} +# #endregion Tooling.LabReset.Database.ArchiveRows + + +# #region Tooling.LabReset.Database.LockSelected [C:3] [TYPE Function] +# @POST Selected row locks are acquired before root; delete later cannot introduce a new selected row lock. +def lock_selected(connection, state): + tables, keys, rows, selected, _ = state + for name in sorted(tables): + ordered = sorted(rows[name], key=lambda row: node(name, row, keys[name])) + for row in ordered: + if node(name, row, keys[name]) not in selected: + continue + predicate = and_(*(tables[name].c[key] == row[key] for key in keys[name])) + require(connection.execute(select(tables[name]).where(predicate).with_for_update()).first() is not None, + "LAB_RESET_PRIMARY_KEY_SET_CHANGED") +# #endregion Tooling.LabReset.Database.LockSelected + + +# #region Tooling.LabReset.Database.Delete [C:3] [TYPE Function] +# @POST Every exact selected row deleted once, child-first; unexpected affected counts roll back the whole transaction. +def delete_rows(connection, state): + tables, keys, rows, selected, order = state + indexed = {node(name, row, keys[name]): row for name in tables for row in rows[name] + if node(name, row, keys[name]) in selected} + for item in order: + name, _ = item + row = indexed[item] + predicate = and_(*(tables[name].c[key] == row[key] for key in keys[name])) + result = connection.execute(tables[name].delete().where(predicate)) + require(result.rowcount == 1, "LAB_RESET_DELETE_COUNT_CONFLICT") +# #endregion Tooling.LabReset.Database.Delete + + +# #region Tooling.LabReset.Database.AfterDelete [C:3] [TYPE Function] +def verify_deleted(connection, scope, before, state): + tables, keys, original, selected, _ = state + table_names(connection, scope) + no_foreign_sessions(connection) + for name, table in tables.items(): + actual = [dict(row) for row in connection.execute(select(table)).mappings()] + expected = [row for row in original[name] if node(name, row, keys[name]) not in selected] + require(digest(sorted(map(encode, actual), key=digest)) == digest(sorted(map(encode, expected), key=digest)), + "LAB_RESET_POST_DELETE_STATE_CONFLICT") + require(len(actual) == before["tables"][name]["preserved_count"], "LAB_RESET_DELETE_COUNT_CONFLICT") +# #endregion Tooling.LabReset.Database.AfterDelete +# #endregion Tooling.LabReset.Database diff --git a/scripts/dashboard_testing_lab_reset_files.py b/scripts/dashboard_testing_lab_reset_files.py new file mode 100644 index 000000000..3c9459656 --- /dev/null +++ b/scripts/dashboard_testing_lab_reset_files.py @@ -0,0 +1,270 @@ +# #region Tooling.LabReset.Files [C:5] [TYPE Module] [SEMANTICS maintenance,storage,holds,archive] +# @BRIEF Exact regular-file preservation, selected-byte archive and SSOT hold reset under the native root lock. +# @PRE All DB locks/reflection/owner rows already acquired; no function in this module queries DB. +# @INVARIANT Activation marker, root lock, directories and unmatched files survive; no alternate evidence I/O. +# @RELATION DEPENDS_ON -> [Storage.NativeResultHold] +from hashlib import sha256 +import os +from pathlib import Path +import stat + +from dashboard_testing_lab_reset_archive import ( + digest, read_bytes, require, safe_path, sync_directory, write_bytes, +) +from dashboard_testing_lab_reset_db import node + +ROOTS = ("/app/backend/data/dashboard_testing", "/app/backend/git_repos", "/app/storage") +MARKER = "/app/storage/.native-result-holds/activated" +INDEX = "/app/storage/.native-result-holds/index.json" +LOCK = "/app/storage/.native-result-mutation.catalog.lock" + + +# #region Tooling.LabReset.Files.Confined [C:2] [TYPE Function] +def confined(root, path): + path = Path(path) + require(path.is_absolute() and path != Path(root), "LAB_RESET_PATH_INVALID") + try: + relative = path.relative_to(root) + except ValueError: + require(False, "LAB_RESET_PATH_INVALID") + require(str(Path(root) / relative) == str(path), "LAB_RESET_PATH_INVALID") + return safe_path(root, str(relative)) +# #endregion Tooling.LabReset.Files.Confined + + +# #region Tooling.LabReset.Files.Member [C:3] [TYPE Function] +def member(root, expected): + path = confined(root, expected["path"]) + info = path.lstat() + require(stat.S_ISREG(info.st_mode) and info.st_size == expected["bytes"], + "LAB_RESET_FILE_CHANGED") + raw = read_bytes(path) + require(len(raw) == expected["bytes"] and sha256(raw).hexdigest() == expected["sha256"], + "LAB_RESET_FILE_CHANGED") + return raw +# #endregion Tooling.LabReset.Files.Member + + +# #region Tooling.LabReset.Files.Scan [C:3] [TYPE Function] +def scan(root): + require(Path(root).is_dir() and not Path(root).is_symlink(), "LAB_RESET_ROOT_INVALID") + regular, directories = [], [] + for home, folders, names in os.walk(root, followlinks=False): + for name in folders + names: + path = Path(home) / name + mode = path.lstat().st_mode + require(not stat.S_ISLNK(mode), "LAB_RESET_SYMLINK_REFUSED") + require(stat.S_ISREG(mode) or stat.S_ISDIR(mode), "LAB_RESET_SPECIAL_FILE_REFUSED") + (directories if stat.S_ISDIR(mode) else regular).append(str(path)) + return sorted(regular), sorted(directories) +# #endregion Tooling.LabReset.Files.Scan + + +# #region Tooling.LabReset.Files.Checkpoint [C:3] [TYPE Function] +def checkpoint(scope): + require(set(scope["files"]) == set(ROOTS), "LAB_RESET_ROOT_INVALID") + state = {} + for root, manifest in sorted(scope["files"].items()): + members = manifest["selected"] + manifest["preserve"] + regular, directories = scan(root) + require(regular == sorted(item["path"] for item in members), "LAB_RESET_FILE_SET_CHANGED") + for item in members: + member(root, item) + state[root] = {"selected": manifest["selected"], "preserve": manifest["preserve"], + "directories_sha256": digest(directories), "regular_count": len(regular), + "file_metadata_sha256": digest([[path, file_metadata(Path(path))] for path in regular]), + "preserved_metadata": {item["path"]: file_metadata(Path(item["path"])) for item in members + if item in manifest["preserve"] or item["path"] == MARKER}} + return state +# #endregion Tooling.LabReset.Files.Checkpoint + + +# #region Tooling.LabReset.Files.Metadata [C:1] [TYPE Function] +def file_metadata(path): + info = path.lstat() + return {"mode": stat.S_IMODE(info.st_mode), "uid": info.st_uid, + "gid": info.st_gid, "mtime_ns": info.st_mtime_ns} +# #endregion Tooling.LabReset.Files.Metadata + + +# #region Tooling.LabReset.Files.RootLock [C:3] [TYPE Function] +# @POST Refuse missing coordination files before the existing lock owner could create them. +def root_lock(scope): + from src.services.storage_holds import mutation_lock + keep = scope["files"]["/app/storage"]["preserve"] + matches = [item for item in keep if item["path"] == LOCK] + require(len(matches) == 1, "LAB_RESET_ROOT_LOCK_REQUIRED") + member("/app/storage", matches[0]) + require(Path(LOCK).stat().st_size == 0, "LAB_RESET_ROOT_LOCK_REQUIRED") + for path in (MARKER, INDEX): + require(Path(path).is_file() and not Path(path).is_symlink(), "LAB_RESET_HOLD_STATE_REQUIRED") + return mutation_lock("/app/storage") +# #endregion Tooling.LabReset.Files.RootLock + + +# #region Tooling.LabReset.Files.SelectedOwner [C:3] [TYPE Function] +def selected_owner(state, table, identity): + _, keys, rows, selected, _ = state + matches = [row for row in rows[table] if row["id"] == identity] + require(len(matches) == 1 and node(table, matches[0], keys[table]) in selected, + "LAB_RESET_HOLD_OWNER_CONFLICT") + return matches[0] +# #endregion Tooling.LabReset.Files.SelectedOwner + + +# #region Tooling.LabReset.Files.HoldOwner [C:4] [TYPE Function] +# @POST Hold identities name exact selected same-run DB rows and an exact issued root record; no new authority is manufactured. +def hold_owner(hold, state): + run = selected_owner(state, "agent_runs", hold.agent_run_id) + capture = selected_owner(state, "draft_artifacts", hold.capture_artifact_id) + candidate = selected_owner(state, "draft_artifacts", hold.candidate_id) + gate = selected_owner(state, "approval_gates", hold.gate_id) + require(all(row["run_id"] == hold.agent_run_id for row in (capture, candidate, gate)), + "LAB_RESET_HOLD_OWNER_CONFLICT") + context = run["context_snapshot"] + require(isinstance(context, dict) and isinstance(context.get("result_authority"), dict), + "LAB_RESET_HOLD_OWNER_CONFLICT") + records = context["result_authority"].get("records") + require(isinstance(records, list), "LAB_RESET_HOLD_OWNER_CONFLICT") + matches = [record for record in records if isinstance(record, dict) + and record.get("capture_artifact_id") == hold.capture_artifact_id] + require(len(matches) == 1 and digest(matches[0]) == hold.authority_record_sha256, + "LAB_RESET_HOLD_OWNER_CONFLICT") + record = matches[0] + require(capture["sha256"] == record["source_response_hash"] + and capture["content_ref"] == record["capture_content_ref"], "LAB_RESET_HOLD_OWNER_CONFLICT") + fields = hold.model_dump(mode="json", exclude={"hold_id"}) + require(digest(fields) == hold.hold_id, "LAB_RESET_HOLD_OWNER_CONFLICT") + return record, context, candidate +# #endregion Tooling.LabReset.Files.HoldOwner + + +# #region Tooling.LabReset.Files.HoldRefs [C:4] [TYPE Function] +def hold_refs(hold, record, context, candidate, state): + request = record["descriptor"]["native_request"] + source = context["reference_source"] + needed = {(request["content_ref"], request["sha256"], "request"), + (record["capture_content_ref"], record["source_response_hash"], "response"), + (source["source_url_ref"], source["source_url_sha256"], "source")} + meta = candidate["capture_meta"] + require(isinstance(meta, dict), "LAB_RESET_HOLD_OWNER_CONFLICT") + if meta.get("kind") == "visual": + review = selected_owner(state, "draft_artifacts", meta["review_disposition_id"]) + require(review["run_id"] == hold.agent_run_id and review["sha256"] == meta["review_disposition_sha256"], + "LAB_RESET_HOLD_OWNER_CONFLICT") + needed |= {(review["content_ref"], review["sha256"], "review"), + (meta["expected_image_content_ref"], meta["expected_image_sha256"], "image")} + actual = {(ref.content_ref, ref.sha256, ref.purpose) for ref in hold.refs} + require(needed.issubset(actual) and len(actual) == len(hold.refs), "LAB_RESET_HOLD_OWNER_CONFLICT") + # Extra visual wire refs must also be registered selected same-run artifacts. + for ref, hashed, purpose in actual - needed: + require(purpose in ("request", "response"), "LAB_RESET_HOLD_OWNER_CONFLICT") + _, keys, rows, selected, _ = state + matches = [row for row in rows["draft_artifacts"] if row["run_id"] == hold.agent_run_id + and row["content_ref"] == ref and row["sha256"] == hashed + and node("draft_artifacts", row, keys["draft_artifacts"]) in selected] + require(len(matches) == 1, "LAB_RESET_HOLD_OWNER_CONFLICT") +# #endregion Tooling.LabReset.Files.HoldRefs + + +# #region Tooling.LabReset.Files.HeldPath [C:1] [TYPE Function] +def held_path(ref): + from src.models.storage import FileCategory + from src.services.storage_holds import relative_ref + return Path("/app/storage") / FileCategory.DRAFT.value / relative_ref(ref) +# #endregion Tooling.LabReset.Files.HeldPath + + +# #region Tooling.LabReset.Files.Holds [C:3] [TYPE Function] +def validate_holds(scope, state): + from src.services.storage_holds import load_index, verify_ref + index = load_index("/app/storage") + selected = {item["path"]: item for item in scope["files"]["/app/storage"]["selected"]} + for hold in index.holds: + record, context, candidate = hold_owner(hold, state) + hold_refs(hold, record, context, candidate, state) + for ref in hold.refs: + path = str(held_path(ref)) + require(path in selected and selected[path]["sha256"] == ref.sha256, + "LAB_RESET_UNSELECTED_HOLD_BYTES") + member("/app/storage", selected[path]) + verify_ref("/app/storage", ref) + return digest(index.model_dump(mode="json")) +# #endregion Tooling.LabReset.Files.Holds + + +# #region Tooling.LabReset.Files.Archive [C:3] [TYPE Function] +def archive_files(scope, evidence): + result = [] + blobs = {} + for root, manifest in sorted(scope["files"].items()): + for item in manifest["selected"]: + raw = member(root, item) + hashed = item["sha256"] + name = f"bytes-{hashed}" + if hashed not in blobs: + blobs[hashed] = write_bytes(evidence, name, raw) + require(blobs[hashed] == hashed, "LAB_RESET_ARCHIVE_READBACK_FAILED") + result.append({**item, "member": name, "file_metadata": file_metadata(Path(item["path"]))}) + return result +# #endregion Tooling.LabReset.Files.Archive + + +# #region Tooling.LabReset.Files.VerifyArchive [C:3] [TYPE Function] +def verify_archive_files(scope, evidence, archived): + expected = sorted([item for manifest in scope["files"].values() for item in manifest["selected"]], + key=lambda item: item["path"]) + require([{key: value for key, value in item.items() if key not in ("member", "file_metadata")} + for item in sorted(archived, key=lambda item: item["path"])] == expected, + "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + for item in archived: + require(item["member"] == f"bytes-{item['sha256']}", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + require(item["file_metadata"] == file_metadata(Path(item["path"])), "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + raw = read_bytes(safe_path(evidence, item["member"]), private=True) + require(len(raw) == item["bytes"] and sha256(raw).hexdigest() == item["sha256"], + "LAB_RESET_ARCHIVE_READBACK_FAILED") +# #endregion Tooling.LabReset.Files.VerifyArchive + + +# #region Tooling.LabReset.Files.Reset [C:4] [TYPE Function] +# @PRE DB committed; root lock remains held; every selected byte and hold already archived/read back. +# @POST Index replaced only via SSOT; exact unlinks after ordinary guard; partial failure remains STOP, never autohealed. +def reset_files(scope, journal): + from src.services.storage_holds import HoldIndex, guard_delete, load_index, write_index + write_index("/app/storage", HoldIndex(schema_version=1, holds=())) + require(load_index("/app/storage").holds == (), "LAB_RESET_HOLD_RESET_FAILED") + journal.event("REFLECT", "Native hold index reset through current storage owner", holds=0) + for root, manifest in sorted(scope["files"].items()): + for item in manifest["selected"]: + if item["path"] in (MARKER, INDEX): + continue + member(root, item) + path = confined(root, item["path"]) + if root == "/app/storage": + guard_delete(root, path) + path.unlink() + sync_directory(path.parent) + journal.event("REFLECT", "Exact selected file removed", member_sha256=item["sha256"]) +# #endregion Tooling.LabReset.Files.Reset + + +# #region Tooling.LabReset.Files.AfterReset [C:3] [TYPE Function] +def verify_reset(scope, before): + from src.services.storage_holds import load_index + require(load_index("/app/storage").holds == (), "LAB_RESET_HOLD_RESET_FAILED") + for root, manifest in scope["files"].items(): + expected = [item["path"] for item in manifest["preserve"]] + if root == "/app/storage": + expected.extend([MARKER, INDEX]) + actual, directories = scan(root) + require(actual == sorted(expected) and digest(directories) == before[root]["directories_sha256"], + "LAB_RESET_POST_FILE_STATE_CONFLICT") + for item in manifest["preserve"]: + member(root, item) + for path, metadata in before[root]["preserved_metadata"].items(): + require(file_metadata(Path(path)) == metadata, "LAB_RESET_POST_FILE_STATE_CONFLICT") + if root == "/app/storage": + marker = next(item for item in manifest["selected"] if item["path"] == MARKER) + member(root, marker) +# #endregion Tooling.LabReset.Files.AfterReset +# #endregion Tooling.LabReset.Files diff --git a/specs/050-mcp-interface/plans/2026-10-09-stage1-adr-chart-response.md b/specs/050-mcp-interface/plans/2026-10-09-stage1-adr-chart-response.md index 255e8d449..4d56e1fd6 100644 --- a/specs/050-mcp-interface/plans/2026-10-09-stage1-adr-chart-response.md +++ b/specs/050-mcp-interface/plans/2026-10-09-stage1-adr-chart-response.md @@ -351,6 +351,8 @@ DATE проверяется по собственному column TEMPORAL_RANGE ### D17. Visual сравнивает независимое owned observation в одном пространстве идентичности +- **Приоритет P0.** Закрытие D17 требует actual independent capture, genuine publication и + явного human review точного expected PNG; component fixtures не закрывают эту приемку. - **@PRE** Visual verification получает явный typed actual locator: binding id, CAS version и completed operation id, ровно один PNG evidence ref и внутренний authenticated actor. Actor берётся из доверенного API-контекста; отсутствие actor не компенсируется владельцем diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md index e3c5bb4da..af396a253 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md @@ -792,4 +792,22 @@ I checked the exact release-packet SHA256 `5534dbd71d612e5bb7b03b5d95768f32efd7a Actual filtered96-event component wire `artifacts/chart-type-stabilization/native-temporal-current/temporal-semantic-current.jsonl` SHA256 `c1c1c89cffb42b39a146ca2e88a08b75d85f68c8fb063b893d64b58ff0ea01e9` includes native-context bounds refusal trace `ced7081bdfc642998a2fe9ce8cd797e9` with its claim/location and driver propagation trace `4fed2c9dddda48cea6392b60833f3177` with the same typed code. Summary180 SHA256 `87b98ac2a8a93962730259a2d4e9af0d960a316fcaf3305a352d277fd88f9079` retains exact node outcomes. No PG, HTTP, browser or installed custom DATE plugin acceptance is claimed. The public reference-capture route still wraps typed native causes as generic NATIVE_REFERENCE_CAPTURE_UNAVAILABLE; this cut does not claim that distinct diagnostic gap fixed. Financial SELECT dates, lab resources and migration/storage proofs are untouched. D17 maintenance remains pending root's explicit concrete phase authorization. +### 2026-10-11 — D17 phase1 private preparation and bounded prospective startup delta + +Root authorized phase1 configuration/manifest preparation only on reviewed runtime checkpoint `5f2ba6a20cde0bb46fe76b4a61dc119e52129f16`. Both application containers remain running0037; the reviewed readiness receipt reports eleven scheduler jobs and does not establish quiescence. No stop, rename, create, reset, upgrade, restart, login, capture or publication occurred. N120/ONE354 and USER approval NONE remain unchanged; the302-red full-suite result and open current product gaps are not superseded. + +The ignored preparer explicitly indexed only DATABASE_URL, AUTH_SECRET_KEY, ENCRYPTION_KEY, SERVICE_JWT and STORAGE_ROOT_PATH in the original container; required values and exact `/app/storage` were validated through a captured private pipe. Exclusive0600 restart configuration and separate own-principal publication overlay reside under a new0700 evidence/private directory. No Config.Env, original environment enumeration, original Gitea/PUBLISHED credential, shared token or secret tool output/argv was used. Current publication names come from PublicationConfig.Load. Inert restart manifests preserve the reviewed image/network/loopback ports/role volumes and bind the current backend/specs read-only; the own historical source copy is not extended. Phase1 receipt SHA256 `62fd6793eb56482fc576a8a7efa84e4b31f38ce263c03dca52b6a3a2ccb98aef` and manifest SHA256 `44b954f25f7a3e5c477f39708462191e6b47794a05cb3032ac797fa8a8ca934e` remain immutable. A later ignored-tool diagnostic update retains original failures privately and emits fixed allowlisted code/phase/trace/claim through host-only canonical Molecular primitives; direct offline privacy guards passed, without repeating phase1. + +Root separately authorized transport of exactly the two existing INITIAL_ADMIN login fields to private0600 intent files. Presence/mode/private transport are ready for both reviewed roles; no login/auth session, forged JWT, password default or password reset was performed. Credential file fingerprints and values are not operational public evidence. Actual worker identity is0/0 in both containers; host identity is1000/1000. New host evidence directories stay0700 owned1000, explicitly reviewed host inputs0600 are readable by the root worker, and new worker outputs stay root-owned0600 for readback through the same oneoff. No protected/config ownership changes are authorized. + +The READ ONLY permissions/roles/role_permissions and projected four-field environment comparison produced receipt SHA256 `d46beaf22d694394de61fda96427a5107ba99e57d893650dea76253487802549`. Original18103 has87 permissions/3 roles/27 grants: all67 current non-plugin declarations exist, Admin is administrative and Maintenance has exactly five canonical grants. Own18104 has86/2/22 and lacks exactly maintenance:settings/WRITE and the Maintenance role. Current source AST exposes ten literal plugin IDs, no dynamic ID body; all ten potential EXECUTE pairs already exist in both DBs, without claiming every plugin will load. Config mirror comparisons are expected no-ops for3→3 and2→2 projected environments; no full AppConfig/password/settings read or validation is claimed. ConfigManager, PluginLoader, ensure/sync owners and authenticated API routes were not instantiated or called by this observation. + +Root approved a prospective post-start delta only: own18104 may add that one permission, one exact non-admin Maintenance role and its five canonical grants, recording actual generated IDs; no existing users/roles/grants change. Both roles may change only next_run_time/job_state for the same eleven APScheduler IDs at restart. Source Start→LoadSchedules removes/re-adds those recurring jobs; this does not authorize maintenance tools to write jobs. Reset and migration still require full protected-content equality including RBAC and scheduler rows. All other protected rows/columns/files remain exact. Root-review receipt SHA256 `1b3b1ae94e68d0eb5821c1b0fb65bb533ed2a869caeebc853475a72c74bb49c8` records these bounds without authorizing any runtime phase. + +Independent READ ONLY DB identity receipts provide the exact database/address/port/OID compact-object digests, never inferred from DSNs. Inert oneoff templates use the reviewed image/network/role mounts, current backend/specs/scripts read-only, explicit worker script, exact base envfiles without publication token overlay, and fresh evidence RW; no ports, Docker socket, shared alias or implicit Alembic. Before tool commit their source binding is explicitly pending. After the reviewed tool commit, fresh manifests must bind the actual commit without re-extracting secrets, and each inventory/archive/reset phase still requires root authorization plus a fresh stopped-container quiescence receipt and preceding reviewed artifact hashes. Ignored D17 instructions now reflect bounded maintenance→PNG P0 ordering; whole-suite green remains the final MERGE gate. Actual independent capture/genuine publication/user inspection of the exact PNG remain required, and component fixtures cannot close D17. + +The first four-script/two-test release passed63 offline checks but was held before commit by independent source review. The producer's shared_ownership.linked_module_ids identify row PKs, not run-owner IDs; reviewed standalone verification rows can have agent_run_id=None. The hold path must use FileCategory.DRAFT.value (`drafts`), not singular `draft`. These were pre-execution review findings: original_trace_available=False; no earlier runtime trace is invented. The corrected release separately verifies selected row identity and exact declared module run sets/AgentRun intents, retains the reviewed standalone verification branch, derives the hold path from its SSOT, rejects duplicate allowlist PKs and preserves private failure evidence when the phase journal cannot be written. + +Curator's revised frozen release passed79 offline guards: the historical63 plus16 hardcoded owner/intent/standalone-verification, duplicate-PK, SSOT-path and journal-failure checks. Default Ruff/C901, AST compilation and balanced anchors passed. Main verified its six exact released hashes before restaging. Independent review packet `artifacts/stage0/reseed-20261010/independent-reset-review.jsonl` SHA256 `15727d3e98df2e19b47c966bb52e57c7ea38d2756a2d3ffc7ca7ce53b9384eac` records the corrected offline owner/path/failure and single-commit transaction checks; root approved the bounded commit. Those checks do not execute operational Docker/DB phases or establish stopped-container quiescence. The tool commit and subsequent clean-source manifest binding remain preparation, with runtime authorization separate. N120/ONE354 and USER approval NONE are unchanged. + ## @} Stage2.ChartTypeStabilizationJournal20261010 diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md index 10bb69736..d439dcc7d 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md @@ -35,7 +35,7 @@ Original275: а=0, б=120, source-restored=155. [Сверка803](2026-10-10-del - Official filter_state observer установил: Clear без Apply сохраняет committed context, Apply меняет его. Chart8 closed context/4×2 и source hashes измерялись; Force refresh прошёл через четыре native owners. Новая политика должна наблюдаться из actual page URL key и official state: иной opaque key допустим при том же effective context. Будущая capture независимо проверяет actual request SHA/context. Standalone DATE normalizer сохраняет авторские endpoints/inclusive; D11 native `[from,to)` discoveryFalse/typedTrue refusal реализован компонентами:180 SQL-free guards PASS/connect0, DATE column и TIME global разделены; browser/custom DATE plugin ещё не измерены, финансовые SELECT dates неизменны. - Последний полный suite24f53f97 завершился exit1:4211collected,3907callPASS,199callFAIL,103setupFAIL,2skipped; все4211teardowns PASS, collection/internal errors отсутствуют.302 private causes сохранены. Их нельзя объявлять целиком прежними или fixture-only. Проверенные bounded восстановления storage/DTO/import/quota/approval/recipe/DATE/logging достигают конкретных assertions; они не заменяют новый полный suite. Подробные результаты и безопасные causal traces находятся в журнале. - Текущие live gaps вне исторической source803 области: зарегистрированные superset_api/sql_evidence приходят в всегда отказывающий QueryExecutor; receipt open/finalize fail-open и repr logs открыты. bounded_transform безусловно unsupported. Publish gate после exact selector требует actual evidence, deployment caller не передаёт selector, scheduled verifier visibly unavailable.037FR012/017 и044FR014 активны; эти свойства не retired wholesale, их source/runtime причины требуют реализации и проверки. -- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены. +- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. Phase1 private config/manifests и READ ONLY startup preflight готовы; runtime maintenance ещё не разрешён. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены. Подробная прежняя хроника — [журнал](2026-10-10-chart-type-stabilization-journal.md). Измерения native controls/силы cache refresh — `artifacts/stage0/reseed-20261010/`; промежуточная