From 403add38eae317a85cd616ae64f13cb7c0b57355 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:22:44 +0800 Subject: [PATCH 1/2] refactor(goals): modularize deletion_service with zero Any Split loopx/control_plane/goals/deletion_service.py into zero-Any submodules (deletion_basis.py, deletion_recovery.py, deletion_service.py < 700 LOC) while preserving single-owner content_digest/OPAQUE_ID pins, project-registry I/O census entries, and the delete_stopped_goal / recovery contract. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/control_plane/goals/deletion_basis.py | 530 ++++++++ .../control_plane/goals/deletion_recovery.py | 659 ++++++++++ loopx/control_plane/goals/deletion_service.py | 1069 +++-------------- .../test_deletion_service_contract.py | 344 ++++++ 4 files changed, 1713 insertions(+), 889 deletions(-) create mode 100644 loopx/control_plane/goals/deletion_basis.py create mode 100644 loopx/control_plane/goals/deletion_recovery.py create mode 100644 tests/control_plane/test_deletion_service_contract.py diff --git a/loopx/control_plane/goals/deletion_basis.py b/loopx/control_plane/goals/deletion_basis.py new file mode 100644 index 0000000000..950d497c6b --- /dev/null +++ b/loopx/control_plane/goals/deletion_basis.py @@ -0,0 +1,530 @@ +"""Pure deletion basis, state fingerprint, backup, and locking helpers.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +import hashlib +import os +from pathlib import Path +import re +import shutil +from typing import Literal, TypedDict, overload +import uuid + +from ...configuration_transaction import configuration_payload_revision +from ...file_lock import ( + EFFECT_MUTATION_LOCK_SUFFIX, + lock_holder_paths, + lock_incident_path, +) +from ...public_safe_text import OPAQUE_ID_PATTERN +from ...registry_writability import probe_registry_write_path +from ..coordination.shadow_management import shadow_maintenance_lock_target +from ..runtime.time import now_local_iso +from .activation_service import ( + GoalActivationAuthorityRouteMode, + _goal_activation_source_identity, + _goal_or_none, + _same_path, +) + +GOAL_DELETION_SCHEMA_VERSION = "loopx_goal_deletion_v1" +GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION = "loopx_goal_deletion_source_basis_v1" +GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION = ( + "loopx_goal_deletion_state_fingerprint_v1" +) +GOAL_DELETION_RECOVERY_SCHEMA_VERSION = "loopx_goal_deletion_recovery_v1" +_MAX_RECOVERY_RECEIPT_BYTES = 64 * 1024 +_OPAQUE_ID: re.Pattern[str] = OPAQUE_ID_PATTERN + +Payload = dict[str, object] +PayloadView = Mapping[str, object] +NowIsoFn = Callable[[], str] + + +class DeletionReadback(TypedDict): + """Readback verification flags produced after deletion or recovery.""" + + source_missing: bool + global_missing: bool + verified: bool + + +class DeletionRoute(TypedDict): + """Resolved source and global registry routing metadata for a Goal.""" + + source_registry: Path + declared_source_registry: Path + target_registry: Path + source_available: bool + source_status: str + source_goal: Payload | None + target_goal: Payload + same_registry: bool + route_mode: str + + +class DeletionResult(dict[str, object]): + """Structured dict returned by Goal deletion preview, execution, and recovery.""" + + @overload + def __getitem__( + self, + key: Literal[ + "schema_version", + "goal_id", + "source_registry", + "target_global_registry", + "authority_route_mode", + "observed_state_fingerprint", + "current_state_fingerprint", + "error_kind", + "error", + ], + /, + ) -> str: ... + + @overload + def __getitem__( + self, + key: Literal["expected_state_fingerprint", "recommended_action"], + /, + ) -> str | None: ... + + @overload + def __getitem__( + self, + key: Literal[ + "ok", + "dry_run", + "execute", + "source_registry_present", + "global_registry_present", + "written", + "partial_write", + "recovery_pending", + "recovered", + "replayed", + "stale", + ], + /, + ) -> bool: ... + + @overload + def __getitem__( + self, + key: Literal["source_basis"], + /, + ) -> dict[str, str]: ... + + @overload + def __getitem__( + self, + key: Literal["backup_paths"], + /, + ) -> list[str]: ... + + @overload + def __getitem__( + self, + key: Literal["readback"], + /, + ) -> DeletionReadback: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +def _as_payload(value: Mapping[str, object]) -> Payload: + return {str(key): item for key, item in value.items()} + + +def _goal_payload_or_none(payload: Payload | None, goal_id: str) -> Payload | None: + if payload is None: + return None + found = _goal_or_none(payload, goal_id) + if not isinstance(found, Mapping): + return None + return {str(key): item for key, item in found.items()} + + +def _require_opaque_id(value: str, *, field: str) -> str: + """Reject any value that is not a compact opaque id; safe for path segments.""" + token = str(value or "").strip() + if not _OPAQUE_ID.fullmatch(token): + raise ValueError(f"{field} must be a compact opaque id") + return token + + +def _registry_fingerprint(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _registry_identity(path: Path) -> str: + return configuration_payload_revision( + {"registry_path": str(path.expanduser().resolve())} + ).removeprefix("sha256:") + + +def _source_basis(route: PayloadView) -> dict[str, str]: + source_registry = Path(str(route["declared_source_registry"])) + try: + source_content = source_registry.read_bytes() + except OSError: + source_content = ( + f"unavailable:{route['source_status']}:{_registry_identity(source_registry)}" + ).encode() + return { + "schema_version": GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION, + "source_identity": _goal_activation_source_identity(source_registry), + "source_content_sha256": hashlib.sha256(source_content).hexdigest(), + "route_mode": str(route["route_mode"]), + } + + +def _state_fingerprint( + *, + goal_id: str, + source_basis: Mapping[str, str], + target_registry: Path, +) -> str: + return configuration_payload_revision( + { + "schema_version": GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, + "goal_id": goal_id, + "source_basis": dict(source_basis), + "target_identity": _registry_identity(target_registry), + "target_content_sha256": _registry_fingerprint(target_registry), + } + ).removeprefix("sha256:") + + +def _normalize_source_basis_with_pattern( + value: PayloadView | None, + *, + sha256_pattern: re.Pattern[str], +) -> dict[str, str] | None: + """Validate and normalize an expected Goal deletion source-basis mapping.""" + if value is None: + return None + if not isinstance(value, Mapping): + raise ValueError("expected source basis must be a mapping") + schema_version = str(value.get("schema_version") or "") + source_identity = str(value.get("source_identity") or "") + source_content_sha256 = str(value.get("source_content_sha256") or "") + route_mode = str(value.get("route_mode") or "") + if schema_version != GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION: + raise ValueError("expected source basis has an unsupported schema version") + if not sha256_pattern.fullmatch(source_identity): + raise ValueError("expected source identity must be a SHA-256 digest") + if not sha256_pattern.fullmatch(source_content_sha256): + raise ValueError("expected source content digest must be a SHA-256 digest") + if route_mode not in {mode.value for mode in GoalActivationAuthorityRouteMode}: + raise ValueError("expected source route mode is unsupported") + return { + "schema_version": schema_version, + "source_identity": source_identity, + "source_content_sha256": source_content_sha256, + "route_mode": route_mode, + } + + +def _mark_stale( + payload: DeletionResult, + *, + current_state_fingerprint: str, + current_source_basis: Mapping[str, str], +) -> None: + payload["ok"] = False + payload["stale"] = True + payload["error_kind"] = "goal_registry_changed" + payload["error"] = ( + "Goal source or registry route changed after preview; " + "regenerate the deletion preview" + ) + payload["current_state_fingerprint"] = current_state_fingerprint + payload["observed_state_fingerprint"] = current_state_fingerprint + payload["source_basis"] = dict(current_source_basis) + + +def _missing_state_fingerprint(*, goal_id: str, registry_path: Path) -> str: + target_content_sha256 = ( + _registry_fingerprint(registry_path) if registry_path.is_file() else None + ) + return configuration_payload_revision( + { + "schema_version": GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, + "goal_id": goal_id, + "deletion_state": "missing", + "target_identity": _registry_identity(registry_path), + "target_content_sha256": target_content_sha256, + } + ).removeprefix("sha256:") + + +def _missing_stale_payload( + *, + goal_id: str, + registry_path: Path, + execute: bool, + expected_state_fingerprint: str | None, +) -> DeletionResult: + current_fingerprint = _missing_state_fingerprint( + goal_id=goal_id, + registry_path=registry_path, + ) + return DeletionResult( + { + "ok": False, + "schema_version": GOAL_DELETION_SCHEMA_VERSION, + "dry_run": not execute, + "execute": execute, + "goal_id": goal_id, + "target_global_registry": str(registry_path), + "expected_state_fingerprint": expected_state_fingerprint, + "observed_state_fingerprint": current_fingerprint, + "current_state_fingerprint": current_fingerprint, + "written": False, + "partial_write": False, + "backup_paths": [], + "recovery_pending": False, + "recovered": False, + "replayed": False, + "readback": { + "source_missing": True, + "global_missing": True, + "verified": False, + }, + "stale": True, + "error_kind": "goal_registry_changed", + "error": "Goal disappeared after preview; regenerate the deletion preview", + } + ) + + +def _backup_path(path: Path, timestamp: str, nonce: str) -> Path: + compact_timestamp = timestamp.replace(":", "").replace("-", "") + return path.with_name( + f"{path.name}.goal-delete-{compact_timestamp}-{nonce}.bak" + ) + + +def _fsync_parent(path: Path) -> None: + if os.name != "posix": + return + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _create_backup(path: Path, *, timestamp: str) -> Path: + """Create an independent snapshot without ever overwriting an old backup.""" + source_path = path.expanduser().resolve(strict=True) + if not source_path.is_file(): + raise ValueError(f"registry path is not a regular file: {source_path}") + for _ in range(8): + backup = _backup_path(source_path, timestamp, uuid.uuid4().hex) + try: + descriptor = os.open( + backup, + os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, + ) + except FileExistsError: + continue + try: + with source_path.open("rb") as source, os.fdopen(descriptor, "wb") as target: + shutil.copyfileobj(source, target) + target.flush() + os.fsync(target.fileno()) + shutil.copystat(source_path, backup) + except Exception: + backup.unlink(missing_ok=True) + raise + _fsync_parent(backup) + return backup + raise FileExistsError( + f"could not allocate a unique Goal deletion backup for {source_path}" + ) + + +def _remove_goal( + payload: Payload, + goal_id: str, + *, + updated_at: object = None, + now_local_iso_fn: NowIsoFn = now_local_iso, +) -> tuple[Payload, bool]: + goals = payload.get("goals") + if not isinstance(goals, list): + raise ValueError("registry goals must be a list") + retained: list[object] = [ + goal + for goal in goals + if not (isinstance(goal, dict) and str(goal.get("id") or "") == goal_id) + ] + changed = len(retained) != len(goals) + updated = dict(payload) + updated["goals"] = retained + if changed: + updated["updated_at"] = ( + now_local_iso_fn() if updated_at is None else updated_at + ) + return updated, changed + + +def _recovery_receipt_path(registry_path: Path, goal_id: str) -> Path: + registry = registry_path.expanduser().resolve() + goal_digest = hashlib.sha256(goal_id.encode("utf-8")).hexdigest() + return registry.with_name( + f".{registry.name}.goal-delete-{goal_digest}.recovery.json" + ) + + +def _canonical_writer_guard_path(target_registry: Path, goal_id: str) -> Path: + runtime_root = target_registry.expanduser().resolve().parent + return shadow_maintenance_lock_target(runtime_root, goal_id) + + +def _check_writability(paths: list[Path]) -> Payload | None: + writability = [ + _as_payload(probe_registry_write_path(path, create_parent=False)) + for path in paths + ] + return next((item for item in writability if not item.get("ok")), None) + + +def _orphan_source_lock_error(path: Path) -> str | None: + parent = path.parent + if parent.exists() and (not parent.is_dir() or parent.is_symlink()): + return "Goal source registry parent is unavailable for safe locking" + kernel_lock = path.with_name(f"{path.name}.lock") + lock_artifacts = { + kernel_lock, + *lock_holder_paths(path), + lock_incident_path(path), + Path(f"{path}{EFFECT_MUTATION_LOCK_SUFFIX}"), + } + if any( + artifact.is_symlink() + or (artifact.exists() and not artifact.is_file()) + for artifact in lock_artifacts + ): + return "Goal source registry lock path is unsafe" + return None + + +def _initial_deletion_payload( + *, + goal_id: str, + route: DeletionRoute, + execute: bool, + normalized_fingerprint: str | None, + observed_source_basis: Mapping[str, str], + observed_fingerprint: str, +) -> DeletionResult: + return DeletionResult( + { + "ok": True, + "schema_version": GOAL_DELETION_SCHEMA_VERSION, + "dry_run": not execute, + "execute": execute, + "goal_id": goal_id, + "source_registry": str(route["source_registry"]), + "target_global_registry": str(route["target_registry"]), + "source_registry_present": route["source_goal"] is not None, + "global_registry_present": route["target_goal"] is not None, + "source_basis": dict(observed_source_basis), + "authority_route_mode": route["route_mode"], + "expected_state_fingerprint": normalized_fingerprint, + "observed_state_fingerprint": observed_fingerprint, + "written": False, + "partial_write": False, + "backup_paths": [], + "recovery_pending": False, + "recovered": False, + "replayed": False, + "readback": { + "source_missing": route["source_goal"] is None, + "global_missing": False, + "verified": False, + }, + } + ) + + +def _deletion_write_paths( + *, + current_payloads: Mapping[Path, Payload], + source_registry: Path, + target_registry: Path, + source_available: bool, +) -> list[Path]: + paths: list[Path] = [] + if ( + source_available + and not _same_path(source_registry, target_registry) + and source_registry in current_payloads + ): + paths.append(source_registry) + if target_registry in current_payloads: + paths.append(target_registry) + if len(paths) != len(current_payloads): + raise ValueError("Goal deletion registry set is invalid") + return paths + + +def _apply_lock_or_writability_failure( + payload: DeletionResult, + route: DeletionRoute, +) -> bool: + if not route["source_available"]: + lock_error = _orphan_source_lock_error(route["declared_source_registry"]) + if lock_error is not None: + payload["ok"] = False + payload["error_kind"] = "goal_source_lock_unavailable" + payload["error"] = lock_error + payload["recommended_action"] = ( + "Repair the Goal source registry route before deleting this Goal." + ) + return True + paths = [route["target_registry"]] + if not route["same_registry"]: + paths.append(route["source_registry"]) + writability = _check_writability(paths) + if writability is not None: + raw_action = writability.get("recommended_action") + payload["ok"] = False + payload["error_kind"] = "goal_registry_write_denied" + payload["error"] = str( + writability.get("error") or "Goal registry is not writable" + ) + payload["recommended_action"] = None if raw_action is None else str(raw_action) + return True + return False + + +def _route_matches_locked_paths( + route: PayloadView, + *, + source_registry: Path, + declared_source_registry: Path, + target_registry: Path, + source_available: bool, + same_registry: bool, +) -> bool: + return ( + _same_path(Path(str(route["source_registry"])), source_registry) + and _same_path( + Path(str(route["declared_source_registry"])), + declared_source_registry, + ) + and _same_path(Path(str(route["target_registry"])), target_registry) + and bool(route["source_available"]) is source_available + and bool(route["same_registry"]) is same_registry + ) diff --git a/loopx/control_plane/goals/deletion_recovery.py b/loopx/control_plane/goals/deletion_recovery.py new file mode 100644 index 0000000000..14513eaee4 --- /dev/null +++ b/loopx/control_plane/goals/deletion_recovery.py @@ -0,0 +1,659 @@ +"""Write-ahead recovery receipts and idempotent completion for Goal deletion.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from contextlib import AbstractContextManager, ExitStack +from dataclasses import dataclass +import hashlib +import os +from pathlib import Path +import re +from typing import Protocol, TypedDict + +from ..projects.registry_codec import ( + ProjectRegistryTransaction, + decode_registry_snapshot, +) +from ...file_lock import exclusive_cross_runtime_file_lock +from ...history import load_registry +from ...registry import atomic_write_json, read_json +from ..effect_runtime import CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS +from .activation_service import ( + _goal_activation_source_identity, + _same_path, + _source_status, +) +from .deletion_basis import ( + GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + GOAL_DELETION_SCHEMA_VERSION, + _MAX_RECOVERY_RECEIPT_BYTES, + DeletionReadback, + DeletionResult, + NowIsoFn, + Payload, + PayloadView, + _as_payload, + _canonical_writer_guard_path, + _fsync_parent, + _goal_payload_or_none, + _normalize_source_basis_with_pattern, + _recovery_receipt_path, + _remove_goal, + _source_basis, +) + + +class RecoverySnapshot(TypedDict): + """Serialized snapshot pointer stored inside a Goal deletion recovery record.""" + + registry_path: str + backup_path: str + preimage_sha256: str + + +class RecoveryRecord(TypedDict): + """Typed write-ahead recovery receipt for idempotent Goal deletion replay.""" + + schema_version: str + goal_id: str + state_fingerprint: str + source_basis: dict[str, str] + source_registry: str + declared_source_registry: str + target_registry: str + source_available: bool + same_registry: bool + snapshots: list[RecoverySnapshot] + + +class AtomicWriteJsonFn(Protocol): + """Callable protocol matching ``loopx.registry.atomic_write_json``.""" + + def __call__( + self, + path: Path, + payload: Payload, + *, + preserve_mode: bool = False, + ) -> None: ... + + +class LockedRegistryWriteFn(Protocol): + """Callable protocol matching locked write/restore operations.""" + + def __call__( + self, + *, + path: Path, + updated: Payload, + source_registry: Path, + source_transaction: ProjectRegistryTransaction | None, + ) -> None: ... + + +class LockedRegistryRestoreFn(Protocol): + """Callable protocol matching locked rollback restoration.""" + + def __call__( + self, + *, + path: Path, + current: Payload, + source_registry: Path, + source_transaction: ProjectRegistryTransaction | None, + ) -> None: ... + + +class RegistryTransactionFn(Protocol): + """Callable protocol matching ``project_registry_transaction``.""" + + def __call__( + self, + path: Path, + *, + operation: str, + ) -> AbstractContextManager[ProjectRegistryTransaction]: ... + + +LoadRegistryFn = Callable[[Path], Payload] + + +@dataclass(frozen=True, slots=True) +class RecoveryRuntimeHooks: + """Runtime dependencies injected from ``deletion_service`` for monkeypatch parity.""" + + load_registry_fn: LoadRegistryFn + atomic_write_json_fn: AtomicWriteJsonFn + project_registry_transaction_fn: RegistryTransactionFn + write_locked_registry_fn: LockedRegistryWriteFn + restore_locked_registry_fn: LockedRegistryRestoreFn + now_local_iso_fn: NowIsoFn + sha256_pattern: re.Pattern[str] + + +def _default_load_registry(path: Path) -> Payload: + return _as_payload(load_registry(path)) + + +def _build_recovery_record( + *, + goal_id: str, + state_fingerprint: str, + source_basis: Mapping[str, str], + source_registry: Path, + declared_source_registry: Path, + target_registry: Path, + source_available: bool, + same_registry: bool, + paths: list[Path], + backup_paths: Mapping[Path, Path], +) -> RecoveryRecord: + snapshots: list[RecoverySnapshot] = [] + for path in paths: + backup = backup_paths[path] + snapshots.append( + { + "registry_path": str(path.expanduser().resolve()), + "backup_path": str(backup.expanduser().resolve()), + "preimage_sha256": hashlib.sha256(backup.read_bytes()).hexdigest(), + } + ) + return { + "schema_version": GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + "goal_id": goal_id, + "state_fingerprint": state_fingerprint, + "source_basis": dict(source_basis), + "source_registry": str(source_registry.expanduser().resolve()), + "declared_source_registry": str( + declared_source_registry.expanduser().resolve() + ), + "target_registry": str(target_registry.expanduser().resolve()), + "source_available": source_available, + "same_registry": same_registry, + "snapshots": snapshots, + } + + +def _validated_recovery_path(value: object, *, field: str) -> Path: + text = str(value or "").strip() + path = Path(text) + if not text or not path.is_absolute(): + raise ValueError(f"Goal deletion recovery {field} must be absolute") + return path.resolve() + + +def _validated_recovery_snapshots( + snapshots_value: object, + *, + expected_paths: list[Path], + sha256_pattern: re.Pattern[str], +) -> list[RecoverySnapshot]: + if not isinstance(snapshots_value, list): + raise ValueError("Goal deletion recovery snapshots are missing") + snapshots: list[RecoverySnapshot] = [] + seen_paths: list[Path] = [] + for snapshot_value in snapshots_value: + if not isinstance(snapshot_value, Mapping): + raise ValueError("Goal deletion recovery snapshot is invalid") + registry_path = _validated_recovery_path( + snapshot_value.get("registry_path"), + field="snapshot registry path", + ) + backup_path = _validated_recovery_path( + snapshot_value.get("backup_path"), + field="snapshot backup path", + ) + preimage_sha256 = str(snapshot_value.get("preimage_sha256") or "") + if not sha256_pattern.fullmatch(preimage_sha256): + raise ValueError("Goal deletion recovery preimage digest is invalid") + if backup_path.parent != registry_path.parent or not ( + backup_path.name.startswith(f"{registry_path.name}.goal-delete-") + and backup_path.name.endswith(".bak") + ): + raise ValueError("Goal deletion recovery backup path is invalid") + if backup_path.is_symlink() or not backup_path.is_file(): + raise ValueError("Goal deletion recovery backup is unavailable") + if any(_same_path(registry_path, seen) for seen in seen_paths): + raise ValueError("Goal deletion recovery repeats a registry path") + seen_paths.append(registry_path) + snapshots.append( + { + "registry_path": str(registry_path), + "backup_path": str(backup_path), + "preimage_sha256": preimage_sha256, + } + ) + if len(seen_paths) != len(expected_paths) or any( + not _same_path(actual, expected) + for actual, expected in zip(seen_paths, expected_paths, strict=True) + ): + raise ValueError("Goal deletion recovery registry set is invalid") + return snapshots + + +def _validated_recovery_record( + value: PayloadView, + *, + receipt_path: Path, + goal_id: str, + sha256_pattern: re.Pattern[str], +) -> RecoveryRecord: + if value.get("schema_version") != GOAL_DELETION_RECOVERY_SCHEMA_VERSION: + raise ValueError("Goal deletion recovery schema is unsupported") + if value.get("goal_id") != goal_id: + raise ValueError("Goal deletion recovery goal identity does not match") + state_fingerprint = str(value.get("state_fingerprint") or "") + if not sha256_pattern.fullmatch(state_fingerprint): + raise ValueError("Goal deletion recovery state fingerprint is invalid") + source_basis_value = value.get("source_basis") + if not isinstance(source_basis_value, Mapping): + raise ValueError("Goal deletion recovery source basis is missing") + source_basis = _normalize_source_basis_with_pattern( + source_basis_value, + sha256_pattern=sha256_pattern, + ) + if source_basis is None: + raise ValueError("Goal deletion recovery source basis is missing") + source_registry = _validated_recovery_path( + value.get("source_registry"), + field="source registry", + ) + declared_source_registry = _validated_recovery_path( + value.get("declared_source_registry"), + field="declared source registry", + ) + target_registry = _validated_recovery_path( + value.get("target_registry"), + field="target registry", + ) + source_available = value.get("source_available") + same_registry = value.get("same_registry") + if not isinstance(source_available, bool) or not isinstance(same_registry, bool): + raise ValueError("Goal deletion recovery route flags are invalid") + if same_registry != _same_path(source_registry, target_registry): + raise ValueError("Goal deletion recovery same-registry flag is invalid") + if source_available != _same_path(source_registry, declared_source_registry): + raise ValueError("Goal deletion recovery source route is invalid") + if not source_available and not same_registry: + raise ValueError("Goal deletion recovery fallback route is invalid") + expected_source_identity = _goal_activation_source_identity( + declared_source_registry + ) + if source_basis["source_identity"] != expected_source_identity: + raise ValueError("Goal deletion recovery source identity does not match") + expected_paths = [target_registry] + if source_available and not same_registry: + expected_paths.insert(0, source_registry) + snapshots = _validated_recovery_snapshots( + value.get("snapshots"), + expected_paths=expected_paths, + sha256_pattern=sha256_pattern, + ) + expected_receipts = [ + _recovery_receipt_path(path, goal_id) for path in expected_paths + ] + if not any(_same_path(receipt_path, expected) for expected in expected_receipts): + raise ValueError("Goal deletion recovery receipt path is invalid") + return { + "schema_version": GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + "goal_id": goal_id, + "state_fingerprint": state_fingerprint, + "source_basis": source_basis, + "source_registry": str(source_registry), + "declared_source_registry": str(declared_source_registry), + "target_registry": str(target_registry), + "source_available": source_available, + "same_registry": same_registry, + "snapshots": snapshots, + } + + +def _load_recovery_record( + path: Path, + goal_id: str, + *, + sha256_pattern: re.Pattern[str], +) -> RecoveryRecord: + if path.is_symlink() or not path.is_file(): + raise ValueError("Goal deletion recovery receipt is unavailable") + if path.stat().st_size > _MAX_RECOVERY_RECEIPT_BYTES: + raise ValueError("Goal deletion recovery receipt exceeds its size limit") + return _validated_recovery_record( + _as_payload(read_json(path)), + receipt_path=path, + goal_id=goal_id, + sha256_pattern=sha256_pattern, + ) + + +def _matching_recovery_record( + *, + requested_registry: Path, + goal_id: str, + expected_state_fingerprint: str | None, + expected_source_basis: Mapping[str, str] | None, + sha256_pattern: re.Pattern[str], +) -> RecoveryRecord | None: + if expected_state_fingerprint is None or expected_source_basis is None: + return None + receipt_path = _recovery_receipt_path(requested_registry, goal_id) + if not os.path.lexists(receipt_path): + return None + record = _load_recovery_record( + receipt_path, + goal_id, + sha256_pattern=sha256_pattern, + ) + if record["state_fingerprint"] != expected_state_fingerprint or record[ + "source_basis" + ] != dict(expected_source_basis): + return None + return record + + +def _write_recovery_receipts( + record: RecoveryRecord, + *, + sha256_pattern: re.Pattern[str], + atomic_write_json_fn: AtomicWriteJsonFn = atomic_write_json, +) -> None: + goal_id = record["goal_id"] + for snapshot in record["snapshots"]: + receipt_path = _recovery_receipt_path( + Path(snapshot["registry_path"]), + goal_id, + ) + if receipt_path.is_symlink() or ( + receipt_path.exists() and not receipt_path.is_file() + ): + raise ValueError("Goal deletion recovery receipt path is unsafe") + atomic_write_json_fn(receipt_path, dict(record), preserve_mode=True) + _fsync_parent(receipt_path) + if ( + _load_recovery_record( + receipt_path, + goal_id, + sha256_pattern=sha256_pattern, + ) + != record + ): + raise ValueError("Goal deletion recovery receipt readback did not verify") + + +def _recovery_images( + record: RecoveryRecord, +) -> dict[Path, tuple[Payload, str]]: + images: dict[Path, tuple[Payload, str]] = {} + for snapshot in record["snapshots"]: + registry_path = Path(snapshot["registry_path"]) + backup_path = Path(snapshot["backup_path"]) + raw_preimage = backup_path.read_bytes() + preimage_sha256 = hashlib.sha256(raw_preimage).hexdigest() + if preimage_sha256 != snapshot["preimage_sha256"]: + raise ValueError("Goal deletion recovery backup digest does not match") + preimage = _as_payload(decode_registry_snapshot(registry_path, raw_preimage)) + if _goal_payload_or_none(preimage, record["goal_id"]) is None: + raise ValueError("Goal deletion recovery backup is missing its Goal") + images[registry_path] = (preimage, preimage_sha256) + return images + + +def _recovery_states( + record: RecoveryRecord, + *, + load_registry_fn: LoadRegistryFn = _default_load_registry, +) -> tuple[dict[Path, str], dict[Path, tuple[Payload, str]]]: + images = _recovery_images(record) + states: dict[Path, str] = {} + for path, (preimage, preimage_sha256) in images.items(): + try: + current_bytes = path.read_bytes() + current = load_registry_fn(path) + except (OSError, UnicodeError, ValueError) as exc: + raise ValueError( + "Goal deletion recovery conflicts with current registry state" + ) from exc + if hashlib.sha256(current_bytes).hexdigest() == preimage_sha256: + states[path] = "preimage" + continue + postimage, changed = _remove_goal( + preimage, + record["goal_id"], + updated_at=current.get("updated_at"), + ) + if not changed or current != postimage: + raise ValueError( + "Goal deletion recovery conflicts with current registry state" + ) + states[path] = "postimage" + return states, images + + +def _recovery_readback( + record: RecoveryRecord, + states: Mapping[Path, str], +) -> DeletionReadback: + source_registry = Path(record["source_registry"]) + declared_source_registry = Path(record["declared_source_registry"]) + target_registry = Path(record["target_registry"]) + source_available = record["source_available"] + source_missing = ( + states[source_registry] == "postimage" + if source_available + else _source_basis( + { + "declared_source_registry": declared_source_registry, + "source_status": _source_status( + declared_source_registry, + goal_id=record["goal_id"], + ).value, + "route_mode": record["source_basis"]["route_mode"], + } + ) + == record["source_basis"] + ) + global_missing = states[target_registry] == "postimage" + return { + "source_missing": source_missing, + "global_missing": global_missing, + "verified": source_missing and global_missing, + } + + +def _recovery_result( + record: RecoveryRecord, + states: Mapping[Path, str], + *, + execute: bool, + written: bool, +) -> DeletionResult: + readback = _recovery_readback(record, states) + if not record["source_available"] and not readback["source_missing"]: + raise ValueError("Goal deletion recovery conflicts with current registry state") + source_registry = Path(record["source_registry"]) + target_registry = Path(record["target_registry"]) + return DeletionResult( + { + "ok": True, + "schema_version": GOAL_DELETION_SCHEMA_VERSION, + "dry_run": not execute, + "execute": execute, + "goal_id": record["goal_id"], + "source_registry": str(source_registry), + "target_global_registry": str(target_registry), + "source_registry_present": bool( + record["source_available"] and states[source_registry] == "preimage" + ), + "global_registry_present": states[target_registry] == "preimage", + "source_basis": dict(record["source_basis"]), + "authority_route_mode": record["source_basis"]["route_mode"], + "expected_state_fingerprint": record["state_fingerprint"], + "observed_state_fingerprint": record["state_fingerprint"], + "written": written, + "partial_write": any(state == "postimage" for state in states.values()) + and not readback["verified"], + "backup_paths": [ + snapshot["backup_path"] for snapshot in record["snapshots"] + ], + "readback": readback, + "recovery_pending": not execute, + "recovered": execute and readback["verified"], + "replayed": execute and readback["verified"] and not written, + } + ) + + +def _as_recovery_record( + record: RecoveryRecord | PayloadView, + *, + sha256_pattern: re.Pattern[str], +) -> RecoveryRecord: + raw_goal_id = record.get("goal_id") + goal_id = raw_goal_id if isinstance(raw_goal_id, str) else "" + if not goal_id.strip(): + raise ValueError("Goal deletion recovery goal identity does not match") + target_registry = _validated_recovery_path( + record.get("target_registry"), + field="target registry", + ) + return _validated_recovery_record( + record, + receipt_path=_recovery_receipt_path(target_registry, goal_id), + goal_id=goal_id, + sha256_pattern=sha256_pattern, + ) + + +def _recovery_receipts_match( + record: RecoveryRecord, + *, + sha256_pattern: re.Pattern[str], +) -> bool: + goal_id = record["goal_id"] + for snapshot in record["snapshots"]: + receipt_path = _recovery_receipt_path( + Path(snapshot["registry_path"]), + goal_id, + ) + if not os.path.lexists(receipt_path): + return False + current = _load_recovery_record( + receipt_path, + goal_id, + sha256_pattern=sha256_pattern, + ) + if current != record: + return False + return True + + +def _execute_recovery( + raw_record: RecoveryRecord | PayloadView, + *, + hooks: RecoveryRuntimeHooks, +) -> DeletionResult: + """Converge every recorded preimage to deletion without overwriting drift.""" + record = _as_recovery_record(raw_record, sha256_pattern=hooks.sha256_pattern) + source_registry = Path(record["source_registry"]) + declared_source_registry = Path(record["declared_source_registry"]) + target_registry = Path(record["target_registry"]) + source_available = record["source_available"] + same_registry = record["same_registry"] + locked_source_registry = ( + source_registry if source_available else declared_source_registry + ) + with ExitStack() as stack: + stack.enter_context( + exclusive_cross_runtime_file_lock( + _canonical_writer_guard_path(target_registry, record["goal_id"]), + operation="recover_delete_stopped_goal_canonical", + timeout_seconds=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, + ) + ) + source_transaction: ProjectRegistryTransaction | None = None + if not _same_path(locked_source_registry, target_registry): + if source_available and not same_registry: + source_transaction = stack.enter_context( + hooks.project_registry_transaction_fn( + locked_source_registry, + operation="recover_delete_stopped_goal", + ) + ) + else: + stack.enter_context( + exclusive_cross_runtime_file_lock( + locked_source_registry, + operation="recover_delete_stopped_goal", + ) + ) + stack.enter_context( + exclusive_cross_runtime_file_lock( + target_registry, + operation="recover_delete_stopped_goal", + ) + ) + states, images = _recovery_states( + record, + load_registry_fn=hooks.load_registry_fn, + ) + if not _recovery_receipts_match( + record, + sha256_pattern=hooks.sha256_pattern, + ): + if any(state == "postimage" for state in states.values()): + raise ValueError( + "Goal deletion recovery conflicts with current registry state" + ) + _write_recovery_receipts( + record, + sha256_pattern=hooks.sha256_pattern, + atomic_write_json_fn=hooks.atomic_write_json_fn, + ) + + written_paths: list[Path] = [] + try: + for snapshot in record["snapshots"]: + path = Path(snapshot["registry_path"]) + if states[path] == "postimage": + continue + preimage, _digest = images[path] + postimage, changed = _remove_goal( + preimage, + record["goal_id"], + now_local_iso_fn=hooks.now_local_iso_fn, + ) + if not changed: + raise ValueError( + "Goal deletion recovery backup is missing its Goal" + ) + hooks.write_locked_registry_fn( + path=path, + updated=postimage, + source_registry=source_registry, + source_transaction=source_transaction, + ) + written_paths.append(path) + final_states, _final_images = _recovery_states( + record, + load_registry_fn=hooks.load_registry_fn, + ) + result = _recovery_result( + record, + final_states, + execute=True, + written=bool(written_paths), + ) + if not result["readback"]["verified"]: + raise ValueError("Goal deletion recovery readback did not verify") + return result + except Exception: + for path in reversed(written_paths): + preimage, _digest = images[path] + hooks.restore_locked_registry_fn( + path=path, + current=preimage, + source_registry=source_registry, + source_transaction=source_transaction, + ) + raise diff --git a/loopx/control_plane/goals/deletion_service.py b/loopx/control_plane/goals/deletion_service.py index bcb8410853..9a49ce87af 100644 --- a/loopx/control_plane/goals/deletion_service.py +++ b/loopx/control_plane/goals/deletion_service.py @@ -4,720 +4,105 @@ from collections.abc import Mapping from contextlib import ExitStack -import hashlib -import os from pathlib import Path -import shutil -from typing import Any -import uuid from ..projects.registry_codec import ( ProjectRegistryTransaction, - decode_registry_snapshot, - project_registry_transaction, + decode_registry_snapshot as decode_registry_snapshot, + project_registry_transaction as project_registry_transaction, ) -from ...configuration_transaction import configuration_payload_revision -from ...file_lock import ( - EFFECT_MUTATION_LOCK_SUFFIX, - exclusive_cross_runtime_file_lock, - lock_holder_paths, - lock_incident_path, -) -from ...history import load_registry -from ...public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID -from ...registry import atomic_write_json, read_json -from ...registry_writability import probe_registry_write_path -from ..coordination.shadow_management import shadow_maintenance_lock_target +from ...file_lock import exclusive_cross_runtime_file_lock +from ...history import load_registry as load_registry +from ...public_safe_text import OPAQUE_ID_PATTERN +from ...registry import atomic_write_json as atomic_write_json, read_json from ..effect_runtime import CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS -from ..runtime.time import now_local_iso +from ..runtime.time import now_local_iso as now_local_iso from .activation import GoalActivationState, goal_activation_state from .activation_service import ( GoalActivationAuthorityRouteMode, - _goal_activation_source_identity, - _goal_or_none, _same_path, _source_and_target, - _source_status, ) from ..content_digest import BARE_SHA256_PATTERN - - -GOAL_DELETION_SCHEMA_VERSION = "loopx_goal_deletion_v1" -GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION = "loopx_goal_deletion_source_basis_v1" -GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION = ( - "loopx_goal_deletion_state_fingerprint_v1" +from .deletion_basis import ( + GOAL_DELETION_RECOVERY_SCHEMA_VERSION as GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + GOAL_DELETION_SCHEMA_VERSION as GOAL_DELETION_SCHEMA_VERSION, + GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION as GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION, + GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION as GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, + _MAX_RECOVERY_RECEIPT_BYTES as _MAX_RECOVERY_RECEIPT_BYTES, + DeletionReadback as DeletionReadback, + DeletionResult as DeletionResult, + DeletionRoute as DeletionRoute, + Payload as Payload, + PayloadView as PayloadView, + _apply_lock_or_writability_failure, + _as_payload, + _backup_path as _backup_path, + _canonical_writer_guard_path, + _create_backup, + _deletion_write_paths as _deletion_write_paths, + _fsync_parent as _fsync_parent, + _goal_payload_or_none, + _initial_deletion_payload, + _mark_stale, + _missing_stale_payload, + _missing_state_fingerprint as _missing_state_fingerprint, + _normalize_source_basis_with_pattern, + _recovery_receipt_path as _recovery_receipt_path, + _registry_fingerprint as _registry_fingerprint, + _registry_identity as _registry_identity, + _remove_goal, + _require_opaque_id, + _route_matches_locked_paths, + _source_basis, + _state_fingerprint, +) +from .deletion_recovery import ( + RecoveryRecord as RecoveryRecord, + RecoveryRuntimeHooks as RecoveryRuntimeHooks, + RecoverySnapshot as RecoverySnapshot, + _build_recovery_record, + _execute_recovery as _run_execute_recovery, + _load_recovery_record as _load_recovery_record, + _matching_recovery_record, + _recovery_images as _recovery_images, + _recovery_readback as _recovery_readback, + _recovery_receipts_match as _recovery_receipts_match, + _recovery_result, + _recovery_states, + _validated_recovery_path as _validated_recovery_path, + _validated_recovery_record as _validated_recovery_record, + _write_recovery_receipts, ) -GOAL_DELETION_RECOVERY_SCHEMA_VERSION = "loopx_goal_deletion_recovery_v1" -_MAX_RECOVERY_RECEIPT_BYTES = 64 * 1024 - - -def _require_opaque_id(value: str, *, field: str) -> str: - """Reject any value that is not a compact opaque id; safe for path segments.""" - - token = str(value or "").strip() - if not _OPAQUE_ID.fullmatch(token): - raise ValueError(f"{field} must be a compact opaque id") - return token - - -def _registry_fingerprint(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def _registry_identity(path: Path) -> str: - return configuration_payload_revision( - {"registry_path": str(path.expanduser().resolve())} - ).removeprefix("sha256:") - - -def _source_basis(route: dict[str, Any]) -> dict[str, str]: - source_registry = Path(route["declared_source_registry"]) - try: - source_content = source_registry.read_bytes() - except OSError: - source_content = ( - f"unavailable:{route['source_status']}:{_registry_identity(source_registry)}" - ).encode() - return { - "schema_version": GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION, - "source_identity": _goal_activation_source_identity(source_registry), - "source_content_sha256": hashlib.sha256(source_content).hexdigest(), - "route_mode": str(route["route_mode"]), - } - - -def _state_fingerprint( - *, - goal_id: str, - source_basis: Mapping[str, str], - target_registry: Path, -) -> str: - return configuration_payload_revision( - { - "schema_version": GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, - "goal_id": goal_id, - "source_basis": dict(source_basis), - "target_identity": _registry_identity(target_registry), - "target_content_sha256": _registry_fingerprint(target_registry), - } - ).removeprefix("sha256:") - - -def _normalize_source_basis(value: Mapping[str, Any] | None) -> dict[str, str] | None: - if value is None: - return None - schema_version = str(value.get("schema_version") or "") - source_identity = str(value.get("source_identity") or "") - source_content_sha256 = str(value.get("source_content_sha256") or "") - route_mode = str(value.get("route_mode") or "") - if schema_version != GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION: - raise ValueError("expected source basis has an unsupported schema version") - if not BARE_SHA256_PATTERN.fullmatch(source_identity): - raise ValueError("expected source identity must be a SHA-256 digest") - if not BARE_SHA256_PATTERN.fullmatch(source_content_sha256): - raise ValueError("expected source content digest must be a SHA-256 digest") - if route_mode not in {mode.value for mode in GoalActivationAuthorityRouteMode}: - raise ValueError("expected source route mode is unsupported") - return { - "schema_version": schema_version, - "source_identity": source_identity, - "source_content_sha256": source_content_sha256, - "route_mode": route_mode, - } - - -def _mark_stale( - payload: dict[str, Any], - *, - current_state_fingerprint: str, - current_source_basis: Mapping[str, str], -) -> None: - payload.update( - { - "ok": False, - "stale": True, - "error_kind": "goal_registry_changed", - "error": ( - "Goal source or registry route changed after preview; " - "regenerate the deletion preview" - ), - "current_state_fingerprint": current_state_fingerprint, - "observed_state_fingerprint": current_state_fingerprint, - "source_basis": dict(current_source_basis), - } - ) - - -def _missing_state_fingerprint(*, goal_id: str, registry_path: Path) -> str: - target_content_sha256 = ( - _registry_fingerprint(registry_path) if registry_path.is_file() else None - ) - return configuration_payload_revision( - { - "schema_version": GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, - "goal_id": goal_id, - "deletion_state": "missing", - "target_identity": _registry_identity(registry_path), - "target_content_sha256": target_content_sha256, - } - ).removeprefix("sha256:") - - -def _missing_stale_payload( - *, - goal_id: str, - registry_path: Path, - execute: bool, - expected_state_fingerprint: str | None, -) -> dict[str, Any]: - current_fingerprint = _missing_state_fingerprint( - goal_id=goal_id, - registry_path=registry_path, - ) - return { - "ok": False, - "schema_version": GOAL_DELETION_SCHEMA_VERSION, - "dry_run": not execute, - "execute": execute, - "goal_id": goal_id, - "target_global_registry": str(registry_path), - "expected_state_fingerprint": expected_state_fingerprint, - "observed_state_fingerprint": current_fingerprint, - "current_state_fingerprint": current_fingerprint, - "written": False, - "partial_write": False, - "backup_paths": [], - "recovery_pending": False, - "recovered": False, - "replayed": False, - "readback": { - "source_missing": True, - "global_missing": True, - "verified": False, - }, - "stale": True, - "error_kind": "goal_registry_changed", - "error": "Goal disappeared after preview; regenerate the deletion preview", - } - - -def _backup_path(path: Path, timestamp: str, nonce: str) -> Path: - compact_timestamp = timestamp.replace(":", "").replace("-", "") - return path.with_name( - f"{path.name}.goal-delete-{compact_timestamp}-{nonce}.bak" - ) - - -def _create_backup(path: Path, *, timestamp: str) -> Path: - """Create an independent snapshot without ever overwriting an old backup.""" - - source_path = path.expanduser().resolve(strict=True) - if not source_path.is_file(): - raise ValueError(f"registry path is not a regular file: {source_path}") - for _ in range(8): - backup = _backup_path(source_path, timestamp, uuid.uuid4().hex) - try: - descriptor = os.open( - backup, - os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 0o600, - ) - except FileExistsError: - continue - try: - with source_path.open("rb") as source, os.fdopen(descriptor, "wb") as target: - shutil.copyfileobj(source, target) - target.flush() - os.fsync(target.fileno()) - shutil.copystat(source_path, backup) - except Exception: - backup.unlink(missing_ok=True) - raise - _fsync_parent(backup) - return backup - raise FileExistsError(f"could not allocate a unique Goal deletion backup for {source_path}") - - -def _remove_goal( - payload: dict[str, Any], - goal_id: str, - *, - updated_at: str | None = None, -) -> tuple[dict[str, Any], bool]: - goals = payload.get("goals") - if not isinstance(goals, list): - raise ValueError("registry goals must be a list") - retained = [ - goal - for goal in goals - if not (isinstance(goal, dict) and str(goal.get("id") or "") == goal_id) - ] - changed = len(retained) != len(goals) - updated = dict(payload) - updated["goals"] = retained - if changed: - updated["updated_at"] = now_local_iso() if updated_at is None else updated_at - return updated, changed - - -def _recovery_receipt_path(registry_path: Path, goal_id: str) -> Path: - registry = registry_path.expanduser().resolve() - goal_digest = hashlib.sha256(goal_id.encode("utf-8")).hexdigest() - return registry.with_name( - f".{registry.name}.goal-delete-{goal_digest}.recovery.json" - ) - - -def _canonical_writer_guard_path(target_registry: Path, goal_id: str) -> Path: - runtime_root = target_registry.expanduser().resolve().parent - return shadow_maintenance_lock_target(runtime_root, goal_id) - - -def _fsync_parent(path: Path) -> None: - if os.name != "posix": - return - descriptor = os.open(path.parent, os.O_RDONLY) - try: - os.fsync(descriptor) - finally: - os.close(descriptor) - - -def _build_recovery_record( - *, - goal_id: str, - state_fingerprint: str, - source_basis: Mapping[str, str], - source_registry: Path, - declared_source_registry: Path, - target_registry: Path, - source_available: bool, - same_registry: bool, - paths: list[Path], - backup_paths: Mapping[Path, Path], -) -> dict[str, Any]: - snapshots = [] - for path in paths: - backup = backup_paths[path] - snapshots.append( - { - "registry_path": str(path.expanduser().resolve()), - "backup_path": str(backup.expanduser().resolve()), - "preimage_sha256": hashlib.sha256(backup.read_bytes()).hexdigest(), - } - ) - return { - "schema_version": GOAL_DELETION_RECOVERY_SCHEMA_VERSION, - "goal_id": goal_id, - "state_fingerprint": state_fingerprint, - "source_basis": dict(source_basis), - "source_registry": str(source_registry.expanduser().resolve()), - "declared_source_registry": str( - declared_source_registry.expanduser().resolve() - ), - "target_registry": str(target_registry.expanduser().resolve()), - "source_available": source_available, - "same_registry": same_registry, - "snapshots": snapshots, - } - - -def _validated_recovery_path(value: Any, *, field: str) -> Path: - text = str(value or "").strip() - path = Path(text) - if not text or not path.is_absolute(): - raise ValueError(f"Goal deletion recovery {field} must be absolute") - return path.resolve() - - -def _validated_recovery_record( - value: Mapping[str, Any], - *, - receipt_path: Path, - goal_id: str, -) -> dict[str, Any]: - if value.get("schema_version") != GOAL_DELETION_RECOVERY_SCHEMA_VERSION: - raise ValueError("Goal deletion recovery schema is unsupported") - if value.get("goal_id") != goal_id: - raise ValueError("Goal deletion recovery goal identity does not match") - state_fingerprint = str(value.get("state_fingerprint") or "") - if not BARE_SHA256_PATTERN.fullmatch(state_fingerprint): - raise ValueError("Goal deletion recovery state fingerprint is invalid") - source_basis_value = value.get("source_basis") - if not isinstance(source_basis_value, Mapping): - raise ValueError("Goal deletion recovery source basis is missing") - source_basis = _normalize_source_basis(source_basis_value) - if source_basis is None: - raise ValueError("Goal deletion recovery source basis is missing") - source_registry = _validated_recovery_path( - value.get("source_registry"), - field="source registry", - ) - declared_source_registry = _validated_recovery_path( - value.get("declared_source_registry"), - field="declared source registry", - ) - target_registry = _validated_recovery_path( - value.get("target_registry"), - field="target registry", - ) - source_available = value.get("source_available") - same_registry = value.get("same_registry") - if not isinstance(source_available, bool) or not isinstance(same_registry, bool): - raise ValueError("Goal deletion recovery route flags are invalid") - if same_registry != _same_path(source_registry, target_registry): - raise ValueError("Goal deletion recovery same-registry flag is invalid") - if source_available != _same_path(source_registry, declared_source_registry): - raise ValueError("Goal deletion recovery source route is invalid") - if not source_available and not same_registry: - raise ValueError("Goal deletion recovery fallback route is invalid") - expected_source_identity = _goal_activation_source_identity( - declared_source_registry - ) - if source_basis["source_identity"] != expected_source_identity: - raise ValueError("Goal deletion recovery source identity does not match") - snapshots_value = value.get("snapshots") - if not isinstance(snapshots_value, list): - raise ValueError("Goal deletion recovery snapshots are missing") - expected_paths = [target_registry] - if source_available and not same_registry: - expected_paths.insert(0, source_registry) - snapshots: list[dict[str, str]] = [] - seen_paths: list[Path] = [] - for snapshot_value in snapshots_value: - if not isinstance(snapshot_value, Mapping): - raise ValueError("Goal deletion recovery snapshot is invalid") - registry_path = _validated_recovery_path( - snapshot_value.get("registry_path"), - field="snapshot registry path", - ) - backup_path = _validated_recovery_path( - snapshot_value.get("backup_path"), - field="snapshot backup path", - ) - preimage_sha256 = str(snapshot_value.get("preimage_sha256") or "") - if not BARE_SHA256_PATTERN.fullmatch(preimage_sha256): - raise ValueError("Goal deletion recovery preimage digest is invalid") - if backup_path.parent != registry_path.parent or not ( - backup_path.name.startswith(f"{registry_path.name}.goal-delete-") - and backup_path.name.endswith(".bak") - ): - raise ValueError("Goal deletion recovery backup path is invalid") - if backup_path.is_symlink() or not backup_path.is_file(): - raise ValueError("Goal deletion recovery backup is unavailable") - if any(_same_path(registry_path, seen) for seen in seen_paths): - raise ValueError("Goal deletion recovery repeats a registry path") - seen_paths.append(registry_path) - snapshots.append( - { - "registry_path": str(registry_path), - "backup_path": str(backup_path), - "preimage_sha256": preimage_sha256, - } - ) - if len(seen_paths) != len(expected_paths) or any( - not _same_path(actual, expected) - for actual, expected in zip(seen_paths, expected_paths, strict=True) - ): - raise ValueError("Goal deletion recovery registry set is invalid") - normalized: dict[str, Any] = { - "schema_version": GOAL_DELETION_RECOVERY_SCHEMA_VERSION, - "goal_id": goal_id, - "state_fingerprint": state_fingerprint, - "source_basis": source_basis, - "source_registry": str(source_registry), - "declared_source_registry": str(declared_source_registry), - "target_registry": str(target_registry), - "source_available": source_available, - "same_registry": same_registry, - "snapshots": snapshots, - } - expected_receipts = [ - _recovery_receipt_path(path, goal_id) for path in expected_paths - ] - if not any(_same_path(receipt_path, expected) for expected in expected_receipts): - raise ValueError("Goal deletion recovery receipt path is invalid") - return normalized +_OPAQUE_ID = OPAQUE_ID_PATTERN -def _load_recovery_record(path: Path, goal_id: str) -> dict[str, Any]: - if path.is_symlink() or not path.is_file(): - raise ValueError("Goal deletion recovery receipt is unavailable") - if path.stat().st_size > _MAX_RECOVERY_RECEIPT_BYTES: - raise ValueError("Goal deletion recovery receipt exceeds its size limit") - return _validated_recovery_record( - read_json(path), - receipt_path=path, - goal_id=goal_id, +def _normalize_source_basis(value: PayloadView | None) -> dict[str, str] | None: + return _normalize_source_basis_with_pattern( + value, + sha256_pattern=BARE_SHA256_PATTERN, ) -def _matching_recovery_record( - *, - requested_registry: Path, - goal_id: str, - expected_state_fingerprint: str | None, - expected_source_basis: Mapping[str, str] | None, -) -> dict[str, Any] | None: - if expected_state_fingerprint is None or expected_source_basis is None: - return None - receipt_path = _recovery_receipt_path(requested_registry, goal_id) - if not os.path.lexists(receipt_path): - return None - record = _load_recovery_record(receipt_path, goal_id) - if record["state_fingerprint"] != expected_state_fingerprint or record[ - "source_basis" - ] != dict(expected_source_basis): - return None - return record +def _load_registry_payload(path: Path) -> Payload: + return _as_payload(load_registry(path)) -def _write_recovery_receipts(record: Mapping[str, Any]) -> None: - goal_id = str(record["goal_id"]) - for snapshot in record["snapshots"]: - receipt_path = _recovery_receipt_path( - Path(snapshot["registry_path"]), - goal_id, - ) - if receipt_path.is_symlink() or ( - receipt_path.exists() and not receipt_path.is_file() - ): - raise ValueError("Goal deletion recovery receipt path is unsafe") - atomic_write_json(receipt_path, dict(record), preserve_mode=True) - _fsync_parent(receipt_path) - if _load_recovery_record(receipt_path, goal_id) != record: - raise ValueError("Goal deletion recovery receipt readback did not verify") - - -def _recovery_images( - record: Mapping[str, Any], -) -> dict[Path, tuple[dict[str, Any], str]]: - images: dict[Path, tuple[dict[str, Any], str]] = {} - for snapshot in record["snapshots"]: - registry_path = Path(snapshot["registry_path"]) - backup_path = Path(snapshot["backup_path"]) - raw_preimage = backup_path.read_bytes() - preimage_sha256 = hashlib.sha256(raw_preimage).hexdigest() - if preimage_sha256 != snapshot["preimage_sha256"]: - raise ValueError("Goal deletion recovery backup digest does not match") - preimage = decode_registry_snapshot(registry_path, raw_preimage) - if _goal_or_none(preimage, str(record["goal_id"])) is None: - raise ValueError("Goal deletion recovery backup is missing its Goal") - images[registry_path] = (preimage, preimage_sha256) - return images - - -def _recovery_states( - record: Mapping[str, Any], -) -> tuple[ - dict[Path, str], - dict[Path, tuple[dict[str, Any], str]], -]: - images = _recovery_images(record) - states: dict[Path, str] = {} - for path, (preimage, preimage_sha256) in images.items(): - try: - current_bytes = path.read_bytes() - current = load_registry(path) - except (OSError, UnicodeError, ValueError) as exc: - raise ValueError( - "Goal deletion recovery conflicts with current registry state" - ) from exc - if hashlib.sha256(current_bytes).hexdigest() == preimage_sha256: - states[path] = "preimage" - continue - postimage, changed = _remove_goal( - preimage, - str(record["goal_id"]), - updated_at=current.get("updated_at"), - ) - if not changed or current != postimage: - raise ValueError( - "Goal deletion recovery conflicts with current registry state" - ) - states[path] = "postimage" - return states, images - - -def _recovery_readback( - record: Mapping[str, Any], - states: Mapping[Path, str], -) -> dict[str, bool]: - source_registry = Path(record["source_registry"]) - declared_source_registry = Path(record["declared_source_registry"]) - target_registry = Path(record["target_registry"]) - source_available = bool(record["source_available"]) - source_missing = ( - states[source_registry] == "postimage" - if source_available - else _source_basis( - { - "declared_source_registry": declared_source_registry, - "source_status": _source_status( - declared_source_registry, - goal_id=str(record["goal_id"]), - ).value, - "route_mode": record["source_basis"]["route_mode"], - } - ) - == record["source_basis"] +def _recovery_hooks() -> RecoveryRuntimeHooks: + return RecoveryRuntimeHooks( + load_registry_fn=_load_registry_payload, + atomic_write_json_fn=atomic_write_json, + project_registry_transaction_fn=project_registry_transaction, + write_locked_registry_fn=_write_locked_registry, + restore_locked_registry_fn=_restore_locked_registry, + now_local_iso_fn=now_local_iso, + sha256_pattern=BARE_SHA256_PATTERN, ) - global_missing = states[target_registry] == "postimage" - return { - "source_missing": source_missing, - "global_missing": global_missing, - "verified": source_missing and global_missing, - } - -def _recovery_result( - record: Mapping[str, Any], - states: Mapping[Path, str], - *, - execute: bool, - written: bool, -) -> dict[str, Any]: - readback = _recovery_readback(record, states) - if not record["source_available"] and not readback["source_missing"]: - raise ValueError("Goal deletion recovery conflicts with current registry state") - source_registry = Path(record["source_registry"]) - target_registry = Path(record["target_registry"]) - return { - "ok": True, - "schema_version": GOAL_DELETION_SCHEMA_VERSION, - "dry_run": not execute, - "execute": execute, - "goal_id": record["goal_id"], - "source_registry": str(source_registry), - "target_global_registry": str(target_registry), - "source_registry_present": bool( - record["source_available"] and states[source_registry] == "preimage" - ), - "global_registry_present": states[target_registry] == "preimage", - "source_basis": dict(record["source_basis"]), - "authority_route_mode": record["source_basis"]["route_mode"], - "expected_state_fingerprint": record["state_fingerprint"], - "observed_state_fingerprint": record["state_fingerprint"], - "written": written, - "partial_write": any(state == "postimage" for state in states.values()) - and not readback["verified"], - "backup_paths": [ - str(snapshot["backup_path"]) for snapshot in record["snapshots"] - ], - "readback": readback, - "recovery_pending": not execute, - "recovered": execute and readback["verified"], - "replayed": execute and readback["verified"] and not written, - } - - -def _recovery_receipts_match(record: Mapping[str, Any]) -> bool: - goal_id = str(record["goal_id"]) - for snapshot in record["snapshots"]: - receipt_path = _recovery_receipt_path( - Path(snapshot["registry_path"]), - goal_id, - ) - if not os.path.lexists(receipt_path): - return False - current = _load_recovery_record(receipt_path, goal_id) - if current != record: - return False - return True - -def _execute_recovery(record: Mapping[str, Any]) -> dict[str, Any]: - """Converge every recorded preimage to deletion without overwriting drift.""" - - source_registry = Path(record["source_registry"]) - declared_source_registry = Path(record["declared_source_registry"]) - target_registry = Path(record["target_registry"]) - source_available = bool(record["source_available"]) - same_registry = bool(record["same_registry"]) - locked_source_registry = ( - source_registry if source_available else declared_source_registry - ) - with ExitStack() as stack: - stack.enter_context( - exclusive_cross_runtime_file_lock( - _canonical_writer_guard_path(target_registry, str(record["goal_id"])), - operation="recover_delete_stopped_goal_canonical", - timeout_seconds=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, - ) - ) - source_transaction = None - if not _same_path(locked_source_registry, target_registry): - if source_available and not same_registry: - source_transaction = stack.enter_context( - project_registry_transaction( - locked_source_registry, - operation="recover_delete_stopped_goal", - ) - ) - else: - stack.enter_context( - exclusive_cross_runtime_file_lock( - locked_source_registry, - operation="recover_delete_stopped_goal", - ) - ) - stack.enter_context( - exclusive_cross_runtime_file_lock( - target_registry, - operation="recover_delete_stopped_goal", - ) - ) - states, images = _recovery_states(record) - if not _recovery_receipts_match(record): - if any(state == "postimage" for state in states.values()): - raise ValueError( - "Goal deletion recovery conflicts with current registry state" - ) - _write_recovery_receipts(record) - - written_paths: list[Path] = [] - try: - for snapshot in record["snapshots"]: - path = Path(snapshot["registry_path"]) - if states[path] == "postimage": - continue - preimage, _digest = images[path] - postimage, changed = _remove_goal( - preimage, - str(record["goal_id"]), - ) - if not changed: - raise ValueError( - "Goal deletion recovery backup is missing its Goal" - ) - _write_locked_registry( - path=path, - updated=postimage, - source_registry=source_registry, - source_transaction=source_transaction, - ) - written_paths.append(path) - final_states, _final_images = _recovery_states(record) - result = _recovery_result( - record, - final_states, - execute=True, - written=bool(written_paths), - ) - if not result["readback"]["verified"]: - raise ValueError("Goal deletion recovery readback did not verify") - return result - except Exception: - for path in reversed(written_paths): - preimage, _digest = images[path] - _restore_locked_registry( - path=path, - current=preimage, - source_registry=source_registry, - source_transaction=source_transaction, - ) - raise +def _execute_recovery(record: RecoveryRecord | PayloadView) -> DeletionResult: + return _run_execute_recovery(record, hooks=_recovery_hooks()) def _resolve_route( @@ -725,18 +110,20 @@ def _resolve_route( registry_path: Path, *, require_stopped: bool = True, -) -> dict[str, Any]: +) -> DeletionRoute: route = _source_and_target( registry_path=registry_path, goal_id=goal_id, target_state=GoalActivationState.STOPPED, runtime_root_override=None, ) - source_available = route.mode is not GoalActivationAuthorityRouteMode.ORPHANED_GLOBAL_STOP_FALLBACK - source_payload = load_registry(route.source_registry) if source_available else None - target_payload = read_json(route.target_registry) - source_goal = _goal_or_none(source_payload, goal_id) if source_payload else None - target_goal = _goal_or_none(target_payload, goal_id) + source_available = ( + route.mode is not GoalActivationAuthorityRouteMode.ORPHANED_GLOBAL_STOP_FALLBACK + ) + source_payload = _load_registry_payload(route.source_registry) if source_available else None + target_payload = _as_payload(read_json(route.target_registry)) + source_goal = _goal_payload_or_none(source_payload, goal_id) + target_goal = _goal_payload_or_none(target_payload, goal_id) goal = source_goal or target_goal if goal is None: raise ValueError(f"goal id not found in registry: {goal_id}") @@ -745,9 +132,7 @@ def _resolve_route( if target_goal is None: raise ValueError("global registry does not contain the Goal projection") declared_source_registry = route.source_registry - if ( - route.mode is GoalActivationAuthorityRouteMode.ORPHANED_GLOBAL_STOP_FALLBACK - ): + if route.mode is GoalActivationAuthorityRouteMode.ORPHANED_GLOBAL_STOP_FALLBACK: source_ref = str(target_goal.get("source_registry") or "").strip() if source_ref: declared_source_registry = Path(source_ref).expanduser().resolve() @@ -764,51 +149,25 @@ def _resolve_route( } -def _check_writability(paths: list[Path]) -> dict[str, Any] | None: - writability = [ - probe_registry_write_path(path, create_parent=False) for path in paths - ] - return next((item for item in writability if not item.get("ok")), None) - - -def _orphan_source_lock_error(path: Path) -> str | None: - parent = path.parent - if parent.exists() and (not parent.is_dir() or parent.is_symlink()): - return "Goal source registry parent is unavailable for safe locking" - kernel_lock = path.with_name(f"{path.name}.lock") - lock_artifacts = { - kernel_lock, - *lock_holder_paths(path), - lock_incident_path(path), - Path(f"{path}{EFFECT_MUTATION_LOCK_SUFFIX}"), - } - if any( - artifact.is_symlink() - or (artifact.exists() and not artifact.is_file()) - for artifact in lock_artifacts - ): - return "Goal source registry lock path is unsafe" - return None - - -def _route_matches_locked_paths( - route: Mapping[str, Any], +def _route_snapshot( *, - source_registry: Path, - declared_source_registry: Path, - target_registry: Path, - source_available: bool, - same_registry: bool, -) -> bool: + goal_id: str, + requested_registry: Path, +) -> tuple[DeletionRoute, dict[str, str], str]: + route = _resolve_route( + goal_id, + requested_registry, + require_stopped=False, + ) + source_basis = _source_basis(route) return ( - _same_path(Path(route["source_registry"]), source_registry) - and _same_path( - Path(route["declared_source_registry"]), - declared_source_registry, - ) - and _same_path(Path(route["target_registry"]), target_registry) - and bool(route["source_available"]) is source_available - and bool(route["same_registry"]) is same_registry + route, + source_basis, + _state_fingerprint( + goal_id=goal_id, + source_basis=source_basis, + target_registry=route["target_registry"], + ), ) @@ -823,8 +182,8 @@ def _validated_locked_route_snapshot( goal_id: str, expected_state_fingerprint: str | None, expected_source_basis: Mapping[str, str] | None, - payload: dict[str, Any], -) -> tuple[dict[str, Any], dict[str, str], str] | None: + payload: DeletionResult, +) -> tuple[DeletionRoute, dict[str, str], str] | None: try: locked_route, current_source_basis, current_fingerprint = _route_snapshot( goal_id=goal_id, @@ -850,12 +209,16 @@ def _validated_locked_route_snapshot( source_available=source_available, same_registry=same_registry, ) - if route_changed or ( - expected_state_fingerprint is not None - and current_fingerprint != expected_state_fingerprint - ) or ( - expected_source_basis is not None - and current_source_basis != expected_source_basis + if ( + route_changed + or ( + expected_state_fingerprint is not None + and current_fingerprint != expected_state_fingerprint + ) + or ( + expected_source_basis is not None + and current_source_basis != expected_source_basis + ) ): _mark_stale( payload, @@ -866,28 +229,6 @@ def _validated_locked_route_snapshot( return locked_route, current_source_basis, current_fingerprint -def _route_snapshot( - *, - goal_id: str, - requested_registry: Path, -) -> tuple[dict[str, Any], dict[str, str], str]: - route = _resolve_route( - goal_id, - requested_registry, - require_stopped=False, - ) - source_basis = _source_basis(route) - return ( - route, - source_basis, - _state_fingerprint( - goal_id=goal_id, - source_basis=source_basis, - target_registry=Path(route["target_registry"]), - ), - ) - - def _load_locked_payloads( *, requested_registry: Path, @@ -899,16 +240,16 @@ def _load_locked_payloads( goal_id: str, expected_state_fingerprint: str | None, expected_source_basis: Mapping[str, str] | None, - payload: dict[str, Any], -) -> tuple[dict[Path, dict[str, Any]], dict[str, str], str] | None: + payload: DeletionResult, +) -> tuple[dict[Path, Payload], dict[str, str], str] | None: current_source = ( - read_json(source_registry) + _as_payload(read_json(source_registry)) if source_available and same_registry - else load_registry(source_registry) + else _load_registry_payload(source_registry) if source_available else None ) - current_target = read_json(target_registry) + current_target = _as_payload(read_json(target_registry)) snapshot = _validated_locked_route_snapshot( requested_registry=requested_registry, source_registry=source_registry, @@ -925,8 +266,8 @@ def _load_locked_payloads( return None _, current_source_basis, current_fingerprint = snapshot - source_goal = _goal_or_none(current_source, goal_id) if current_source else None - target_goal = _goal_or_none(current_target, goal_id) + source_goal = _goal_payload_or_none(current_source, goal_id) + target_goal = _goal_payload_or_none(current_target, goal_id) locked_goal = source_goal or target_goal if locked_goal is None or target_goal is None: raise ValueError("Goal disappeared before deletion; refresh and retry") @@ -941,42 +282,25 @@ def _load_locked_payloads( def _updated_payloads( - current_payloads: dict[Path, dict[str, Any]], goal_id: str -) -> dict[Path, dict[str, Any]]: - updated_payloads: dict[Path, dict[str, Any]] = {} + current_payloads: dict[Path, Payload], goal_id: str +) -> dict[Path, Payload]: + updated_payloads: dict[Path, Payload] = {} for path, current in current_payloads.items(): - updated, changed = _remove_goal(current, goal_id) + updated, changed = _remove_goal( + current, + goal_id, + now_local_iso_fn=now_local_iso, + ) if not changed: raise ValueError("Goal disappeared before deletion; refresh and retry") updated_payloads[path] = updated return updated_payloads -def _deletion_write_paths( - *, - current_payloads: Mapping[Path, dict[str, Any]], - source_registry: Path, - target_registry: Path, - source_available: bool, -) -> list[Path]: - paths: list[Path] = [] - if ( - source_available - and not _same_path(source_registry, target_registry) - and source_registry in current_payloads - ): - paths.append(source_registry) - if target_registry in current_payloads: - paths.append(target_registry) - if len(paths) != len(current_payloads): - raise ValueError("Goal deletion registry set is invalid") - return paths - - def _write_deletion( *, - current_payloads: dict[Path, dict[str, Any]], - updated_payloads: dict[Path, dict[str, Any]], + current_payloads: dict[Path, Payload], + updated_payloads: dict[Path, Payload], source_registry: Path, declared_source_registry: Path, target_registry: Path, @@ -984,7 +308,7 @@ def _write_deletion( locked_source_basis: Mapping[str, str], locked_state_fingerprint: str, goal_id: str, - payload: dict[str, Any], + payload: DeletionResult, source_transaction: ProjectRegistryTransaction | None, ) -> None: written_paths: list[Path] = [] @@ -997,10 +321,11 @@ def _write_deletion( source_available=source_available, ) backup_paths: dict[Path, Path] = {} + backup_list = payload["backup_paths"] for path in paths: backup = _create_backup(path, timestamp=timestamp) backup_paths[path] = backup - payload["backup_paths"].append(str(backup)) + backup_list.append(str(backup)) recovery_record = _build_recovery_record( goal_id=goal_id, state_fingerprint=locked_state_fingerprint, @@ -1013,7 +338,11 @@ def _write_deletion( paths=paths, backup_paths=backup_paths, ) - _write_recovery_receipts(recovery_record) + _write_recovery_receipts( + recovery_record, + sha256_pattern=BARE_SHA256_PATTERN, + atomic_write_json_fn=atomic_write_json, + ) for path in paths: _write_locked_registry( path=path, @@ -1022,23 +351,27 @@ def _write_deletion( source_transaction=source_transaction, ) written_paths.append(path) - source_missing = ( - _goal_or_none(load_registry(source_registry), goal_id) is None - if source_available - else _source_basis( - { - "declared_source_registry": declared_source_registry, - "source_status": _source_status( - declared_source_registry, - goal_id=goal_id, - ).value, - "route_mode": locked_source_basis["route_mode"], - } + if source_available: + source_after = _load_registry_payload(source_registry) + source_missing = _goal_payload_or_none(source_after, goal_id) is None + else: + from .activation_service import _source_status + + source_missing = ( + _source_basis( + { + "declared_source_registry": declared_source_registry, + "source_status": _source_status( + declared_source_registry, + goal_id=goal_id, + ).value, + "route_mode": locked_source_basis["route_mode"], + } + ) + == locked_source_basis ) - == locked_source_basis - ) - target_after = read_json(target_registry) - global_missing = _goal_or_none(target_after, goal_id) is None + target_after = _as_payload(read_json(target_registry)) + global_missing = _goal_payload_or_none(target_after, goal_id) is None if not source_missing or not global_missing: raise ValueError("Goal deletion readback did not verify") payload["readback"] = { @@ -1065,7 +398,7 @@ def _write_deletion( def _write_locked_registry( *, path: Path, - updated: dict[str, Any], + updated: Payload, source_registry: Path, source_transaction: ProjectRegistryTransaction | None, ) -> None: @@ -1078,7 +411,7 @@ def _write_locked_registry( def _restore_locked_registry( *, path: Path, - current: dict[str, Any], + current: Payload, source_registry: Path, source_transaction: ProjectRegistryTransaction | None, ) -> None: @@ -1099,10 +432,9 @@ def _execute_deletion( goal_id: str, expected_state_fingerprint: str | None, expected_source_basis: Mapping[str, str] | None, - payload: dict[str, Any], + payload: DeletionResult, ) -> None: """Apply deletion and read it back while registry locks are held.""" - locked_source_registry = ( source_registry if source_available else declared_source_registry ) @@ -1114,7 +446,7 @@ def _execute_deletion( timeout_seconds=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, ) ) - source_transaction = None + source_transaction: ProjectRegistryTransaction | None = None if not _same_path(locked_source_registry, target_registry): if source_available and not same_registry: source_transaction = stack.enter_context( @@ -1131,7 +463,9 @@ def _execute_deletion( ) ) stack.enter_context( - exclusive_cross_runtime_file_lock(target_registry, operation="delete_stopped_goal") + exclusive_cross_runtime_file_lock( + target_registry, operation="delete_stopped_goal" + ) ) locked_state = _load_locked_payloads( requested_registry=requested_registry, @@ -1186,8 +520,8 @@ def delete_stopped_goal( goal_id: str, execute: bool = False, expected_state_fingerprint: str | None = None, - expected_source_basis: Mapping[str, Any] | None = None, -) -> dict[str, Any]: + expected_source_basis: PayloadView | None = None, +) -> DeletionResult: """Preview or permanently remove one stopped Goal from its registries. Goal data such as state files and project files is intentionally retained; @@ -1196,7 +530,6 @@ def delete_stopped_goal( while both registry locks are held. A matching write-ahead recovery receipt makes retries from the same preview idempotent after process termination. """ - normalized_goal_id = _require_opaque_id(goal_id, field="goal_id") requested_registry = Path(registry_path) normalized_fingerprint = str(expected_state_fingerprint or "").strip() or None @@ -1210,11 +543,15 @@ def delete_stopped_goal( goal_id=normalized_goal_id, expected_state_fingerprint=normalized_fingerprint, expected_source_basis=normalized_source_basis, + sha256_pattern=BARE_SHA256_PATTERN, ) if recovery_record is not None: if execute: return _execute_recovery(recovery_record) - recovery_states, _recovery_payloads = _recovery_states(recovery_record) + recovery_states, _recovery_payloads = _recovery_states( + recovery_record, + load_registry_fn=_load_registry_payload, + ) return _recovery_result( recovery_record, recovery_states, @@ -1246,32 +583,14 @@ def delete_stopped_goal( target_registry=route["target_registry"], ) - payload: dict[str, Any] = { - "ok": True, - "schema_version": GOAL_DELETION_SCHEMA_VERSION, - "dry_run": not execute, - "execute": execute, - "goal_id": normalized_goal_id, - "source_registry": str(route["source_registry"]), - "target_global_registry": str(route["target_registry"]), - "source_registry_present": route["source_goal"] is not None, - "global_registry_present": route["target_goal"] is not None, - "source_basis": observed_source_basis, - "authority_route_mode": route["route_mode"], - "expected_state_fingerprint": normalized_fingerprint, - "observed_state_fingerprint": observed_fingerprint, - "written": False, - "partial_write": False, - "backup_paths": [], - "recovery_pending": False, - "recovered": False, - "replayed": False, - "readback": { - "source_missing": route["source_goal"] is None, - "global_missing": False, - "verified": False, - }, - } + payload = _initial_deletion_payload( + goal_id=normalized_goal_id, + route=route, + execute=execute, + normalized_fingerprint=normalized_fingerprint, + observed_source_basis=observed_source_basis, + observed_fingerprint=observed_fingerprint, + ) if ( normalized_fingerprint is not None and observed_fingerprint != normalized_fingerprint @@ -1291,35 +610,7 @@ def delete_stopped_goal( if not execute: return payload - if not route["source_available"]: - lock_error = _orphan_source_lock_error(route["declared_source_registry"]) - if lock_error is not None: - payload.update( - { - "ok": False, - "error_kind": "goal_source_lock_unavailable", - "error": lock_error, - "recommended_action": ( - "Repair the Goal source registry route before deleting " - "this Goal." - ), - } - ) - return payload - - paths = [route["target_registry"]] - if not route["same_registry"]: - paths.append(route["source_registry"]) - writability = _check_writability(paths) - if writability is not None: - payload.update( - { - "ok": False, - "error_kind": "goal_registry_write_denied", - "error": str(writability.get("error") or "Goal registry is not writable"), - "recommended_action": writability.get("recommended_action"), - } - ) + if _apply_lock_or_writability_failure(payload, route): return payload _execute_deletion( diff --git a/tests/control_plane/test_deletion_service_contract.py b/tests/control_plane/test_deletion_service_contract.py new file mode 100644 index 0000000000..05f78d152e --- /dev/null +++ b/tests/control_plane/test_deletion_service_contract.py @@ -0,0 +1,344 @@ +from __future__ import annotations + +import ast +import io +import json +from pathlib import Path +import tokenize + +import pytest + +from loopx.control_plane.goals import deletion_basis, deletion_recovery, deletion_service +from loopx.control_plane.goals.activation import build_goal_activation +from loopx.control_plane.goals.activation_service import ( + GoalActivationAuthorityRouteMode, + set_goal_activation_state, +) +from loopx.control_plane.goals.deletion_basis import ( + _MAX_RECOVERY_RECEIPT_BYTES, + DeletionReadback, + DeletionResult, + DeletionRoute, + Payload, + PayloadView, +) +from loopx.control_plane.goals.deletion_recovery import ( + RecoveryRecord, + RecoveryRuntimeHooks, + RecoverySnapshot, + _as_recovery_record, + _load_recovery_record, +) +from loopx.control_plane.goals.deletion_service import ( + GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + GOAL_DELETION_SCHEMA_VERSION, + GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION, + GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION, + _normalize_source_basis, + _recovery_hooks, + _recovery_receipt_path, + delete_stopped_goal, +) +from loopx.global_registry import sync_project_registry_to_global +from loopx.history import load_registry +from loopx.public_safe_text import OPAQUE_ID_PATTERN +from loopx.registry import registry_goals +from loopx.semantics.inventory import SourceFile +from loopx.semantics.project_registry_io import scan_python_registry_io + +_SHA256_A = "a" * 64 +_SHA256_B = "b" * 64 +_REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _write_json(path: Path, payload: dict[str, object]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + + +def _stopped_connected_registries(tmp_path: Path) -> tuple[Path, Path]: + runtime_root = tmp_path / "runtime" + source_registry = tmp_path / "project" / ".loopx" / "registry.json" + _write_json( + source_registry, + { + "schema_version": "0.1", + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": "goal-one", + "display_name": "Contract Goal", + "repo": str(tmp_path / "project"), + "quota": {"compute": 1, "allowed_slots": 4, "spent_slots": 0}, + } + ], + }, + ) + synced = sync_project_registry_to_global( + registry_path=source_registry, + runtime_root_override=str(runtime_root), + goal_id="goal-one", + dry_run=False, + ) + assert synced["ok"] is True + global_registry = runtime_root / "registry.global.json" + stopped = set_goal_activation_state( + registry_path=global_registry, + goal_id="goal-one", + state="stopped", + actor_kind="owner", + execute=True, + ) + assert stopped["ok"] is True + return source_registry, global_registry + + +def test_deletion_modules_strict_zero_any_size_and_boundaries() -> None: + targets = [ + _REPO_ROOT / "loopx" / "control_plane" / "goals" / "deletion_basis.py", + _REPO_ROOT / "loopx" / "control_plane" / "goals" / "deletion_recovery.py", + _REPO_ROOT / "loopx" / "control_plane" / "goals" / "deletion_service.py", + Path(__file__).resolve(), + ] + for path in targets: + text = path.read_text(encoding="utf-8") + lines = text.splitlines() + assert len(lines) < 700, f"{path} exceeded 700 LOC ({len(lines)})" + comments = [ + tok.string + for tok in tokenize.generate_tokens(io.StringIO(text).readline) + if tok.type == tokenize.COMMENT + ] + assert not any( + "type: ignore" in comment or "noqa" in comment for comment in comments + ), f"{path} contains suppression comments" + tree = ast.parse(text) + any_names = [ + node + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + ] + assert any_names == [], f"{path} must remain 0-Any" + + for helper_path in targets[:2]: + rel_path = helper_path.relative_to(_REPO_ROOT).as_posix() + text = helper_path.read_text(encoding="utf-8") + assert "content_digest" not in text + observations = scan_python_registry_io( + SourceFile(path=rel_path, suffix=".py", text=text) + ) + direct_io = [ + obs for obs in observations if obs.kind.startswith("direct_json_") + ] + assert direct_io == [] + + +def test_deletion_service_reexports_and_runtime_seams() -> None: + assert deletion_service._OPAQUE_ID is OPAQUE_ID_PATTERN + assert deletion_service.GOAL_DELETION_SCHEMA_VERSION == GOAL_DELETION_SCHEMA_VERSION + assert ( + deletion_service.GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION + == GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION + ) + assert ( + deletion_service.GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION + == GOAL_DELETION_STATE_FINGERPRINT_SCHEMA_VERSION + ) + assert ( + deletion_service.GOAL_DELETION_RECOVERY_SCHEMA_VERSION + == GOAL_DELETION_RECOVERY_SCHEMA_VERSION + ) + assert deletion_service.DeletionResult is DeletionResult + assert deletion_service.DeletionReadback is DeletionReadback + assert deletion_service.DeletionRoute is DeletionRoute + assert deletion_service.Payload is Payload + assert deletion_service.PayloadView is PayloadView + assert deletion_service.RecoveryRecord is RecoveryRecord + assert deletion_service.RecoverySnapshot is RecoverySnapshot + assert deletion_service.RecoveryRuntimeHooks is RecoveryRuntimeHooks + assert deletion_basis._MAX_RECOVERY_RECEIPT_BYTES == _MAX_RECOVERY_RECEIPT_BYTES + assert deletion_recovery._execute_recovery is not None + + hooks = _recovery_hooks() + assert hooks.atomic_write_json_fn is deletion_service.atomic_write_json + assert ( + hooks.project_registry_transaction_fn + is deletion_service.project_registry_transaction + ) + assert hooks.write_locked_registry_fn is deletion_service._write_locked_registry + assert hooks.restore_locked_registry_fn is deletion_service._restore_locked_registry + assert hooks.now_local_iso_fn is deletion_service.now_local_iso + + +def test_normalize_source_basis_and_input_validation_fail_closed( + tmp_path: Path, +) -> None: + valid_basis = { + "schema_version": GOAL_DELETION_SOURCE_BASIS_SCHEMA_VERSION, + "source_identity": _SHA256_A, + "source_content_sha256": _SHA256_B, + "route_mode": GoalActivationAuthorityRouteMode.SOURCE_TO_GLOBAL.value, + } + assert _normalize_source_basis(valid_basis) == valid_basis + assert _normalize_source_basis(None) is None + + for bad_basis in ( + {**valid_basis, "schema_version": "wrong"}, + {**valid_basis, "source_identity": "short"}, + {**valid_basis, "source_content_sha256": "short"}, + {**valid_basis, "route_mode": "unsupported"}, + ): + with pytest.raises(ValueError): + _normalize_source_basis(bad_basis) + + _source_registry, global_registry = _stopped_connected_registries(tmp_path) + with pytest.raises(ValueError, match="compact opaque id"): + delete_stopped_goal(registry_path=global_registry, goal_id="../escape") + with pytest.raises(ValueError, match="SHA-256 digest"): + delete_stopped_goal( + registry_path=global_registry, + goal_id="goal-one", + expected_state_fingerprint="not-a-digest", + ) + with pytest.raises(ValueError, match="expected source route mode is unsupported"): + delete_stopped_goal( + registry_path=global_registry, + goal_id="goal-one", + expected_source_basis={**valid_basis, "route_mode": "invalid"}, + ) + + +def test_load_and_as_recovery_record_reject_malformed_and_oversized_inputs( + tmp_path: Path, +) -> None: + pattern = _recovery_hooks().sha256_pattern + target_registry = tmp_path / "runtime" / "registry.global.json" + _write_json(target_registry, {"schema_version": "0.1", "goals": []}) + receipt_path = _recovery_receipt_path(target_registry, "goal-one") + + with pytest.raises(ValueError, match="unavailable"): + _load_recovery_record(receipt_path, "goal-one", sha256_pattern=pattern) + + receipt_path.parent.mkdir(parents=True, exist_ok=True) + receipt_path.write_text("x" * (_MAX_RECOVERY_RECEIPT_BYTES + 1), encoding="utf-8") + with pytest.raises(ValueError, match="size limit"): + _load_recovery_record(receipt_path, "goal-one", sha256_pattern=pattern) + + symlink_target = tmp_path / "outside.json" + symlink_target.write_text("{}", encoding="utf-8") + receipt_path.unlink() + receipt_path.symlink_to(symlink_target) + with pytest.raises(ValueError, match="unavailable"): + _load_recovery_record(receipt_path, "goal-one", sha256_pattern=pattern) + + with pytest.raises(ValueError, match="goal identity"): + _as_recovery_record({"target_registry": str(target_registry)}, sha256_pattern=pattern) + + _write_json( + symlink_target, + { + "schema_version": "wrong", + "goal_id": "goal-one", + }, + ) + receipt_path.unlink() + _write_json( + receipt_path, + { + "schema_version": GOAL_DELETION_RECOVERY_SCHEMA_VERSION, + "goal_id": "goal-one", + "state_fingerprint": "bad", + }, + ) + with pytest.raises(ValueError, match="state fingerprint"): + _load_recovery_record(receipt_path, "goal-one", sha256_pattern=pattern) + + +def test_delete_stopped_goal_missing_stale_lock_failure_and_replay_contract( + tmp_path: Path, +) -> None: + source_registry, global_registry = _stopped_connected_registries(tmp_path) + + with pytest.raises(ValueError, match="goal id not found in registry"): + delete_stopped_goal(registry_path=global_registry, goal_id="missing-goal") + + missing_stale = delete_stopped_goal( + registry_path=global_registry, + goal_id="missing-goal", + execute=True, + expected_state_fingerprint=_SHA256_A, + ) + assert isinstance(missing_stale, DeletionResult) + assert isinstance(missing_stale, dict) + assert missing_stale["ok"] is False + assert missing_stale["stale"] is True + assert missing_stale["error_kind"] == "goal_registry_changed" + assert missing_stale["readback"]["verified"] is False + + preview = delete_stopped_goal( + registry_path=global_registry, + goal_id="goal-one", + execute=False, + ) + assert preview["ok"] is True + assert preview["dry_run"] is True + + deleted = delete_stopped_goal( + registry_path=global_registry, + goal_id="goal-one", + execute=True, + expected_state_fingerprint=preview["observed_state_fingerprint"], + expected_source_basis=preview["source_basis"], + ) + assert deleted["ok"] is True + assert deleted["written"] is True + assert deleted["readback"]["verified"] is True + assert registry_goals(load_registry(source_registry)) == [] + assert registry_goals(load_registry(global_registry)) == [] + + replayed = delete_stopped_goal( + registry_path=global_registry, + goal_id="goal-one", + execute=True, + expected_state_fingerprint=preview["observed_state_fingerprint"], + expected_source_basis=preview["source_basis"], + ) + assert replayed["ok"] is True + assert replayed["written"] is False + assert replayed["recovered"] is True + assert replayed["replayed"] is True + assert replayed["readback"]["verified"] is True + + orphan_source = tmp_path / "orphan-project" / ".loopx" / "registry.json" + orphan_source.parent.mkdir(parents=True, exist_ok=True) + lock_target = tmp_path / "lock-target" + lock_target.write_text("", encoding="utf-8") + orphan_source.with_name(f"{orphan_source.name}.lock").symlink_to(lock_target) + orphan_global = tmp_path / "orphan-runtime" / "registry.global.json" + _write_json( + orphan_global, + { + "schema_version": "0.1", + "registry_role": "global-local", + "goals": [ + { + "id": "orphaned-goal", + "display_name": "Orphaned Goal", + "source_registry": str(orphan_source), + "activation": build_goal_activation( + state="stopped", + updated_at="2026-08-20T00:00:00+00:00", + reason="Fixture setup", + ), + } + ], + }, + ) + blocked = delete_stopped_goal( + registry_path=orphan_global, + goal_id="orphaned-goal", + execute=True, + ) + assert blocked["ok"] is False + assert blocked["error_kind"] == "goal_source_lock_unavailable" From 11a7a6b393ecadb4010c57a02384157cae09714c Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:51:10 +0800 Subject: [PATCH 2/2] fix(chat): align goal_lifecycle_actions with DeletionResult typing Use dedicated deletion_preview and deletion_current local variables in ChatGoalLifecycleActionMixin and read deletion readback through the typed deletion_readback helper without changing runtime behavior. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/chat/goal_lifecycle_actions.py | 33 +++++---- loopx/control_plane/goals/deletion_basis.py | 12 ++++ loopx/control_plane/goals/deletion_service.py | 1 + .../test_deletion_service_contract.py | 71 +++++++++++++++++++ 4 files changed, 104 insertions(+), 13 deletions(-) diff --git a/loopx/chat/goal_lifecycle_actions.py b/loopx/chat/goal_lifecycle_actions.py index 5580c55a64..c66a98552d 100644 --- a/loopx/chat/goal_lifecycle_actions.py +++ b/loopx/chat/goal_lifecycle_actions.py @@ -6,7 +6,11 @@ from ..control_plane.goals.activation import GoalActivationState, goal_activation_state from ..control_plane.goals.activation_service import set_goal_activation_state -from ..control_plane.goals.deletion_service import delete_stopped_goal +from ..control_plane.goals.deletion_service import ( + DeletionResult, + delete_stopped_goal as delete_stopped_goal, + deletion_readback, +) GOAL_LIFECYCLE_SOURCE_BASIS_SCHEMA_VERSION = "loopx_goal_lifecycle_source_basis_v1" @@ -21,21 +25,21 @@ def _goal_lifecycle_preview( ) -> dict[str, Any]: operation = str(parameters["operation"]) if operation == "delete": - preview = delete_stopped_goal( + deletion_preview: DeletionResult = delete_stopped_goal( registry_path=self.registry_path, goal_id=str(parameters["goal_id"]), execute=False, ) - fingerprint = str(preview.get("observed_state_fingerprint") or "") - source_basis = preview.get("source_basis") + fingerprint = str(deletion_preview.get("observed_state_fingerprint") or "") + source_basis = deletion_preview.get("source_basis") if ( - not preview.get("ok") + not deletion_preview.get("ok") or not fingerprint or not isinstance(source_basis, dict) ): raise ValueError( str( - preview.get("error") + deletion_preview.get("error") or "Goal deletion source basis is unavailable" ) ) @@ -111,7 +115,7 @@ def _apply_goal_delete( ) return {"proposal": stale, "turn": None} - result = delete_stopped_goal( + result: DeletionResult = delete_stopped_goal( registry_path=self.registry_path, goal_id=goal_id, execute=True, @@ -138,7 +142,8 @@ def _apply_goal_delete( if not result.get("written") and not result.get("partial_write"): return self._goal_delete_failed(proposal_id, error) raise error - if not (result.get("readback") or {}).get("verified"): + readback = deletion_readback(result) + if readback is None or not readback["verified"]: raise ValueError("Goal deletion did not verify") receipt = { "receipt_id": _digest( @@ -189,7 +194,7 @@ def _apply_goal_lifecycle( else None ) try: - current = delete_stopped_goal( + deletion_current: DeletionResult = delete_stopped_goal( registry_path=self.registry_path, goal_id=goal_id, execute=False, @@ -198,9 +203,11 @@ def _apply_goal_lifecycle( ) except (OSError, ValueError) as exc: return self._goal_delete_failed(proposal_id, exc) - current_fingerprint = str(current.get("observed_state_fingerprint") or "") - if not current.get("ok") or not current_fingerprint: - if current.get("stale") and current_fingerprint: + current_fingerprint = str( + deletion_current.get("observed_state_fingerprint") or "" + ) + if not deletion_current.get("ok") or not current_fingerprint: + if deletion_current.get("stale") and current_fingerprint: stale = self.store.apply( proposal_id, current_state_fingerprint=current_fingerprint, @@ -211,7 +218,7 @@ def _apply_goal_lifecycle( proposal_id, ValueError( str( - current.get("error") + deletion_current.get("error") or "Goal deletion source basis is unavailable" ) ), diff --git a/loopx/control_plane/goals/deletion_basis.py b/loopx/control_plane/goals/deletion_basis.py index 950d497c6b..9effaf842f 100644 --- a/loopx/control_plane/goals/deletion_basis.py +++ b/loopx/control_plane/goals/deletion_basis.py @@ -138,6 +138,18 @@ def __getitem__(self, key: str, /) -> object: return super().__getitem__(key) +def deletion_readback(payload: PayloadView) -> DeletionReadback | None: + """Return the typed readback block from a deletion result when present.""" + raw = payload.get("readback") + if not isinstance(raw, Mapping): + return None + return { + "source_missing": bool(raw.get("source_missing")), + "global_missing": bool(raw.get("global_missing")), + "verified": bool(raw.get("verified")), + } + + def _as_payload(value: Mapping[str, object]) -> Payload: return {str(key): item for key, item in value.items()} diff --git a/loopx/control_plane/goals/deletion_service.py b/loopx/control_plane/goals/deletion_service.py index 9a49ce87af..b491a2c8be 100644 --- a/loopx/control_plane/goals/deletion_service.py +++ b/loopx/control_plane/goals/deletion_service.py @@ -56,6 +56,7 @@ _route_matches_locked_paths, _source_basis, _state_fingerprint, + deletion_readback as deletion_readback, ) from .deletion_recovery import ( RecoveryRecord as RecoveryRecord, diff --git a/tests/control_plane/test_deletion_service_contract.py b/tests/control_plane/test_deletion_service_contract.py index 05f78d152e..cf4b3dff5b 100644 --- a/tests/control_plane/test_deletion_service_contract.py +++ b/tests/control_plane/test_deletion_service_contract.py @@ -8,6 +8,9 @@ import pytest +from loopx.chat import goal_lifecycle_actions +from loopx.chat_action_store import ChatActionStore +from loopx.chat_actions import ChatActionService from loopx.control_plane.goals import deletion_basis, deletion_recovery, deletion_service from loopx.control_plane.goals.activation import build_goal_activation from loopx.control_plane.goals.activation_service import ( @@ -38,6 +41,7 @@ _recovery_hooks, _recovery_receipt_path, delete_stopped_goal, + deletion_readback, ) from loopx.global_registry import sync_project_registry_to_global from loopx.history import load_registry @@ -342,3 +346,70 @@ def test_delete_stopped_goal_missing_stale_lock_failure_and_replay_contract( ) assert blocked["ok"] is False assert blocked["error_kind"] == "goal_source_lock_unavailable" + + +def test_deletion_readback_helper_and_chat_caller_fail_closed( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + assert deletion_service.deletion_readback is deletion_readback + assert deletion_readback({}) is None + assert deletion_readback({"readback": "not-a-mapping"}) is None + assert deletion_readback( + { + "readback": { + "source_missing": True, + "global_missing": True, + "verified": True, + } + } + ) == { + "source_missing": True, + "global_missing": True, + "verified": True, + } + + _source_registry, global_registry = _stopped_connected_registries(tmp_path) + service = ChatActionService( + store=ChatActionStore(tmp_path / "actions"), + registry_path=global_registry, + ) + proposal = service.preview( + { + "action_kind": "goal.lifecycle", + "summary": "Delete stopped contract Goal", + "normalized_parameters": { + "goal_id": "goal-one", + "operation": "delete", + "reason": "Contract test", + }, + "context": {"kind": "goal_directory"}, + "idempotency_key": "contract-delete-readback-missing", + } + ) + + def delete_without_readback( + *, + registry_path: Path, + goal_id: str, + execute: bool = False, + expected_state_fingerprint: str | None = None, + expected_source_basis: PayloadView | None = None, + ) -> dict[str, object]: + if execute: + return {"ok": True} + return delete_stopped_goal( + registry_path=registry_path, + goal_id=goal_id, + execute=False, + expected_state_fingerprint=expected_state_fingerprint, + expected_source_basis=expected_source_basis, + ) + + monkeypatch.setattr( + goal_lifecycle_actions, + "delete_stopped_goal", + delete_without_readback, + ) + with pytest.raises(ValueError, match="Goal deletion did not verify"): + service.apply(str(proposal["proposal_id"]))