chore(dashboard-testing): add bounded laboratory reset tooling
This commit is contained in:
308
scripts/dashboard_testing_lab_reset.py
Normal file
308
scripts/dashboard_testing_lab_reset.py
Normal file
@@ -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
|
||||
230
scripts/dashboard_testing_lab_reset_archive.py
Normal file
230
scripts/dashboard_testing_lab_reset_archive.py
Normal file
@@ -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
|
||||
309
scripts/dashboard_testing_lab_reset_db.py
Normal file
309
scripts/dashboard_testing_lab_reset_db.py
Normal file
@@ -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
|
||||
270
scripts/dashboard_testing_lab_reset_files.py
Normal file
270
scripts/dashboard_testing_lab_reset_files.py
Normal file
@@ -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
|
||||
Reference in New Issue
Block a user