# #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] # @TEST_INVARIANT One private pack retains exact bytes once; repeated member metadata cannot expand the selected scope. 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": {str(tmp_path): {"selected": [item]}}} packed = archive.json_bytes(archive.encode({hashed: raw})) packed_sha = archive.write_bytes(tmp_path, files.PACK, packed) archived = [{**item, "member": hashed, "pack_sha256": packed_sha, "file_metadata": metadata}] 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) corrupted = archive.json_bytes(archive.encode({hashed: b"corrupt"})) (tmp_path / files.PACK).write_bytes(corrupted) archived[0]["pack_sha256"] = sha256(corrupted).hexdigest() 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.PackDedup [C:2] [TYPE Function] def test_selected_files_have_one_exclusive_private_deduplicated_pack(tmp_path): evidence = tmp_path / "evidence" evidence.mkdir(mode=0o700) live = tmp_path / "live" live.mkdir() selected = [] for name in ("second", "first"): path = live / name path.write_bytes(b"selected-content") selected.append({"path": str(path), "bytes": 16, "sha256": sha256(b"selected-content").hexdigest()}) scope = {"files": {str(live): {"selected": selected}}} archived = files.archive_files(scope, evidence) assert [path.name for path in evidence.iterdir()] == ["selected-files.json"] pack = evidence / "selected-files.json" hashed = sha256(b"selected-content").hexdigest() assert json.loads(pack.read_bytes()) == ["dict", [[hashed, ["bytes", "c2VsZWN0ZWQtY29udGVudA=="]]]] assert pack.stat().st_mode & 0o777 == 0o600 assert {item["member"] for item in archived} == {hashed} assert {item["pack_sha256"] for item in archived} == {sha256(pack.read_bytes()).hexdigest()} files.verify_archive_files(scope, evidence, archived) with pytest.raises(FileExistsError): files.archive_files(scope, evidence) assert len(list(evidence.iterdir())) == 1 # #endregion Test.LabReset.Storage.PackDedup # #region Test.LabReset.Storage.PackRefusals [C:2] [TYPE Function] @pytest.mark.parametrize("change,code", [("extra", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("missing", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("duplicate", "LAB_RESET_ARCHIVE_INVALID"), ("altered", "LAB_RESET_ARCHIVE_READBACK_FAILED"), ("forged_member", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("pack_digest", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("current_bytes", "LAB_RESET_FILE_CHANGED")]) def test_pack_tampering_refuses_before_any_selected_file_is_deleted(tmp_path, change, code): evidence = tmp_path / "evidence" evidence.mkdir(mode=0o700) path = tmp_path / "selected" path.write_bytes(b"original") hashed = sha256(b"original").hexdigest() scope = {"files": {str(tmp_path): {"selected": [{"path": str(path), "bytes": 8, "sha256": hashed}]}}} archived = files.archive_files(scope, evidence) encoded = ["dict", [[hashed, ["bytes", "b3JpZ2luYWw="]]]] if change == "extra": encoded[1].append(["b" * 64, ["bytes", "eA=="]]) elif change == "missing": encoded[1].clear() elif change == "duplicate": encoded[1].append(encoded[1][0]) elif change == "altered": encoded[1][0][1] = ["bytes", "Y2hhbmdlZA=="] elif change == "forged_member": archived[0]["member"] = "foreign" elif change == "current_bytes": previous = path.stat() path.write_bytes(b"modified") os.utime(path, ns=(previous.st_atime_ns, previous.st_mtime_ns)) raw = archive.json_bytes(encoded) (evidence / files.PACK).write_bytes(raw) archived[0]["pack_sha256"] = "f" * 64 if change == "pack_digest" else sha256(raw).hexdigest() with pytest.raises(archive.Stop, match="^" + code + "$"): files.verify_archive_files(scope, evidence, archived) assert path.exists() # #endregion Test.LabReset.Storage.PackRefusals # #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