diff --git a/CMakeLists.txt b/CMakeLists.txt index a5f66b5..00f89c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -174,6 +174,9 @@ if(PROTOCYTE_INSTALL) "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteSourceDependency.cmake" "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteGenerate.cmake" "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteOutputCoordinator.py" + "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteOwnershipIndex.py" + "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocytePathObservation.py" + "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteObservationCommit.py" "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteResetOutputDirectory.cmake" "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteFunctions.cmake" "${CMAKE_CURRENT_LIST_DIR}/cmake/ProtocyteProcess.cmake" diff --git a/cmake/ProtocyteObservationCommit.py b/cmake/ProtocyteObservationCommit.py new file mode 100644 index 0000000..ef8893f --- /dev/null +++ b/cmake/ProtocyteObservationCommit.py @@ -0,0 +1,1331 @@ +"""Transient native read-set commit; never standalone mutation authority. + +Positive objects use root-anchored short opens and exact ID/version witnesses. +Only volume roots retain handles; foreign build directories are not pinned. +Negative namespace observations are refreshed at every comparison and commit. +The coordinator decides authority only after seal and complete handle release; +no observations may cross into reconciliation or publication mutations. +""" + +from __future__ import annotations + +import ctypes +import contextlib +import concurrent.futures +import json +import os +import struct +import threading +from collections import deque +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any, Iterable, Mapping + + +class CommitUnavailable(RuntimeError): + pass + + +class CapabilityUnavailable(CommitUnavailable): + pass + + +class ObservationChanged(RuntimeError): + pass + + +class ProbeCleanupFailed(RuntimeError): + """Native work or handle cleanup failed; fallback must not authorize mutation.""" + + +class ProbeSession: + """Bounded independent comparisons; no query can outlive close, even on error. + + The admission gate also covers a task queued by a submit call that raises + before returning its Future. Shutdown closes admission first, then joins + the executor and independently drains all admitted native work. + """ + + BATCH_SIZE = 32 + + def __init__(self, compare, *, workers: int = 4) -> None: + if type(workers) is not int or not 1 <= workers <= 4: + raise CapabilityUnavailable("unsupported probe worker bound") + self.workers = workers + self._owner = threading.get_ident() + self._compare = compare + self._condition = threading.Condition() + self._accepting = True + self._native_retired = False + self._finished = False + self._close_error: BaseException | None = None + self._active = self._peak = 0 + self._started = self._completed = self._comparisons = 0 + self._submitted = self._peak_pending = 0 + self._threads: set[int] = set() + self._futures: set[Any] = set() + self._executor = concurrent.futures.ThreadPoolExecutor( + max_workers=workers, thread_name_prefix="protocyte-probes" + ) + + def _run(self, batch): + admitted = False + completed = 0 + result = [] + try: + with self._condition: + if not self._accepting: + raise ObservationChanged("probe work admitted after retirement") + self._active += 1 + admitted = True + # Bookkeeping can allocate and raise. It belongs inside the + # same retirement finally as the native comparison itself. + self._peak = max(self._peak, self._active) + self._started += 1 + self._threads.add(threading.get_ident()) + for reservation, prepared in batch: + if self._compare(prepared): + result.append(reservation) + completed += 1 + return result + finally: + if admitted: + with self._condition: + # Retire first: even a later accounting failure cannot + # leave close() waiting for a batch that already exited. + self._active -= 1 + self._condition.notify_all() + self._comparisons += completed + self._completed += 1 + + def compare(self, prepared): + self._require_owner() + with self._condition: + if not self._accepting: + raise ObservationChanged("probe session used after retirement") + rows = iter(prepared) + pending = deque() + result = [] + + def submit() -> bool: + batch = [] + for _ in range(self.BATCH_SIZE): + try: + batch.append(next(rows)) + except StopIteration: + break + if not batch: + return False + future = self._executor.submit(self._run, tuple(batch)) + self._futures.add(future) + pending.append(future) + self._submitted += 1 + self._peak_pending = max(self._peak_pending, len(pending)) + return True + + try: + for _ in range(self.workers * 2): + if not submit(): + break + while pending: + future = pending.popleft() + result.extend(future.result()) + self._futures.remove(future) + submit() + return result + except BaseException: + # This finishes every admitted query before the exception can + # reach the read set's handle-release/fallback boundary. + self.close() + raise + + def close(self) -> None: + self._require_owner() + if not self._finished: + # Close admission and drain *before* touching the executor. Catch + # interruption at lock acquisition as well as inside wait(). This + # monotonic fence is independently checked before root release. + while True: + try: + with self._condition: + self._accepting = False + if not self._active: + self._native_retired = True + break + # A worker may fail while notifying its retirement. + # Recheck the fence even if that notification is lost. + self._condition.wait(timeout=0.1) + except BaseException as error: + if self._close_error is None: + self._close_error = error + for future in self._futures: + try: + future.cancel() + except BaseException as error: + if self._close_error is None: + self._close_error = error + try: + self._executor.shutdown(wait=True, cancel_futures=True) + except BaseException as error: + if self._close_error is None: + self._close_error = error + self._futures.clear() + self._compare = None + self._finished = True + if self._close_error is not None: + if isinstance(self._close_error, Exception): + raise ProbeCleanupFailed( + "probe worker retirement failed" + ) from self._close_error + raise self._close_error + + def _require_owner(self) -> None: + if threading.get_ident() != self._owner: + raise ObservationChanged("probe session control used by a worker") + + @property + def native_retired(self) -> bool: + return self._native_retired + + def metrics(self) -> dict[str, Any]: + with self._condition: + return { + "commit_probe_state": "failed" + if self._close_error is not None + else "closed" + if self._finished + else "active", + "commit_probe_workers": self.workers, + "commit_probe_native_retired": self._native_retired, + "commit_probe_threads": len(self._threads), + "commit_probe_active": self._active, + "commit_probe_peak_active": self._peak, + "commit_probe_pending": len(self._futures), + "commit_probe_peak_pending": self._peak_pending, + "commit_probe_batches_submitted": self._submitted, + "commit_probe_batches_started": self._started, + "commit_probe_batches_finished": self._completed, + "commit_probe_comparisons": self._comparisons, + } + + +CLOSE_REASON = 0x80000000 + + +@dataclass(frozen=True) +class JournalRecord: + usn: int + file_id: int + reason: int + + +def parse_journal_page(data: bytes) -> tuple[int, tuple[JournalRecord, ...]]: + """Decode headers only; never retain names or unrelated filesystem paths.""" + if len(data) < 8: + raise CommitUnavailable("short journal cursor") + cursor = struct.unpack_from(" len(data): + raise CommitUnavailable("invalid journal record length") + width = 8 if major == 2 else 16 + file_id = int.from_bytes(data[offset + 8 : offset + 8 + width], "little") + usn_offset = offset + (24 if major == 2 else 40) + usn = struct.unpack_from("= cursor + or name_length % 2 + or ( + name_length + and ( + name_offset < minimum + or name_offset % 2 + or name_offset + name_length > length + ) + ) + ): + raise CommitUnavailable("invalid journal record fields") + records.append(JournalRecord(usn, file_id, reason)) + previous = usn + offset += length + return cursor, tuple(records) + + +def verify_witnesses( + expected: Mapping[int, int], records: Iterable[JournalRecord] +) -> None: + """Require positive evidence for every requested USN; absence never succeeds.""" + found: set[int] = set() + for record in records: + if record.usn not in expected: + continue + if record.usn in found or record.file_id != expected[record.usn]: + raise CommitUnavailable("duplicate or misbound close witness") + if record.reason != CLOSE_REASON: + raise ObservationChanged("close witness contains accumulated changes") + found.add(record.usn) + if found != set(expected): + raise CommitUnavailable("incomplete close witnesses") + + +@dataclass +class _Guard: + handle: Any + volume: int + file_id: int + start_usn: int + is_directory: bool + request: Any = None + + +@dataclass(frozen=True) +class _View: + path: Path + facts: Any + guard: _Guard + missing: tuple[str, ...] = () + probe: Any = None + relative: str = "" + + +@dataclass +class _Volume: + handle: Any + epoch: int + first: int + + +class _FrozenComparisons: + """Workers see prepared immutable views, never the mutable observation maps.""" + + def __init__(self, scope, workers: int) -> None: + self._scope = scope + self._views = MappingProxyType(dict(scope._views)) + self._closed = False + self.probe_session = ProbeSession(self._compare, workers=workers) + + def _get(self, path: Path) -> _View: + if self._closed: + raise ObservationChanged("frozen comparisons used after retirement") + self._scope._require_owner() + if self._scope._state != "comparing": + raise ObservationChanged("comparisons used outside their phase") + view = self._views.get(str(path)) + if view is None: + raise CommitUnavailable("comparison path was not observed before freezing") + if not view.missing and not view.guard.is_directory: + raise ObservationChanged("non-directory comparison endpoint") + return view + + def is_stable(self, path: Path) -> bool: + return not self._get(path).missing + + def facts(self, path: Path): + return self._get(path).facts + + def prepare_overlap(self, first: Path, second: Path): + return self._get(first), self._get(second) + + def _compare(self, prepared) -> bool: + if self._closed or self._scope._state != "comparing": + raise ObservationChanged("prepared comparison used after retirement") + return self._scope._overlaps_views(*prepared) + + def close(self) -> None: + try: + self.probe_session.close() + finally: + if not self.probe_session.native_retired: + # Preserve views and root bindings if an interruption happens + # before close() can enter its draining loop. Scope cleanup can + # retry, but must never release handles on an unproved fence. + raise ProbeCleanupFailed("native probe retirement is unproved") + self._closed = True + self._views = MappingProxyType({}) + self._scope = None + + +class WindowsObservationCommit: + """One bounded read set; instances and facts are never shared across phases.""" + + MAX_OBJECTS = 32768 + MAX_JOURNAL_BYTES = 64 * 1024 * 1024 + MAX_RECORD_BYTES = 16 * 1024 * 1024 + + def __init__(self, native: Any, model: Any) -> None: + # Keep old coordinators safe too: they predate the caller-side version + # checks and can import an in-progress or mixed helper installation. + contracts = ( + (globals().get("COMMIT_CONTRACT_VERSION"), 2), + (getattr(native, "PATH_CONTRACT_VERSION", None), 1), + (getattr(model, "OWNERSHIP_CONTRACT_VERSION", None), 1), + ) + if any(type(value) is not int or value != expected for value, expected in contracts): + raise CapabilityUnavailable("incomplete observation helper installation") + if os.name != "nt": + raise CapabilityUnavailable("commit observations require Windows") + self.native, self.model = native, model + self.reader = native.FreshPathObserver() + self.w = self.reader._w + self._state = "active" + self._owner = threading.get_ident() + self._negative_lock = threading.Lock() + self._comparison_reader: _FrozenComparisons | None = None + self._objects: dict[tuple[int, int], _Guard] = {} + self._volumes: dict[int, _Volume] = {} + self._roots: dict[str, _View] = {} + self._views: dict[str, _View] = {} + self._bindings: list[tuple[_Guard, str, tuple[int, int] | None, Any]] = [] + self._inventories: list[ + tuple[_Guard, tuple[str, ...], frozenset[str] | None] + ] = [] + self._cleanup_error: BaseException | None = None + self._counts = { + name: 0 + for name in ( + "commit_open_calls", + "commit_info_calls", + "commit_negative_probes", + "commit_close_posts", + "commit_version_reads", + "commit_epoch_queries", + "commit_journal_reads", + "commit_journal_bytes", + "commit_witnesses", + "commit_records_read", + "commit_binding_checks", + "commit_record_read_calls", + "commit_record_seek_calls", + "commit_directory_enumerations", + "commit_full_inventory_scans", + "commit_worker_context_checks", + ) + } + + class FileId(ctypes.Structure): + _fields_ = [("Volume", ctypes.c_ulonglong), ("Id", ctypes.c_ubyte * 16)] + + class Basic(ctypes.Structure): + _fields_ = [("Times", ctypes.c_longlong * 4), ("Attributes", self.w.ULONG)] + + self._id_type, self._basic_type = FileId, Basic + self._control = self.reader._kernel.DeviceIoControl + self._control.argtypes = ( + self.w.HANDLE, + self.w.DWORD, + self.w.LPVOID, + self.w.DWORD, + self.w.LPVOID, + self.w.DWORD, + ctypes.POINTER(self.w.DWORD), + self.w.LPVOID, + ) + self._control.restype = self.w.BOOL + self._query = self.reader._nt.NtQueryAttributesFile + self._query.argtypes = ( + ctypes.POINTER(self.reader._attributes), + ctypes.POINTER(Basic), + ) + self._query.restype = self.w.LONG + self._read = self.reader._kernel.ReadFile + self._read.argtypes = ( + self.w.HANDLE, + self.w.LPVOID, + self.w.DWORD, + ctypes.POINTER(self.w.DWORD), + self.w.LPVOID, + ) + self._read.restype = self.w.BOOL + self._seek = self.reader._kernel.SetFilePointerEx + self._seek.argtypes = ( + self.w.HANDLE, + ctypes.c_longlong, + ctypes.POINTER(ctypes.c_longlong), + self.w.DWORD, + ) + self._seek.restype = self.w.BOOL + self._fs_info = self.reader._kernel.GetVolumeInformationByHandleW + self._fs_info.argtypes = ( + self.w.HANDLE, + self.w.LPWSTR, + self.w.DWORD, + ctypes.POINTER(self.w.DWORD), + ctypes.POINTER(self.w.DWORD), + ctypes.POINTER(self.w.DWORD), + self.w.LPWSTR, + self.w.DWORD, + ) + self._fs_info.restype = self.w.BOOL + self._check_worker_context() + + def _check_worker_context(self) -> None: + self._counts["commit_worker_context_checks"] += 1 + if ctypes.sizeof(ctypes.c_void_p) != 8: + raise CapabilityUnavailable( + "parallel probes require a native 64-bit process" + ) + kernel = self.reader._kernel + current_process = kernel.GetCurrentProcess + current_process.argtypes = () + current_process.restype = self.w.HANDLE + machine = getattr(kernel, "IsWow64Process2", None) + if machine is None: + raise CapabilityUnavailable("native process context cannot be established") + machine.argtypes = ( + self.w.HANDLE, + ctypes.POINTER(self.w.WORD), + ctypes.POINTER(self.w.WORD), + ) + machine.restype = self.w.BOOL + process_machine, native_machine = self.w.WORD(), self.w.WORD() + if ( + not machine( + current_process(), + ctypes.byref(process_machine), + ctypes.byref(native_machine), + ) + or process_machine.value + or native_machine.value not in (0x8664, 0xAA64) + ): + raise CapabilityUnavailable( + "emulated filesystem context needs reference validation" + ) + current_thread = kernel.GetCurrentThread + current_thread.argtypes = () + current_thread.restype = self.w.HANDLE + open_token = ctypes.WinDLL("advapi32", use_last_error=True).OpenThreadToken + open_token.argtypes = ( + self.w.HANDLE, + self.w.DWORD, + self.w.BOOL, + ctypes.POINTER(self.w.HANDLE), + ) + open_token.restype = self.w.BOOL + token = self.w.HANDLE() + if open_token(current_thread(), 0x8, True, ctypes.byref(token)): + if not self.reader._close(token): + raise ProbeCleanupFailed("thread token handle could not be retired") + raise CapabilityUnavailable( + "impersonating caller needs reference validation" + ) + if ctypes.get_last_error() != 1008: # ERROR_NO_TOKEN is the required result. + raise CapabilityUnavailable("ordinary thread context cannot be established") + + def _active(self) -> None: + self._require_owner() + if self._state != "active": + raise ObservationChanged("read set used outside its observation phase") + + def _require_owner(self) -> None: + if threading.get_ident() != self._owner: + raise ObservationChanged("mutable observations used by a worker") + + @contextlib.contextmanager + def comparisons(self, *, workers: int = 4): + self._active() + if self._comparison_reader is not None: + raise ObservationChanged("read set comparisons already retired") + self._check_worker_context() + self._state = "comparing" + try: + reader = _FrozenComparisons(self, workers) + except BaseException: + self._state = "active" + raise + self._comparison_reader = reader + try: + yield reader + finally: + try: + reader.close() + finally: + if reader.probe_session.native_retired: + self._state = "observed" + + def _io( + self, handle: Any, code: int, request: bytes | None, capacity: int + ) -> bytes: + incoming = ctypes.create_string_buffer(request) if request is not None else None + output = ctypes.create_string_buffer(capacity) + size = self.w.DWORD() + if not self._control( + handle, + code, + incoming, + len(request) if request else 0, + output, + capacity, + ctypes.byref(size), + None, + ): + raise CapabilityUnavailable( + f"journal operation unavailable ({ctypes.get_last_error()})" + ) + if size.value > capacity: + raise CommitUnavailable("oversized journal reply") + return output.raw[: size.value] + + def _epoch(self, handle: Any) -> tuple[int, int, int]: + self._counts["commit_epoch_queries"] += 1 + data = self._io(handle, 0x900F4, None, 128) + if len(data) < 56: + raise CommitUnavailable("short journal information") + epoch, first, next_usn, lowest = struct.unpack_from(" next_usn + or lowest > next_usn + ): + raise CommitUnavailable("invalid journal information") + return epoch, max(first, lowest), next_usn + + def _post_close(self, handle: Any) -> int: + self._counts["commit_close_posts"] += 1 + data = self._io(handle, 0x900EF, None, 8) + if len(data) != 8: + raise CommitUnavailable("short close marker") + usn = struct.unpack(" int: + self._counts["commit_version_reads"] += 1 + data = self._io(handle, 0x900EB, struct.pack(" len(data): + raise CommitUnavailable("unsupported file version") + return struct.unpack_from(" tuple[int, int]: + self._counts["commit_info_calls"] += 1 + value = self._id_type() + if not self.reader._info(handle, 18, ctypes.byref(value), ctypes.sizeof(value)): + raise CapabilityUnavailable("128-bit object identity unavailable") + key = value.Volume, int.from_bytes(bytes(value.Id), "little") + if not key[0] or not key[1]: + raise CommitUnavailable("empty object identity") + return key + + def _release(self, handle: Any) -> None: + try: + closed = self.reader._close(handle) + except BaseException as error: + self._cleanup_error = error + if isinstance(error, Exception): + raise ProbeCleanupFailed("native handle release failed") from error + raise + if not closed: + error = ProbeCleanupFailed("native handle release failed") + self._cleanup_error = error + raise error + self.reader.handles_closed += 1 + + def _adopt( + self, handle: Any, *, request: Any = None, retain_root: bool = False + ) -> tuple[_Guard, Path]: + retained = False + try: + key = self._identity(handle) + known = self._objects.get(key) + if known is None: + if len(self._objects) >= self.MAX_OBJECTS: + raise CommitUnavailable("read set object budget exceeded") + if key[0] not in self._volumes: + if not retain_root: + raise CommitUnavailable( + "relative lookup crossed a volume boundary" + ) + filesystem = ctypes.create_unicode_buffer(32) + self._counts["commit_info_calls"] += 1 + if ( + not self._fs_info( + handle, + None, + 0, + None, + None, + None, + filesystem, + len(filesystem), + ) + or filesystem.value != "NTFS" + ): + raise CapabilityUnavailable( + "only local NTFS supports this prototype" + ) + epoch, first, _ = self._epoch(handle) + self._volumes[key[0]] = _Volume(handle, epoch, first) + start = self._post_close(handle) + # Facts are collected only after the initial close marker. + tag = self.reader._tag() + self._counts["commit_info_calls"] += 1 + if not self.reader._info( + handle, 9, ctypes.byref(tag), ctypes.sizeof(tag) + ): + raise CommitUnavailable("attribute information unavailable") + if tag.Attributes & 0x400: + raise ObservationChanged("observed reparse point") + is_directory = bool(tag.Attributes & 0x10) + if is_directory: + # This is a capability gate, not a versioned fact. NTFS can + # change this flag without changing the file USN. Reuse is + # restricted to exact canonical names below, whose binding + # does not depend on case-insensitive alias lookup. + case = self.w.DWORD() + self._counts["commit_info_calls"] += 1 + if ( + not self.reader._info( + handle, 23, ctypes.byref(case), ctypes.sizeof(case) + ) + or case.value + ): + raise CapabilityUnavailable( + "case-sensitive directory needs reference validation" + ) + known = _Guard( + handle if retain_root else None, + key[0], + key[1], + start, + is_directory, + request, + ) + self._objects[key] = known + retained = retain_root + canonical = self.reader._describe(handle, leaf_may_be_file=True) + return known, canonical + finally: + if not retained: + self._release(handle) + + def _request(self, parent: _View, component: str): + if ( + not component + or component in (".", "..") + or any(c in component for c in ("\\", "/", ":", "\x00")) + ): + raise CommitUnavailable("unsupported relative component") + relative = parent.relative + ("\\" if parent.relative else "") + component + length = len(relative.encode("utf-16-le")) + if length > 65532: + raise CommitUnavailable("relative component too long") + storage = ctypes.create_unicode_buffer(relative) + name = self.reader._unicode( + length, length + 2, ctypes.cast(storage, self.w.LPWSTR) + ) + attributes = self.reader._attributes( + ctypes.sizeof(self.reader._attributes), + self._volumes[parent.guard.volume].handle, + ctypes.pointer(name), + 0x1040, + None, + None, + ) + return storage, name, attributes + + def _open_child(self, request: Any): + self._counts["commit_open_calls"] += 1 + handle, status = self.w.HANDLE(), self.reader._status() + result = self.reader._invoke_open( + handle, + 0x100081, + ctypes.byref(request[2]), + ctypes.byref(status), + None, + 0, + 7, + 1, + 0x20, + None, + 0, + ) + code = result & 0xFFFFFFFF + if code in (0xC0000034, 0xC000003A): + return None + if result < 0: + raise ObservationChanged( + f"relative open changed or unavailable ({code:08x})" + ) + if not handle.value: + raise CommitUnavailable("relative open returned no handle") + self.reader.handles_opened += 1 + if code: + self._release(handle) + raise CommitUnavailable("unexpected relative-open status") + return handle + + def _probe_absence(self, request: Any) -> None: + if self._state not in ("active", "comparing", "sealing"): + raise ObservationChanged("negative probe used after its phase") + with self._negative_lock: + self._counts["commit_negative_probes"] += 1 + value = self._basic_type() + code = self._query(ctypes.byref(request[2]), ctypes.byref(value)) & 0xFFFFFFFF + if code not in (0xC0000034, 0xC000003A): + raise ObservationChanged("missing component changed during comparison") + + def _root(self, path: Path) -> _View: + self.reader._native_name(path) + root = Path(path.anchor) + key = str(root).casefold() + if key not in self._roots: + self._counts["commit_open_calls"] += 1 + handle = self.reader._open_existing(root) + if handle is None: + raise CommitUnavailable("drive root unavailable") + guard, canonical = self._adopt(handle, retain_root=True) + if canonical != root: + raise CommitUnavailable("drive aliases need reference validation") + if any(view.guard.volume == guard.volume for view in self._roots.values()): + # A serial is not a license to route a second drive's relative + # lookups through the first root handle (for example, cloned + # volumes or an additional DOS binding). Refuse ambiguity. + raise CapabilityUnavailable( + "duplicate volume binding needs reference validation" + ) + location = (guard.volume, guard.file_id, ()) + view = _View( + canonical, + self.model.DirectoryObservation( + str(canonical).replace("\\", "/").casefold().rstrip("/"), + location, + (location,), + ), + guard, + ) + self._roots[key] = view + self._views[str(root)] = view + return self._roots[key] + + def _view(self, path: Path, *, leaf_may_be_file: bool = False) -> _View: + self._active() + key = str(path) + known = self._views.get(key) + if known is not None: + if known.missing: + self._probe_absence(known.probe) + elif not known.guard.is_directory and not leaf_may_be_file: + raise ObservationChanged("non-directory path component") + return known + path = Path(os.path.normpath(path)) + self.reader._native_name(path) + key = str(path) + parent = self._root(path) + parts = path.parts[1:] + input_path = Path(path.anchor) + for number, component in enumerate(parts): + input_path /= component + cached = self._views.get(str(input_path)) + if cached is not None and not cached.missing: + parent = cached + if number < len(parts) - 1 and not parent.guard.is_directory: + raise ObservationChanged("non-directory ancestor") + continue + if not parent.guard.is_directory: + raise ObservationChanged("non-directory ancestor") + request = self._request(parent, component) + handle = self._open_child(request) + if handle is None: + missing = tuple(parts[number:]) + suffix = tuple(part.casefold() for part in missing) + location = (parent.guard.volume, parent.guard.file_id, suffix) + ancestors = ( + tuple( + (parent.guard.volume, parent.guard.file_id, suffix[:n]) + for n in range(len(suffix), 0, -1) + ) + + parent.facts.ancestors + ) + canonical = parent.path.joinpath(*missing) + facts = self.model.DirectoryObservation( + str(canonical).replace("\\", "/").casefold().rstrip("/"), + location, + ancestors, + ) + view = _View(canonical, facts, parent.guard, missing, request) + self._views[key] = view + self._bindings.append((parent.guard, component, None, request)) + return view + guard, canonical = self._adopt(handle, request=request) + if str(canonical) != str(input_path): + # A case-mode ABA need not post a USN change. In particular, a + # differently cased alias can disappear without changing its + # original object's ID or USN. Exact spellings still identify + # that object in either case mode; all aliases use reference. + raise CapabilityUnavailable( + "noncanonical spelling needs reference validation" + ) + self._bindings.append( + (parent.guard, component, (guard.volume, guard.file_id), request) + ) + location = (guard.volume, guard.file_id, ()) + facts = self.model.DirectoryObservation( + str(canonical).replace("\\", "/").casefold().rstrip("/"), + location, + (location, *parent.facts.ancestors), + ) + relative = parent.relative + ("\\" if parent.relative else "") + component + parent = _View(canonical, facts, guard, relative=relative) + self._views[str(input_path)] = parent + self._views.setdefault(str(canonical), parent) + if not parent.guard.is_directory and not leaf_may_be_file: + raise ObservationChanged("non-directory path component") + return parent + + def project(self, path: Path, *, leaf_may_be_file: bool = False) -> Path: + return self._view(path, leaf_may_be_file=leaf_may_be_file).path + + def facts(self, path: Path): + return self._view(path).facts + + def _descriptor(self, path: Path) -> _View: + self._active() + view = self._views.get(str(path)) + if view is None: + return self._view(path) + if not view.missing and not view.guard.is_directory: + raise ObservationChanged("non-directory path component") + return view + + def is_stable(self, path: Path) -> bool: + # A conservative classification hint, never a negative lookup result. + # Every actual comparison below refreshes its negative inputs. + return not self._descriptor(path).missing + + def path_key(self, path: Path) -> str: + import hashlib + + value = str(self.project(path)).replace("\\", "/").casefold() + return hashlib.sha256(value.encode()).hexdigest() + + def same_path(self, first: Path, second: Path) -> bool: + self._active() + if first == second: + return True + left, right = self._view(first), self._view(second) + return ( + not left.missing + and not right.missing + and left.facts.location == right.facts.location + ) + + def overlaps(self, first: Path, second: Path) -> bool: + left, right = self._descriptor(first), self._descriptor(second) + return self._overlaps_views(left, right) + + def _overlaps_views(self, left: _View, right: _View) -> bool: + if self._state not in ("active", "comparing"): + raise ObservationChanged("comparison used after its phase") + + def refresh(view: _View) -> None: + if view.missing: + self._probe_absence(view.probe) + + # Canonical positive prefixes are provisional under their version fence. + # Native negative checks combine projection and endpoint observation; + # there is no separate stale projection reused by the physical check. + refresh(left) + refresh(right) + if ( + left.facts.portable == right.facts.portable + or left.facts.portable.startswith(right.facts.portable + "/") + or right.facts.portable.startswith(left.facts.portable + "/") + ): + return True + if left.facts.location in right.facts.ancestors: + return True + refresh(right) + refresh(left) + return right.facts.location in left.facts.ancestors + + def contains(self, parent: Path, child: Path) -> bool: + first, second = self._view(parent), self._view(child, leaf_may_be_file=True) + return ( + second.facts.portable == first.facts.portable + or second.facts.portable.startswith(first.facts.portable + "/") + ) + + def physically_contains(self, parent: Path, child: Path) -> bool: + return self._view(parent).facts.location in self._view(child).facts.ancestors + + @contextlib.contextmanager + def _lease(self, guard: _Guard): + if guard.handle is not None: + yield guard.handle + return + handle = self._open_child(guard.request) + if handle is None: + raise ObservationChanged("observed object disappeared") + try: + if self._identity(handle) != (guard.volume, guard.file_id): + raise ObservationChanged("observed object identity changed") + yield handle + finally: + self._release(handle) + + def _list_handle(self, guard: _Guard) -> tuple[str, ...]: + with self._lease(guard) as handle: + return self._list_open_directory(handle) + + def _list_open_directory(self, handle: Any) -> tuple[str, ...]: + names = [] + restart = True + while True: + buffer = ctypes.create_string_buffer(65536) + self._counts["commit_info_calls"] += 1 + self._counts["commit_directory_enumerations"] += 1 + if not self.reader._info( + handle, 11 if restart else 10, buffer, len(buffer) + ): + error = ctypes.get_last_error() + if error == 18: + break + raise CommitUnavailable(f"directory enumeration unavailable ({error})") + restart = False + data = buffer.raw + offset = 0 + while True: + if offset + 104 > len(buffer): + raise CommitUnavailable("invalid directory enumeration") + (next_offset,) = struct.unpack_from(" len(buffer): + raise CommitUnavailable("invalid directory name") + name = data[offset + 104 : offset + 104 + length].decode("utf-16-le") + if name not in (".", ".."): + names.append(name) + if not next_offset: + break + if next_offset < 104 or next_offset % 8: + raise CommitUnavailable("invalid directory enumeration offset") + offset += next_offset + return tuple(sorted(names)) + + def list_names( + self, path: Path, *, relevant: frozenset[str] | None = None + ) -> tuple[str, ...]: + view = self._view(path) + if view.missing or not view.guard.is_directory: + raise ObservationChanged("registry directory disappeared") + names = self._list_handle(view.guard) + if relevant is None: + self._counts["commit_full_inventory_scans"] += 1 + observed = ( + names + if relevant is None + else tuple(name for name in names if name in relevant) + ) + self._inventories.append((view.guard, observed, relevant)) + return names + + def read_json(self, path: Path, description: str) -> dict[str, Any]: + view = self._view(path, leaf_may_be_file=True) + if view.missing or view.guard.is_directory: + raise ObservationChanged("registry record disappeared or changed type") + if view.path != path: + raise ObservationChanged("registry record path changed canonical spelling") + with self._lease(view.guard) as handle: + if self._version(handle) != view.guard.start_usn: + raise ObservationChanged("registry record changed before reading") + data = self._read_open_record(handle) + value = json.loads(data) + canonical = ( + json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n" + ).encode() + if not isinstance(value, dict) or canonical != data: + raise ObservationChanged(f"{description} is not canonical JSON") + self._counts["commit_records_read"] += 1 + return value + + def _read_open_record(self, handle: Any) -> bytes: + self._counts["commit_record_seek_calls"] += 1 + if not self._seek(handle, 0, None, 0): + raise CommitUnavailable("record seek unavailable") + parts = [] + total = 0 + while True: + buffer = ctypes.create_string_buffer(65536) + size = self.w.DWORD() + self._counts["commit_record_read_calls"] += 1 + if not self._read(handle, buffer, len(buffer), ctypes.byref(size), None): + raise CommitUnavailable("record read unavailable") + if not size.value: + break + total += size.value + if total > self.MAX_RECORD_BYTES: + raise CommitUnavailable("record exceeds observation budget") + parts.append(buffer.raw[: size.value]) + return b"".join(parts) + + def record_exists(self, path: Path) -> bool: + return not self._view(path, leaf_may_be_file=True).missing + + def _collect_witnesses(self, volume: _Volume, expected: dict[int, int]) -> None: + if not expected: + return + epoch, first, next_usn = self._epoch(volume.handle) + if epoch != volume.epoch or first > min(expected) or next_usn <= max(expected): + raise ObservationChanged("journal epoch or witness range changed") + cursor = min(expected) + records = [] + remaining = set(expected) + consumed = 0 + while remaining: + request = struct.pack( + " self.MAX_JOURNAL_BYTES: + raise CommitUnavailable("journal witness budget exceeded") + following, batch = parse_journal_page(data) + if following <= cursor: + raise CommitUnavailable("journal witness cursor made no progress") + for record in batch: + if record.usn < cursor: + raise CommitUnavailable("journal witness cursor moved backward") + if record.usn in expected: + records.append(record) + remaining.discard(record.usn) + if following > max(expected) and remaining: + raise CommitUnavailable("journal omitted required witnesses") + cursor = following + verify_witnesses(expected, records) + epoch_after, _, next_after = self._epoch(volume.handle) + if epoch_after != epoch or next_after < next_usn: + raise ObservationChanged("journal changed while reading witnesses") + self._counts["commit_witnesses"] += len(expected) + + def seal(self) -> None: + self._require_owner() + if self._state not in ("active", "observed"): + raise ObservationChanged("read set sealed outside its phase") + if self._comparison_reader is not None: + probes = self._comparison_reader.probe_session.metrics() + if ( + probes["commit_probe_state"] != "closed" + or probes["commit_probe_active"] + or probes["commit_probe_pending"] + ): + raise ProbeCleanupFailed("probe workers were not retired before seal") + self._state = "sealing" + for guard, names, relevant in self._inventories: + current = self._list_handle(guard) + if relevant is None: + self._counts["commit_full_inventory_scans"] += 1 + current = ( + current + if relevant is None + else tuple(name for name in current if name in relevant) + ) + if current != names: + raise ObservationChanged("registry inventory changed") + for root, view in self._roots.items(): + self._counts["commit_open_calls"] += 1 + handle = self.reader._open_existing(Path(root)) + if handle is None: + raise ObservationChanged("drive binding disappeared") + try: + if self._identity(handle) != (view.guard.volume, view.guard.file_id): + raise ObservationChanged("drive binding changed") + finally: + self._release(handle) + expected: dict[int, dict[int, int]] = {volume: {} for volume in self._volumes} + certified: set[tuple[int, int]] = set() + + def certify(guard: _Guard, handle: Any) -> None: + key = guard.volume, guard.file_id + if key in certified: + return + if self._version(handle) != guard.start_usn: + raise ObservationChanged("observed object version changed") + witness = self._post_close(handle) + if witness <= guard.start_usn or witness in expected[guard.volume]: + raise CommitUnavailable("non-monotonic close witness") + expected[guard.volume][witness] = guard.file_id + certified.add(key) + + for parent, component, identity, request in self._bindings: + self._counts["commit_binding_checks"] += 1 + if identity is None: + self._probe_absence(request) + continue + handle = self._open_child(request) + if handle is None: + raise ObservationChanged("positive name binding disappeared") + try: + if self._identity(handle) != identity: + raise ObservationChanged("positive name binding changed") + certify(self._objects[identity], handle) + finally: + self._release(handle) + for guard in self._objects.values(): + if (guard.volume, guard.file_id) not in certified: + with self._lease(guard) as handle: + certify(guard, handle) + for volume, witnesses in expected.items(): + self._collect_witnesses(self._volumes[volume], witnesses) + self._state = "sealed" + + def close(self) -> None: + self._require_owner() + error = self._cleanup_error + if self._comparison_reader is not None: + try: + self._comparison_reader.close() + except BaseException as failure: + if error is None: + error = failure + if not self._comparison_reader.probe_session.native_retired: + raise ProbeCleanupFailed( + "root handles cannot close before native probe retirement" + ) from error + self._state = "closed" + for guard in reversed(tuple(self._objects.values())): + if guard.handle is None: + continue + # Never retry an uncertain close: the OS may already have consumed + # the value and reused it for an unrelated process/thread handle. + handle, guard.handle = guard.handle, None + try: + self._release(handle) + except BaseException as failure: + if error is None: + error = failure + self._objects.clear() + self._views.clear() + self._roots.clear() + self._bindings.clear() + self._inventories.clear() + self._volumes.clear() + try: + self.reader.close() + except BaseException as failure: + if error is None: + error = failure + if error is not None: + self._state = "failed" + self._cleanup_error = error + if isinstance(error, Exception) and not isinstance(error, ProbeCleanupFailed): + raise ProbeCleanupFailed("native observation cleanup failed") from error + raise error + + def metrics(self) -> dict[str, Any]: + probes = ( + {} + if self._comparison_reader is None + else self._comparison_reader.probe_session.metrics() + ) + return { + **self._counts, + **probes, + "commit_info_calls": self._counts["commit_info_calls"] + + self.reader.information_calls, + "commit_state": self._state, + "commit_cleanup_failed": self._cleanup_error is not None, + "commit_handles_opened": self.reader.handles_opened, + "commit_handles_closed": self.reader.handles_closed, + "commit_final_path_calls": self.reader.final_path_calls, + } + + +class ProvisionalOwnershipIndex: + """Index positives; compare every unstable endpoint with fresh negatives. + + No result is usable until the associated read set supplies all close + witnesses. This object and its observations do not cross that boundary. + """ + + def __init__(self, model: Any, filesystem: WindowsObservationCommit, entries): + self.model, self.filesystem = model, filesystem + self.entries = tuple(entries) + self.positive = model.OwnershipIndex( + reservation for reservation, _, stable in self.entries if stable + ) + self.negative = tuple( + (reservation, path) + for reservation, path, stable in self.entries + if not stable + ) + self.queries = 0 + self.fresh_comparisons = 0 + + def _overlapping(self, path: Path): + self.queries += 1 + if self.filesystem.is_stable(path): + yield from self.positive.overlapping(self.filesystem.facts(path)) + remaining = self.negative + else: + remaining = tuple( + (reservation, reserved) for reservation, reserved, _ in self.entries + ) + probes = getattr(self.filesystem, "probe_session", None) + if probes is not None: + prepared = tuple( + (reservation, self.filesystem.prepare_overlap(reserved, path)) + for reservation, reserved in remaining + ) + self.fresh_comparisons += len(prepared) + yield from probes.compare(prepared) + return + for reservation, reserved in remaining: + self.fresh_comparisons += 1 + if self.filesystem.overlaps(reserved, path): + yield reservation + + def conflict( + self, + *, + root: Path, + root_key: str, + build_id: str, + staging, + retiring_root_keys: set[str], + ): + for reservation in self._overlapping(root): + if reservation.kind == "root": + if reservation.root_key != root_key: + return "root-root" + else: + return "root-staging" + for target, path in staging: + for reservation in self._overlapping(path): + if reservation.kind == "root": + return "staging-root" + if target == reservation.target and ( + root_key == reservation.root_key + or ( + reservation.root_key in retiring_root_keys + and build_id == reservation.build_id + ) + ): + continue + return "staging-staging" + return None + + +# Publish only after the complete helper has loaded. A syntactically valid +# truncated install must not advertise its contract. This is not a disk format. +COMMIT_CONTRACT_VERSION = 2 diff --git a/cmake/ProtocyteOutputCoordinator.py b/cmake/ProtocyteOutputCoordinator.py index 25f1660..09ec670 100644 --- a/cmake/ProtocyteOutputCoordinator.py +++ b/cmake/ProtocyteOutputCoordinator.py @@ -20,6 +20,7 @@ import contextlib import ctypes import hashlib +import importlib.util import json import os import secrets @@ -31,14 +32,17 @@ import time from dataclasses import dataclass from pathlib import Path, PurePosixPath -from typing import Any, Mapping, NoReturn, Sequence +from typing import Any, Iterator, Mapping, NoReturn, Sequence PROTOCOL_VERSION = 1 +# Enable native validation after correctness and upgrade qualification. +# Every invocation still requires supported capabilities, verified witnesses, +# complete worker retirement, and successful native-handle cleanup. +_COMMITTED_INDEX_QUALIFIED = True PLAN_HEADER = "protocyte-output-plan-v1" GENERATED_SUFFIXES = (".protocyte.cpp", ".protocyte.hpp", "/runtime.hpp") - class CoordinatorError(RuntimeError): """A fail-closed coordinator error suitable for a CMake diagnostic.""" @@ -92,27 +96,6 @@ def _require_absolute(path: Path, description: str) -> Path: return Path(os.path.normpath(text)) -def _existing_chain(path: Path) -> list[Path]: - current = path - missing: list[Path] = [] - while not os.path.lexists(current): - parent = current.parent - if parent == current: - _fail(f"could not find an existing ancestor for {path}") - missing.append(current) - current = parent - chain: list[Path] = [] - cursor = current - while True: - chain.append(cursor) - parent = cursor.parent - if parent == cursor: - break - cursor = parent - chain.reverse() - return chain - - def project_path(path: Path, *, leaf_may_be_file: bool = False) -> Path: """Resolve existing components and append a normalized missing suffix. @@ -130,7 +113,10 @@ def project_path(path: Path, *, leaf_may_be_file: bool = False) -> Path: _fail(f"could not project filesystem path: {path}") suffix.append(existing.name) existing = existing.parent - for component in _existing_chain(existing): + # Construct the chain without another existence search. Every component + # is still freshly checked, and the separate stat/strict resolve below + # retries if the initially existing leaf has disappeared. + for component in (*reversed(existing.parents), existing): if _is_link(component): _fail(f"filesystem path contains a symbolic link or junction: {path}") try: @@ -231,15 +217,41 @@ def _physically_contains(parent: Path, child: Path) -> bool: def _projected_physically_contains(parent: Path, child: Path) -> bool: parent_key = _physical_location_key(parent) - current = child + return parent_key in _physical_ancestor_keys(child) + + +def _physical_ancestor_keys(path: Path) -> Iterator[tuple[int, int, tuple[str, ...]]]: + """Observe ancestry once, only for this directional comparison. + + Missing descendants share their nearest existing directory's identity plus + a normalized suffix. Existing ordinary directories use the device/inode + relation used by samefile, without its two additional following stat calls. + No observations survive the comparison, including negative observations. + """ + current = path + missing: list[str] = [] while True: - if _same_physical_path(parent, current) or parent_key == _physical_location_key( - current - ): - return True + try: + observed = current.lstat() + except FileNotFoundError: + missing.append(current.name.casefold()) + except OSError as error: + _fail(f"could not identify physical filesystem location {path}: {error}") + else: + if _stat_is_link(observed): + _fail(f"filesystem path contains a symbolic link or junction: {path}") + if not stat.S_ISDIR(observed.st_mode): + _fail(f"filesystem path has a non-directory ancestor: {current}") + suffix = tuple(reversed(missing)) + for length in range(len(suffix), 0, -1): + yield observed.st_dev, observed.st_ino, suffix[:length] + missing.clear() + yield observed.st_dev, observed.st_ino, () next_parent = current.parent if next_parent == current: - return False + if missing: + _fail(f"could not identify physical filesystem location: {path}") + return current = next_parent @@ -447,8 +459,11 @@ def visit(directory: Path) -> None: return paths -def _load_json(path: Path, description: str) -> dict[str, Any]: - expected = project_path(path, leaf_may_be_file=True) +def _load_json(path: Path, description: str, *, _filesystem: Any = None) -> dict[str, Any]: + if _filesystem is not None and hasattr(_filesystem, "read_json"): + return _filesystem.read_json(path, description) + project = project_path if _filesystem is None else _filesystem.project + expected = project(path, leaf_may_be_file=True) if expected != path or _is_link(path): _fail(f"{description} path is unsafe or was replaced: {path}") try: @@ -541,15 +556,14 @@ def __exit__(self, *_: object) -> None: class _ReconcileProgress: - """Bounded, path-free stderr progress, including while OS locks block. + """Bounded-frequency, path-free stderr progress while work or locks block. - Fast operations stay silent. Long operations emit at most twelve progress - lines and one completion/failure summary. Nothing is written to the claim + Fast operations stay silent. Long operations report throughout their lifetime + and emit one completion/failure summary. Nothing is written to the claim token stream on stdout. The reporter observes counters only, not the FS. """ INTERVAL_SECONDS = 5.0 - MAX_REPORTS = 12 def __init__(self, current: int, retired: int) -> None: self.current = current @@ -607,13 +621,8 @@ def _emit(self, phase: str) -> None: def _report(self) -> bool: with self._mutex: - if self._reports >= self.MAX_REPORTS: - return False self._reports += 1 - phase = self._phase - if self._reports == self.MAX_REPORTS: - phase += " (further progress suppressed until completion)" - self._emit(phase) + self._emit(self._phase) return True def _run(self) -> None: @@ -743,7 +752,9 @@ def read(cls, path: Path) -> Plan: ) @classmethod - def from_payload(cls, payload: Mapping[str, Any], source: Path) -> Plan: + def from_payload( + cls, payload: Mapping[str, Any], source: Path, *, _filesystem: Any = None + ) -> Plan: if ( set(payload) != { @@ -760,8 +771,10 @@ def from_payload(cls, payload: Mapping[str, Any], source: Path) -> Plan: or not isinstance(payload["targets"], list) ): _fail(f"configured output plan is malformed: {source}") - root = project_path(Path(str(payload["root"]))) - build_root = project_path(Path(str(payload["build_root"]))) + project = project_path if _filesystem is None else _filesystem.project + path_key = _path_key if _filesystem is None else _filesystem.path_key + root = project(Path(str(payload["root"]))) + build_root = project(Path(str(payload["build_root"]))) outputs: list[PlanOutput] = [] for value in payload["outputs"]: if ( @@ -788,7 +801,7 @@ def from_payload(cls, payload: Mapping[str, Any], source: Path) -> Plan: PlanTarget( identity, _validate_staging_path( - root, identity, Path(str(value["staging"])) + root, identity, Path(str(value["staging"])), _filesystem=_filesystem ), ) ) @@ -796,7 +809,7 @@ def from_payload(cls, payload: Mapping[str, Any], source: Path) -> Plan: plan = cls( root, build_root, - _path_key(build_root), + path_key(build_root), tuple(sorted(targets, key=lambda target: target.identity)), tuple(sorted(outputs, key=lambda output: (output.relative, output.target))), ) @@ -812,11 +825,13 @@ def staging_for_target(self, identity: str) -> Path: def _validate_staging_path( - root: Path | None, identity: str, path: Path + root: Path | None, identity: str, path: Path, *, _filesystem: Any = None ) -> Path: - path = project_path(_require_absolute(path, "generation staging directory")) + project = project_path if _filesystem is None else _filesystem.project + overlaps = _paths_overlap if _filesystem is None else _filesystem.overlaps + path = project(_require_absolute(path, "generation staging directory")) if root is not None: - expected = project_path( + expected = project( root.parent / f".protocyte-generation-staging-{identity}" ) if path != expected: @@ -824,7 +839,7 @@ def _validate_staging_path( "output plan target metadata contains an unexpected staging directory: " f"{path}" ) - if _paths_overlap(root, path): + if overlaps(root, path): _fail( "output plan generation staging overlaps its own output root: " f"{path} and {root}" @@ -877,9 +892,212 @@ def _generation_environment() -> dict[str, str]: return environment +_ownership_module: Any = None + + +def _load_ownership_index() -> Any: + global _ownership_module + if _ownership_module is None: + path = Path(__file__).with_name("ProtocyteOwnershipIndex.py") + name = f"{__name__}_ownership_index" + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail("experimental ownership index could not be loaded") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + # Loading an optional preview must not create __pycache__ in a + # source/installed prefix. Compile exactly the trusted sibling + # source; do not change process-global bytecode/import settings. + exec(compile(path.read_bytes(), os.fspath(path), "exec"), module.__dict__) + except BaseException: + sys.modules.pop(name, None) + raise + _ownership_module = module + return _ownership_module + + +class _SampledRegistryFilesystem: + """Read-only, non-authoritative samples for one experimental preview. + + Only the shadow preview may use these cached observations. They do not + survive its scope or replace any fresh reference/mutation-time checks. + """ + + def __init__(self, model: Any) -> None: + self._model = model + self._projected: dict[str, Path] = {} + self._facts: dict[str, Any] = {} + self._closed = False + self.projections = 0 + self.observations = 0 + + def close(self) -> None: + self._closed = True + self._projected.clear() + self._facts.clear() + + def project(self, path: Path, *, leaf_may_be_file: bool = False) -> Path: + if self._closed: + _fail("experimental filesystem sample used outside its preview") + if leaf_may_be_file: + # Registry record paths retain fresh, uncached observations even + # while the directory-only index preview samples geometry. + return project_path(path, leaf_may_be_file=True) + name = os.fspath(_require_absolute(path, "sampled directory")) + if name not in self._projected: + projected = project_path(path) + self.projections += 1 + self._projected[name] = projected + self._projected.setdefault(os.fspath(projected), projected) + return self._projected[name] + + def path_key(self, path: Path) -> str: + identity = os.fspath(self.project(path)).replace("\\", "/").casefold() + return _sha256_bytes(identity.encode("utf-8")) + + def facts(self, path: Path) -> Any: + projected = self.project(path) + name = os.fspath(projected) + if name not in self._facts: + ancestors = tuple(_physical_ancestor_keys(projected)) + location = _physical_location_key(projected) + if location not in ancestors: + _fail("experimental sample observed a changed physical identity") + self._facts[name] = self._model.DirectoryObservation( + name.replace("\\", "/").casefold().rstrip("/"), + location, + ancestors, + ) + self.observations += 1 + return self._facts[name] + + def overlaps(self, first: Path, second: Path) -> bool: + return bool(self.facts(first).overlaps(self.facts(second))) + + def contains(self, parent: Path, child: Path) -> bool: + return _projected_contains(self.project(parent), self.project(child)) + + def physically_contains(self, parent: Path, child: Path) -> bool: + return self.facts(parent).location in self.facts(child).ancestors + + def same_path(self, first: Path, second: Path) -> bool: + if self._closed: + _fail("experimental filesystem sample used outside its preview") + if first == second: + return True + first_key, second_key = self.facts(first).location, self.facts(second).location + # samefile fails for missing endpoints. Do not turn equivalent missing + # suffixes into a successful immutable claim/plan identity binding. + return not first_key[2] and not second_key[2] and first_key == second_key + + +_path_observation_module: Any = None + + +def _load_path_observation() -> Any: + global _path_observation_module + if _path_observation_module is None: + path = Path(__file__).with_name("ProtocytePathObservation.py") + name = f"{__name__}_path_observation" + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail("experimental path observer could not be loaded") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + exec(compile(path.read_bytes(), os.fspath(path), "exec"), module.__dict__) + except BaseException: + sys.modules.pop(name, None) + raise + _path_observation_module = module + return _path_observation_module + + +class _FreshRegistryFilesystem: + """Fresh projection reader; retains no filesystem facts across comparisons. + + Native handles have call lifetime only. Physical containment, immutable + identity binding and the subsequent reference pass remain freshly observed. + """ + + def __init__(self) -> None: + self.module = _load_path_observation() + self.reader = self.module.FreshPathObserver() + + def close(self) -> None: + self.reader.close() + + def project(self, path: Path, *, leaf_may_be_file: bool = False) -> Path: + path = _require_absolute(path, "filesystem path") + try: + return self.reader.project(path, leaf_may_be_file=leaf_may_be_file) + except self.module.UnsafeObservation as error: + _fail(f"experimental path observation rejected a path: {error}") + + def path_key(self, path: Path) -> str: + identity = os.fspath(self.project(path)).replace("\\", "/").casefold() + return _sha256_bytes(identity.encode("utf-8")) + + def overlaps(self, first: Path, second: Path) -> bool: + first, second = self.project(first), self.project(second) + return ( + _projected_contains(first, second) + or _projected_contains(second, first) + or _projected_physically_contains(first, second) + or _projected_physically_contains(second, first) + ) + + def contains(self, parent: Path, child: Path) -> bool: + return _projected_contains( + self.project(parent), self.project(child, leaf_may_be_file=True) + ) + + def physically_contains(self, parent: Path, child: Path) -> bool: + return _projected_physically_contains(self.project(parent), self.project(child)) + + @staticmethod + def same_path(first: Path, second: Path) -> bool: + return _same_physical_path(first, second) + + +_observation_commit_module: Any = None + + +def _load_observation_commit() -> Any: + global _observation_commit_module + if _observation_commit_module is None: + path = Path(__file__).with_name("ProtocyteObservationCommit.py") + name = f"{__name__}_observation_commit" + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail("experimental observation commit could not be loaded") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + exec(compile(path.read_bytes(), os.fspath(path), "exec"), module.__dict__) + except BaseException: + sys.modules.pop(name, None) + raise + _observation_commit_module = module + return _observation_commit_module + + class OutputCoordinator: - def __init__(self, lock_root: Path) -> None: + def __init__(self, lock_root: Path, *, registry_validation: str | None = None) -> None: + if registry_validation is None: + selected = os.environ.get("PROTOCYTE_REGISTRY_VALIDATION", "auto").strip().lower() or "auto" + if selected not in ("auto", "reference"): + _fail("PROTOCYTE_REGISTRY_VALIDATION must be auto or reference") + registry_validation = ( + "indexed" if selected == "auto" and _COMMITTED_INDEX_QUALIFIED and os.name == "nt" + else "reference" + ) + if registry_validation not in ("reference", "shadow", "native-shadow", "commit-shadow", "indexed"): + _fail("registry validation must be reference, indexed, or shadow (including native/commit-shadow)") self.lock_root = project_path(_require_absolute(lock_root, "output lock root")) + self.registry_validation = registry_validation + self.validation_metrics: dict[str, Any] = {} def reconcile(self, plan: Plan) -> str: # All claim/plan writers hold the registry lock through plan commit, so @@ -1289,11 +1507,381 @@ def _validate_registry( retiring_root_keys: set[str] | None = None, *, progress: _ReconcileProgress | None = None, + ) -> None: + metrics: dict[str, Any] = { + "mode": self.registry_validation, + "authoritative": "reference", + "preview_wall_seconds": 0.0, + "reference_wall_seconds": 0.0, + "agreement": None, + } + self.validation_metrics = metrics + preview_accepted: bool | None = None + index_allowed = self.registry_validation == "indexed" and _COMMITTED_INDEX_QUALIFIED + if self.registry_validation == "indexed" and not index_allowed: + metrics["index_authorization_blocked"] = True + metrics["fallback"] = "reference" + if self.registry_validation == "commit-shadow" or index_allowed: + if progress is not None: + progress.phase("validating registry", "validation") + started = time.perf_counter() + try: + # Close markers on shared ancestors would otherwise invalidate + # simultaneous observers using different private registries. + # This lock coordinates observers only; it never substitutes + # for registry/generation/publication locks or filesystem checks. + with self._observation_lock(): + preview_accepted = self._preview_committed_index( + plans, retiring_root_keys or set(), progress=progress + ) + metrics["preview_result"] = "accepted" if preview_accepted else "conflict" + except Exception as error: + module = _observation_commit_module + cleanup_failure = getattr(module, "ProbeCleanupFailed", None) + if cleanup_failure is not None and isinstance(error, cleanup_failure): + _fail("native observation resources could not be retired safely; no reconciliation changes were authorized") + # A failed or unsupported certificate grants no authority. The + # ordinary reference path still determines this operation. + metrics["preview_result"] = "unverified" + metrics["commit_certificate"] = "unverified" + metrics["commit_failure_type"] = type(error).__name__ + metrics["fallback"] = "reference" + finally: + metrics["preview_wall_seconds"] = time.perf_counter() - started + if self.registry_validation == "indexed": + if ( + preview_accepted is True + and metrics.get("commit_certificate") == "verified" + and metrics.get("commit_state") == "closed" + and metrics.get("commit_cleanup_failed") is False + and metrics.get("commit_probe_state") == "closed" + and metrics.get("commit_probe_native_retired") is True + and type(metrics.get("commit_probe_active")) is int + and metrics["commit_probe_active"] == 0 + and type(metrics.get("commit_probe_pending")) is int + and metrics["commit_probe_pending"] == 0 + and type(metrics.get("commit_probe_comparisons")) is int + and type(metrics.get("commit_fresh_comparisons")) is int + and metrics["commit_probe_comparisons"] == metrics["commit_fresh_comparisons"] + and type(metrics.get("commit_handles_opened")) is int + and type(metrics.get("commit_handles_closed")) is int + and metrics["commit_handles_opened"] > 0 + and metrics.get("commit_handles_opened") == metrics.get("commit_handles_closed") + ): + metrics["authoritative"] = "index" + metrics["reference_result"] = "not-required" + return + # Reference decides conflicts and all unverified/capability + # cases, retaining its diagnostics and upgrade behavior. + metrics["fallback"] = "reference" + else: + self._inject("after-observation-commit") + if progress is not None: + progress.phase("validating registry (reference authority)", "validation") + if self.registry_validation == "native-shadow": + if progress is not None: + progress.phase("fresh experimental path observation", "validation") + started = time.perf_counter() + filesystem: Any = None + try: + filesystem = _FreshRegistryFilesystem() + self._validate_registry_reference( + plans, retiring_root_keys, _filesystem=filesystem + ) + preview_accepted = True + metrics["preview_result"] = "accepted" + except Exception as error: + module = _path_observation_module + if module is not None and isinstance(error, module.ObservationUnavailable): + # Capability failure is never a reason to demand privileges, + # change user configuration or authorize cached geometry. + metrics["preview_result"] = "unavailable" + else: + metrics["preview_result"] = "sample-error" + metrics["preview_error_type"] = type(error).__name__ + finally: + if filesystem is not None: + try: + filesystem.close() + except Exception as error: + preview_accepted = None + metrics["preview_result"] = "sample-error" + metrics["preview_error_type"] = type(error).__name__ + finally: + metrics.update(filesystem.reader.metrics()) + metrics["preview_wall_seconds"] = time.perf_counter() - started + self._inject("after-native-observation") + if progress is not None: + progress.phase("validating registry (reference authority)", "validation") + if self.registry_validation == "shadow": + if progress is not None: + progress.phase("sampling experimental ownership index", "validation") + started = time.perf_counter() + try: + preview_accepted = self._preview_registry_index( + plans, retiring_root_keys or set(), progress=progress + ) + metrics["preview_result"] = "accepted" if preview_accepted else "conflict" + except Exception as error: + # Even a preview/parser failure cannot replace a fresh reference + # pass. Keep diagnostics path-free and fail closed if reference + # later accepts; preserve its original error if it rejects. + metrics["preview_result"] = "sample-error" + metrics["preview_error_type"] = type(error).__name__ + finally: + metrics["preview_wall_seconds"] = time.perf_counter() - started + self._inject("after-index-preview") + if progress is not None: + progress.phase("validating registry (reference authority)", "validation") + + started = time.perf_counter() + try: + self._validate_registry_reference(plans, retiring_root_keys, progress=progress) + except CoordinatorError: + metrics["reference_result"] = "rejected" + if preview_accepted is not None: + metrics["agreement"] = not preview_accepted + raise + finally: + metrics["reference_wall_seconds"] = time.perf_counter() - started + metrics["reference_result"] = "accepted" + if self.registry_validation in ("shadow", "native-shadow", "commit-shadow"): + if metrics.get("fallback") == "reference": + metrics["agreement"] = None + return + if metrics.get("preview_result") == "unavailable": + metrics["agreement"] = None + metrics["fallback"] = "reference" + return + metrics["agreement"] = preview_accepted is True + if preview_accepted is not True: + _fail( + "experimental ownership index disagrees with the fresh reference " + "validator; no reconciliation changes were authorized" + ) + + def _observation_lock(self) -> Any: + if os.name != "nt": + return contextlib.nullcontext() + for name in ("LOCALAPPDATA", "TEMP", "TMP"): + value = os.environ.get(name) + if value and Path(value).is_absolute(): + return FileLock(Path(value) / "protocyte" / "observation-commit-v1.lock") + _fail("native observation coordination is unavailable") + + def _preview_committed_index( + self, plans: Sequence[Plan], retiring_root_keys: set[str], *, + progress: _ReconcileProgress | None = None, + ) -> bool: + model = _load_ownership_index() + module = _load_observation_commit() + # A partially updated install must not dispatch work through an older + # helper lacking exception-safe admission and fatal handle cleanup. + contract = getattr(module, "COMMIT_CONTRACT_VERSION", None) + if type(contract) is not int or contract != 2: + raise RuntimeError("observation helper contract requires reference validation") + native = _load_path_observation() + for dependency, marker in ((model, "OWNERSHIP_CONTRACT_VERSION"), (native, "PATH_CONTRACT_VERSION")): + contract = getattr(dependency, marker, None) + if type(contract) is not int or contract != 1: + raise RuntimeError("observation dependency requires reference validation") + scope = module.WindowsObservationCommit(native, model) + metrics = self.validation_metrics + metrics.update(commit_claims_checked=0, commit_certificate="unverified") + entries = [] + accepted = True + try: + internal = (self.lock_root / "roots", self.lock_root / "generation", self.lock_root / "publication") + for plan in plans: + for target in plan.targets: + if scope.contains(target.staging, self.lock_root) or scope.physically_contains(target.staging, self.lock_root): + accepted = False + if scope.overlaps(plan.root, self.lock_root) or any(scope.overlaps(path, plan.root) for path in internal): + accepted = False + roots = self.lock_root / "roots" + if plans and scope.record_exists(roots): + if scope.project(roots) != roots: + _fail("provisional commit found an unsafe registry path") + state_names = scope.list_names(roots) + if progress is not None: + progress.registry(states=len(state_names)) + for name in state_names: + if not _is_sha256(name): + _fail("provisional commit found an unsafe registry entry") + state = roots / name + if scope.project(state) != state: + _fail("provisional commit found a changed registry entry") + names = scope.list_names(state, relevant=frozenset(("claim.json", "plan.json"))) + if "claim.json" not in names: + # Reference owns abandoned-initialization cleanup. Do + # not silently change its recovery behavior on upgrade. + raise module.CapabilityUnavailable("unclaimed state requires reference cleanup") + source = state / "claim.json" + claim = _load_json(source, "output claim", _filesystem=scope) + self._validate_claim_shape(claim, source) + root, _ = self._claim_paths(claim, source, _filesystem=scope) + if name != claim["root_key"]: + _fail("provisional commit found a claim under the wrong key") + recorded = self._load_recorded_plan(state, claim, _filesystem=scope) + key, build = str(claim["root_key"]), str(claim["build_id"]) + entries.append((model.Reservation("root", key, build, None, scope.facts(root)), root, scope.is_stable(root))) + if recorded is not None: + for target in recorded.targets: + entries.append((model.Reservation("staging", key, build, target.identity, scope.facts(target.staging)), target.staging, scope.is_stable(target.staging))) + metrics["commit_claims_checked"] += 1 + if progress is not None: + progress.registry(claim=True) + progress.phase(f"validating registry ({metrics['commit_claims_checked']} claims)", "validation") + queries = [ + (plan.root, scope.path_key(plan.root), plan.build_id, + tuple((target.identity, target.staging) for target in plan.targets)) + for plan in plans + ] + # Registration is complete before any worker can run. The frozen + # adapter exposes prepared immutable comparisons, not path lookup. + with scope.comparisons() as comparisons: + index = module.ProvisionalOwnershipIndex(model, comparisons, entries) + for root, key, build, staging in queries: + conflict = index.conflict( + root=root, root_key=key, build_id=build, + staging=staging, retiring_root_keys=retiring_root_keys, + ) + if conflict is not None: + accepted = False + metrics["commit_reservations"] = len(entries) + metrics["commit_index_queries"] = index.queries + metrics["commit_fresh_comparisons"] = index.fresh_comparisons + self._inject("before-observation-commit") + scope.seal() + metrics["commit_certificate"] = "verified" + return accepted + finally: + try: + scope.close() + finally: + metrics.update(scope.metrics()) + + def _preview_registry_index( + self, + plans: Sequence[Plan], + retiring_root_keys: set[str], + *, + progress: _ReconcileProgress | None = None, + ) -> bool: + """Sample all ownership records without authorizing or mutating anything. + + The caller holds the ordinary reconciliation locks. Filesystem facts are + deliberately untrusted across comparisons: only the subsequent fresh + reference pass can authorize proceeding. No preview objects escape. + """ + model = _load_ownership_index() + sample = _SampledRegistryFilesystem(model) + metrics = self.validation_metrics + metrics.update(preview_claims=0, preview_records_read=0, preview_unclaimed_states=0) + reservations: list[Any] = [] + try: + internal_paths = ( + self.lock_root / "roots", self.lock_root / "generation", + self.lock_root / "publication", + ) + for plan in plans: + for target in plan.targets: + if sample.contains(target.staging, self.lock_root) or sample.physically_contains( + target.staging, self.lock_root + ): + metrics["preview_conflict"] = "staging-lock-namespace" + return False + if sample.overlaps(plan.root, self.lock_root) or any( + sample.overlaps(path, plan.root) for path in internal_paths + ): + metrics["preview_conflict"] = "root-lock-namespace" + return False + roots = self.lock_root / "roots" + if plans and os.path.lexists(roots): + if sample.project(roots) != roots: + _fail("experimental sample found an unsafe registry path") + with os.scandir(roots) as stream: + states = sorted(stream, key=lambda entry: entry.name) + for entry in states: + state = roots / entry.name + if ( + _is_link(state) or not entry.is_dir(follow_symlinks=False) + or not _is_sha256(entry.name) + ): + _fail("experimental sample found an unsafe registry entry") + with os.scandir(state) as stream: + names = {child.name for child in stream} + if "claim.json" not in names: + # Reference validation owns abandoned-initialization + # cleanup. A preview must never mutate registry state. + metrics["preview_unclaimed_states"] += 1 + continue + source = state / "claim.json" + claim = _load_json(source, "output claim") + metrics["preview_records_read"] += 1 + self._validate_claim_shape(claim, source) + root, _ = self._claim_paths(claim, source, _filesystem=sample) + if entry.name != claim["root_key"]: + _fail("experimental sample found a claim under the wrong key") + recorded = self._load_recorded_plan(state, claim, _filesystem=sample) + if recorded is not None: + metrics["preview_records_read"] += 1 + root_key, build_id = str(claim["root_key"]), str(claim["build_id"]) + reservations.append(model.Reservation( + "root", root_key, build_id, None, sample.facts(root) + )) + if recorded is not None: + reservations.extend( + model.Reservation( + "staging", root_key, build_id, target.identity, + sample.facts(target.staging), + ) + for target in recorded.targets + ) + metrics["preview_claims"] += 1 + if progress is not None: + progress.phase( + f"sampling experimental index ({metrics['preview_claims']} claims)", + "validation", + ) + index = model.OwnershipIndex(reservations) + metrics["indexed_reservations"] = len(reservations) + for plan in plans: + conflict = index.conflict( + root=sample.facts(plan.root), root_key=sample.path_key(plan.root), + build_id=plan.build_id, + staging=((target.identity, sample.facts(target.staging)) for target in plan.targets), + retiring_root_keys=retiring_root_keys, + ) + metrics["index_queries"] = index.queries + if conflict is not None: + metrics["preview_conflict"] = conflict + return False + return True + finally: + metrics["sampled_geometry_projections"] = sample.projections + metrics["sampled_directory_observations"] = sample.observations + sample.close() + + def _validate_registry_reference( + self, + plans: Sequence[Plan], + retiring_root_keys: set[str] | None = None, + *, + progress: _ReconcileProgress | None = None, + _filesystem: Any = None, ) -> None: if not plans: return if retiring_root_keys is None: retiring_root_keys = set() + project = project_path if _filesystem is None else _filesystem.project + path_key = _path_key if _filesystem is None else _filesystem.path_key + overlaps = _paths_overlap if _filesystem is None else _filesystem.overlaps + contains = _contains if _filesystem is None else _filesystem.contains + physically_contains = _physically_contains if _filesystem is None else _filesystem.physically_contains + if _filesystem is not None: + self.validation_metrics["native_claims_checked"] = 0 internal_paths = ( self.lock_root / "roots", self.lock_root / "generation", @@ -1301,15 +1889,15 @@ def _validate_registry( ) for plan in plans: for target in plan.targets: - if _contains(target.staging, self.lock_root) or _physically_contains( + if contains(target.staging, self.lock_root) or physically_contains( target.staging, self.lock_root ): _fail( "generation staging contains the output coordinator lock root: " f"{target.staging} and {self.lock_root}" ) - if _paths_overlap(plan.root, self.lock_root) or any( - _paths_overlap(path, plan.root) for path in internal_paths + if overlaps(plan.root, self.lock_root) or any( + overlaps(path, plan.root) for path in internal_paths ): _fail( "output root overlaps the output coordinator lock namespace: " @@ -1320,7 +1908,7 @@ def _validate_registry( if progress is not None: progress.registry(states=0) return - if project_path(roots) != roots: + if project(roots) != roots: _fail(f"output registry is unsafe or was replaced: {roots}") try: with os.scandir(roots) as stream: @@ -1344,34 +1932,40 @@ def _validate_registry( _fail(f"could not enumerate output claim state {state}: {error}") claim_path = state / "claim.json" if "claim.json" not in names: - _durable_rmtree(state) + if _filesystem is None: + _durable_rmtree(state) continue - claim = _load_json(claim_path, "output claim") + claim = _load_json(claim_path, "output claim", _filesystem=_filesystem) self._validate_claim_shape(claim, claim_path) - claimed_root, _ = self._claim_paths(claim, claim_path) + claimed_root, _ = self._claim_paths(claim, claim_path, _filesystem=_filesystem) if entry.name != claim["root_key"]: _fail( f"output claim is stored under the wrong registry key: {claim_path}" ) - recorded_plan = self._load_recorded_plan(state, claim) + if _filesystem is None: + recorded_plan = self._load_recorded_plan(state, claim) + else: + recorded_plan = self._load_recorded_plan(state, claim, _filesystem=_filesystem) if progress is not None: progress.registry(claim=True) + if _filesystem is not None: + self.validation_metrics["native_claims_checked"] += 1 recorded_targets = recorded_plan.targets if recorded_plan else () for plan in plans: - same_root_key = claim["root_key"] == _path_key(plan.root) - if _paths_overlap(claimed_root, plan.root) and not same_root_key: + same_root_key = claim["root_key"] == path_key(plan.root) + if overlaps(claimed_root, plan.root) and not same_root_key: _fail( "output root overlaps a root claimed by another build: " f"{plan.root} and {claimed_root}" ) for recorded_target in recorded_targets: - if _paths_overlap(recorded_target.staging, plan.root): + if overlaps(recorded_target.staging, plan.root): _fail( "output root overlaps staging reserved by another plan: " f"{plan.root} and {recorded_target.staging}" ) for target in plan.targets: - if _paths_overlap(claimed_root, target.staging): + if overlaps(claimed_root, target.staging): _fail( "generation staging overlaps a claimed output root: " f"{target.staging} and {claimed_root}" @@ -1388,7 +1982,7 @@ def _validate_registry( and target.identity == recorded_target.identity ): continue - if _paths_overlap(recorded_target.staging, target.staging): + if overlaps(recorded_target.staging, target.staging): _fail( "generation staging overlaps staging reserved by another plan: " f"{target.staging} and {recorded_target.staging}" @@ -1425,26 +2019,32 @@ def _load_claim(self, state: Path, plan: Plan) -> dict[str, Any]: @staticmethod def _require_plan_claim_binding( - plan: Plan, claim: Mapping[str, Any], source: Path + plan: Plan, claim: Mapping[str, Any], source: Path, *, _filesystem: Any = None ) -> None: - claim_root, claim_build_root = OutputCoordinator._claim_paths(claim, source) + path_key = _path_key if _filesystem is None else _filesystem.path_key + same_path = _same_physical_path if _filesystem is None else _filesystem.same_path + claim_root, claim_build_root = OutputCoordinator._claim_paths( + claim, source, _filesystem=_filesystem + ) if ( - str(claim["root_key"]) != _path_key(plan.root) + str(claim["root_key"]) != path_key(plan.root) or str(claim["build_id"]) != plan.build_id - or not _same_physical_path(claim_root, plan.root) - or not _same_physical_path(claim_build_root, plan.build_root) + or not same_path(claim_root, plan.root) + or not same_path(claim_build_root, plan.build_root) ): _fail(f"configured output plan does not match its immutable claim: {source}") @staticmethod def _claim_paths( - claim: Mapping[str, Any], source: Path + claim: Mapping[str, Any], source: Path, *, _filesystem: Any = None ) -> tuple[Path, Path]: - claim_root = project_path(Path(str(claim["root"]))) - claim_build_root = project_path(Path(str(claim["build_root"]))) + project = project_path if _filesystem is None else _filesystem.project + path_key = _path_key if _filesystem is None else _filesystem.path_key + claim_root = project(Path(str(claim["root"]))) + claim_build_root = project(Path(str(claim["build_root"]))) if ( - str(claim["root_key"]) != _path_key(claim_root) - or str(claim["build_id"]) != _path_key(claim_build_root) + str(claim["root_key"]) != path_key(claim_root) + or str(claim["build_id"]) != path_key(claim_build_root) ): _fail(f"output claim identity is inconsistent: {source}") return claim_root, claim_build_root @@ -1507,13 +2107,26 @@ def _require_current_plan( ) def _load_recorded_plan( - self, state: Path, claim: Mapping[str, Any] + self, state: Path, claim: Mapping[str, Any], *, _filesystem: Any = None ) -> Plan | None: path = state / "plan.json" - if not path.exists(): + if _filesystem is not None and hasattr(_filesystem, "record_exists"): + exists = _filesystem.record_exists(path) + else: + try: + path.lstat() + except FileNotFoundError: + exists = False + except OSError as error: + _fail(f"could not inspect configured output plan {path}: {error}") + else: + exists = True + if not exists: return None - plan = Plan.from_payload(_load_json(path, "configured output plan"), path) - self._require_plan_claim_binding(plan, claim, path) + plan = Plan.from_payload( + _load_json(path, "configured output plan", _filesystem=_filesystem), path, _filesystem=_filesystem + ) + self._require_plan_claim_binding(plan, claim, path, _filesystem=_filesystem) return plan @staticmethod @@ -2071,6 +2684,22 @@ def _parse_arguments(arguments: Sequence[str]) -> argparse.Namespace: parser.add_argument("--exec", dest="execution", nargs=argparse.REMAINDER) parser.add_argument("--current-plan", type=Path, action="append", default=[]) parser.add_argument("--retired-plan", type=Path, action="append", default=[]) + parser.add_argument( + "--experimental-registry-index", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--experimental-native-observation", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--experimental-observation-commit", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--experimental-committed-index", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--reference-registry-validation", action="store_true", + help="use the full reference registry validator", + ) return parser.parse_args(arguments) @@ -2085,7 +2714,20 @@ def main(arguments: Sequence[str] | None = None) -> int: return 0 if options.lock_root is None: _fail(f"{options.command} requires --lock-root") - coordinator = OutputCoordinator(options.lock_root) + if sum((options.experimental_native_observation, options.experimental_registry_index, options.experimental_observation_commit, options.experimental_committed_index, options.reference_registry_validation)) > 1: + _fail("choose one experimental validation mode") + if options.experimental_committed_index and not _COMMITTED_INDEX_QUALIFIED: + _fail("committed index is not qualified for consumer use; reference validation is required") + coordinator = OutputCoordinator( + options.lock_root, + registry_validation=( + "reference" if options.reference_registry_validation + else "indexed" if options.experimental_committed_index + else "commit-shadow" if options.experimental_observation_commit + else "native-shadow" if options.experimental_native_observation + else "shadow" if options.experimental_registry_index else None + ), + ) if options.command == "reconcile-set": current = [Plan.read(path) for path in options.current_plan] retired = [Plan.read(path) for path in options.retired_plan] diff --git a/cmake/ProtocyteOwnershipIndex.py b/cmake/ProtocyteOwnershipIndex.py new file mode 100644 index 0000000..22097b0 --- /dev/null +++ b/cmake/ProtocyteOwnershipIndex.py @@ -0,0 +1,128 @@ +"""Ownership geometry, with no mutation or filesystem authority. + +The observing caller must authenticate records and verify the observation +scope before using this geometry to authorize reconciliation or publication. +""" + +from __future__ import annotations + +from bisect import bisect_left +from dataclasses import dataclass +from typing import Iterable, Literal + + +LocationKey = tuple[int, int, tuple[str, ...]] + + +@dataclass(frozen=True) +class DirectoryObservation: + portable: str + location: LocationKey + ancestors: tuple[LocationKey, ...] + + def overlaps(self, other: DirectoryObservation) -> bool: + return ( + self.portable == other.portable + or self.portable.startswith(other.portable + "/") + or other.portable.startswith(self.portable + "/") + or self.location in other.ancestors + or other.location in self.ancestors + ) + + +@dataclass(frozen=True) +class Reservation: + kind: Literal["root", "staging"] + root_key: str + build_id: str + target: str | None + directory: DirectoryObservation + + +class OwnershipIndex: + """Find overlapping reservations from both lexical and physical geometry. + + Physical ancestors include normalized missing-suffix prefixes. Indexing both + endpoint and ancestor keys covers containment in either direction, including + non-link aliases whose names have no lexical prefix in common. Common + ancestors alone do not imply overlap. + """ + + def __init__(self, reservations: Iterable[Reservation]) -> None: + contract = globals().get("OWNERSHIP_CONTRACT_VERSION") + if type(contract) is not int or contract != 1: + raise RuntimeError("incomplete ownership helper installation") + self.reservations = tuple(reservations) + self.queries = 0 + exact: dict[LocationKey, set[int]] = {} + ancestors: dict[LocationKey, set[int]] = {} + lexical: dict[str, set[int]] = {} + for identifier, reservation in enumerate(self.reservations): + facts = reservation.directory + exact.setdefault(facts.location, set()).add(identifier) + for ancestor in facts.ancestors: + ancestors.setdefault(ancestor, set()).add(identifier) + lexical.setdefault(facts.portable, set()).add(identifier) + self._exact = {key: frozenset(value) for key, value in exact.items()} + self._ancestors = {key: frozenset(value) for key, value in ancestors.items()} + self._lexical = {key: frozenset(value) for key, value in lexical.items()} + self._names = sorted(lexical) + + def overlapping(self, directory: DirectoryObservation) -> tuple[Reservation, ...]: + self.queries += 1 + candidates: set[int] = set(self._ancestors.get(directory.location, ())) + for ancestor in directory.ancestors: + candidates.update(self._exact.get(ancestor, ())) + + current = directory.portable + while True: + candidates.update(self._lexical.get(current, ())) + if "/" not in current: + break + current = current.rsplit("/", 1)[0] + prefix = directory.portable + "/" + position = bisect_left(self._names, prefix) + while position < len(self._names) and self._names[position].startswith(prefix): + candidates.update(self._lexical[self._names[position]]) + position += 1 + # Keep deterministic reporting. The final predicate is also a defensive + # check on candidate retrieval; it uses observations, never fresh I/O. + return tuple( + self.reservations[identifier] + for identifier in sorted(candidates) + if self.reservations[identifier].directory.overlaps(directory) + ) + + def conflict( + self, + *, + root: DirectoryObservation, + root_key: str, + build_id: str, + staging: Iterable[tuple[str, DirectoryObservation]], + retiring_root_keys: set[str], + ) -> str | None: + for reservation in self.overlapping(root): + if reservation.kind == "root": + if reservation.root_key != root_key: + return "root-root" + else: + return "root-staging" + for target, directory in staging: + for reservation in self.overlapping(directory): + if reservation.kind == "root": + return "staging-root" + if target == reservation.target and ( + root_key == reservation.root_key + or ( + reservation.root_key in retiring_root_keys + and build_id == reservation.build_id + ) + ): + continue + return "staging-staging" + return None + + +# EOF capability marker; an incomplete installed source cannot advertise it. +OWNERSHIP_CONTRACT_VERSION = 1 diff --git a/cmake/ProtocytePathObservation.py b/cmake/ProtocytePathObservation.py new file mode 100644 index 0000000..456f77d --- /dev/null +++ b/cmake/ProtocytePathObservation.py @@ -0,0 +1,268 @@ +"""Fresh Windows path operations, never an operation-wide lease. + +Each projection opens the entire existing path with OBJ_DONT_REPARSE, reads that +handle and closes it before returning. No filesystem facts are cached. Missing +components are searched again on every call. This module grants no ownership or +mutation authority; the coordinator verifies the observation scope separately. +""" + +from __future__ import annotations + +import ctypes +import os +from pathlib import Path + + +class ObservationUnavailable(RuntimeError): + """The native observation contract is unavailable; use the reference path.""" + + +class UnsafeObservation(RuntimeError): + """An observed path is unsafe or changed during observation.""" + + +class FreshPathObserver: + """Own native call bindings, not observations, for one validation phase.""" + + def __init__(self) -> None: + contract = globals().get("PATH_CONTRACT_VERSION") + if type(contract) is not int or contract != 1: + raise ObservationUnavailable("incomplete path helper installation") + if os.name != "nt": + raise ObservationUnavailable("native path observation requires Windows") + from ctypes import wintypes as w + + class UnicodeString(ctypes.Structure): + _fields_ = [ + ("Length", w.USHORT), + ("MaximumLength", w.USHORT), + ("Buffer", w.LPWSTR), + ] + + class ObjectAttributes(ctypes.Structure): + _fields_ = [ + ("Length", w.ULONG), + ("RootDirectory", w.HANDLE), + ("ObjectName", ctypes.POINTER(UnicodeString)), + ("Attributes", w.ULONG), + ("SecurityDescriptor", w.LPVOID), + ("SecurityQualityOfService", w.LPVOID), + ] + + class IoStatusBlock(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + + class AttributeTagInfo(ctypes.Structure): + _fields_ = [("Attributes", w.DWORD), ("ReparseTag", w.DWORD)] + + self._w = w + self._unicode = UnicodeString + self._attributes = ObjectAttributes + self._status = IoStatusBlock + self._tag = AttributeTagInfo + self._nt = ctypes.WinDLL("ntdll", use_last_error=True) + self._kernel = ctypes.WinDLL("kernel32", use_last_error=True) + self._open = self._nt.NtCreateFile + self._open.argtypes = ( + ctypes.POINTER(w.HANDLE), + w.DWORD, + ctypes.POINTER(ObjectAttributes), + ctypes.POINTER(IoStatusBlock), + w.LPVOID, + w.ULONG, + w.ULONG, + w.ULONG, + w.ULONG, + w.LPVOID, + w.ULONG, + ) + self._open.restype = w.LONG + self._dos_error = self._nt.RtlNtStatusToDosError + self._dos_error.argtypes = (w.LONG,) + self._dos_error.restype = w.ULONG + self._info = self._kernel.GetFileInformationByHandleEx + self._info.argtypes = (w.HANDLE, ctypes.c_int, w.LPVOID, w.DWORD) + self._info.restype = w.BOOL + self._final = self._kernel.GetFinalPathNameByHandleW + self._final.argtypes = (w.HANDLE, w.LPWSTR, w.DWORD, w.DWORD) + self._final.restype = w.DWORD + self._close = self._kernel.CloseHandle + self._close.argtypes = (w.HANDLE,) + self._close.restype = w.BOOL + self._closed = False + self.projections = 0 + self.open_calls = 0 + self.information_calls = 0 + self.final_path_calls = 0 + self.handles_opened = 0 + self.handles_closed = 0 + + def close(self) -> None: + self._closed = True + if self.handles_opened != self.handles_closed: + raise UnsafeObservation("native observation leaked a handle") + + @staticmethod + def _native_name(path: Path) -> str: + text = os.fspath(path) + if text.startswith("\\\\?\\"): + # Path.resolve preserves an explicitly supplied namespace prefix. + # Stripping it would alter the existing ownership-key spelling. + raise ObservationUnavailable("explicit namespaces use reference validation") + # Deliberately narrow capability boundary. Device names, UNC shares and + # alternate data streams use reference validation, without new user flags. + if ( + not path.is_absolute() + or len(text) < 3 + or not text[0].isascii() + or not text[0].isalpha() + or text[1:3] != ":\\" + or ":" in text[2:] + or any(character in text for character in ("\x00", "\r", "\n")) + ): + raise ObservationUnavailable("path needs the portable reference reader") + return "\\??\\" + text + + def _invoke_open(self, handle, *arguments): + try: + return self._open(ctypes.byref(handle), *arguments) + except BaseException: + # A foreign call can raise after the OS wrote its output handle. + # It has not been published to any caller yet; retire it exactly + # once before propagating the error or permitting reference work. + if handle.value: + try: + self.handles_opened += 1 + finally: + if not self._close(handle): + raise UnsafeObservation("interrupted open could not release its handle") + self.handles_closed += 1 + raise + + def _open_existing(self, path: Path): + text = self._native_name(path) + encoded_length = len(text.encode("utf-16-le")) + if encoded_length > 65532: + raise ObservationUnavailable("path exceeds the native Unicode name limit") + storage = ctypes.create_unicode_buffer(text) + name = self._unicode( + encoded_length, + encoded_length + 2, + ctypes.cast(storage, self._w.LPWSTR), + ) + attributes = self._attributes( + ctypes.sizeof(self._attributes), + None, + ctypes.pointer(name), + 0x1040, # OBJ_DONT_REPARSE | OBJ_CASE_INSENSITIVE + None, + None, + ) + status = self._status() + handle = self._w.HANDLE() + self.open_calls += 1 + result = self._invoke_open( + handle, + 0x100080, # SYNCHRONIZE | FILE_READ_ATTRIBUTES + ctypes.byref(attributes), + ctypes.byref(status), + None, + 0, + 7, # share read/write/delete; no claim of a topology freeze + 1, # FILE_OPEN, never create anything + 0x20, # FILE_SYNCHRONOUS_IO_NONALERT; no incompatible DIRECTORY flags + None, + 0, + ) + code = result & 0xFFFFFFFF + if code in (0xC0000034, 0xC000003A): # name/path not found + return None + if code in (0xC000050B, 0xC0000279, 0xC0000280): + raise UnsafeObservation("filesystem path contains a reparse point") + if result < 0: + # Do not reinterpret permission/sharing/invalid-name failures as + # missing components. The caller can only fall back to reference. + raise ctypes.WinError(self._dos_error(result)) + if not handle.value: + raise UnsafeObservation("native open returned an unsupported result") + self.handles_opened += 1 + if code != 0: + if not self._close(handle): + raise ctypes.WinError(ctypes.get_last_error()) + self.handles_closed += 1 + raise UnsafeObservation("native open returned an unsupported result") + return handle + + def _describe(self, handle, *, leaf_may_be_file: bool) -> Path: + tag = self._tag() + self.information_calls += 1 + if not self._info(handle, 9, ctypes.byref(tag), ctypes.sizeof(tag)): + raise ctypes.WinError(ctypes.get_last_error()) + if tag.Attributes & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT, any tag + raise UnsafeObservation("filesystem path contains a reparse point") + if not tag.Attributes & 0x10 and not leaf_may_be_file: + raise UnsafeObservation("filesystem path has a non-directory ancestor") + capacity = 512 + for _ in range(3): + buffer = ctypes.create_unicode_buffer(capacity) + self.final_path_calls += 1 + size = self._final(handle, buffer, capacity, 0) + if not size: + raise ctypes.WinError(ctypes.get_last_error()) + if size < capacity: + value = buffer.value + if not value.startswith("\\\\?\\") or value.startswith("\\\\?\\UNC\\"): + raise ObservationUnavailable("unsupported final path namespace") + return Path(os.path.normpath(value[4:])) + capacity = size + 1 + raise UnsafeObservation("native final path changed repeatedly") + + def project(self, path: Path, *, leaf_may_be_file: bool = False) -> Path: + if self._closed: + raise UnsafeObservation("filesystem observation used outside its scope") + self.projections += 1 + path = Path(os.path.normpath(path)) + self._native_name(path) + # Fresh on every call. In particular, there is no negative lookup cache + # and no retained ancestor handle that could lose its name binding. + for _ in range(8): + current = path + missing: list[str] = [] + while True: + handle = self._open_existing(current) + if handle is not None: + break + if current.parent == current: + raise UnsafeObservation("could not observe an existing ancestor") + missing.append(current.name) + current = current.parent + try: + projected = self._describe( + handle, leaf_may_be_file=leaf_may_be_file and not missing + ) + except FileNotFoundError: + continue + finally: + if not self._close(handle): + raise ctypes.WinError(ctypes.get_last_error()) + self.handles_closed += 1 + for component in reversed(missing): + if component in ("", ".", ".."): + raise UnsafeObservation("unsafe missing path component") + projected /= component + return projected + raise UnsafeObservation("filesystem path changed repeatedly while observing") + + def metrics(self) -> dict[str, int]: + return { + "native_projections": self.projections, + "native_open_calls": self.open_calls, + "native_information_calls": self.information_calls, + "native_final_path_calls": self.final_path_calls, + "native_handles_opened": self.handles_opened, + "native_handles_closed": self.handles_closed, + } + + +# EOF capability marker; an incomplete installed source cannot advertise it. +PATH_CONTRACT_VERSION = 1 diff --git a/docs/wiki/Troubleshooting.md b/docs/wiki/Troubleshooting.md index 830d902..6de2bb8 100644 --- a/docs/wiki/Troubleshooting.md +++ b/docs/wiki/Troubleshooting.md @@ -202,11 +202,18 @@ progress on standard error. It distinguishes waiting for registry, generation, o publication locks from current-plan validation, registry validation, and output reconciliation. Lines include plan/claim counts and elapsed phase times, without consumer paths or claim tokens. Fast operations remain silent; long operations -emit at most twelve progress lines and one completion or failure summary. A lock +emit progress every five seconds until completion, followed by one completion +or failure summary. A lock wait includes preparing and acquiring its lock files. `registry_entries` counts state directories, including any abandoned initialization directories encountered; `claims_checked` counts authenticated claim/plan records. +Registry validation uses the accelerated validator where supported and falls back +to full validation when needed. Existing builds need no migration, cache reset, +or new configuration. To use the full validator while diagnosing an issue, set +`PROTOCYTE_REGISTRY_VALIDATION=reference` in the build environment; remove it to +restore automatic selection. + If cleanup refuses an unsafe path or cannot remove it, the diagnostic warns that inert staging data outside `OUT_DIR` may remain. Stop related processes and remove only the named staging path after inspecting it. ## Adding a Proto File Does Not Generate It diff --git a/tests/benchmark_observation_commit.py b/tests/benchmark_observation_commit.py new file mode 100644 index 0000000..446ccd7 --- /dev/null +++ b/tests/benchmark_observation_commit.py @@ -0,0 +1,183 @@ +"""Read-only committed candidate benchmark; never reconciliation authority. + +Seeds real claims in a new private registry, takes the ordinary coordinator +locks, validates all current plans and runs the entire provisional read-set +commit (record authentication, comparisons, inventories, versions, witnesses, +and handle release). No tokens, claims, or outputs are produced after seeding. +The optional reference oracle is timed separately. Even a verified native +certificate does not make this experimental algorithm an authorized validator. +Only results.json is suitable for sharing; fixtures contain private paths. +""" + +from __future__ import annotations + +import argparse +import cProfile +import contextlib +import json +import platform +import tempfile +import time +from pathlib import Path + +from benchmark_output_registry import ( + _filesystem_counts, + _implementation_fingerprint, + _load, + _prepare_fixture, +) + + +def sample(module, work: Path, args) -> dict: + expected = _implementation_fingerprint(module) + engine, current, setup_wall, setup_cpu = _prepare_fixture( + module, + work, + args.claims, + args.plans, + targets_per_plan=args.targets_per_plan, + shared_build_root=args.shared_build_root, + existing_directories=args.existing_directories, + ) + profile = cProfile.Profile() + started = time.perf_counter() + with ( + module._ReconcileProgress(len(current), 0) as progress, + contextlib.ExitStack() as locks, + ): + progress.phase("waiting for read-only commit locks", "lock_wait") + locks.enter_context(module.FileLock(engine.lock_root / "registry.lock")) + roots = {module._path_key(plan.root): plan.root for plan in current} + for root in sorted(roots.values(), key=module._portable_identity): + locks.enter_context(module.FileLock(engine._generation_lock(root))) + for root in sorted(roots.values(), key=module._portable_identity): + locks.enter_context(module.FileLock(engine._publication_lock(root))) + lock_seconds = time.perf_counter() - started + progress.phase("checking all current plans", "validation") + total_started, total_cpu = time.perf_counter(), time.process_time() + started = time.perf_counter() + engine._validate_plan_set(current) + current_seconds = time.perf_counter() - started + engine.validation_metrics = { + "mode": "commit-candidate-only", + "authoritative": "none", + } + progress.phase("read-only provisional observation commit", "validation") + started, cpu = time.perf_counter(), time.process_time() + if not args.no_profile: + profile.enable() + try: + accepted = engine._preview_committed_index( + current, set(), progress=progress + ) + finally: + if not args.no_profile: + profile.disable() + committed_seconds = time.perf_counter() - started + committed_cpu = time.process_time() - cpu + if not args.no_profile: + profile.dump_stats(work / "candidate.prof") + total_seconds = time.perf_counter() - total_started + total_cpu_seconds = time.process_time() - total_cpu + assert accepted + metrics = engine.validation_metrics + assert metrics["commit_certificate"] == "verified" + assert metrics["commit_claims_checked"] == args.claims + assert metrics["commit_records_read"] == 2 * args.claims + assert metrics["commit_state"] == "closed" + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + oracle_wall = oracle_cpu = None + if args.reference_oracle: + progress.phase("fresh reference oracle (separate timing)", "validation") + started, cpu = time.perf_counter(), time.process_time() + engine._validate_registry_reference(current, set(), progress=progress) + oracle_wall = time.perf_counter() - started + oracle_cpu = time.process_time() - cpu + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == args.claims + if _implementation_fingerprint(module) != expected: + raise RuntimeError( + "coordinator sources changed during the sample; discard its timings" + ) + return { + "scope": "complete read-only committed candidate; no reconciliation authority", + "cprofile_enabled": not args.no_profile, + "reference_validation_performed": args.reference_oracle, + "reference_result": "accepted" if args.reference_oracle else None, + "reconciliation_authorized": False, + "tokens_produced": 0, + "implementation_files": expected, + "retained_claims": args.claims, + "current_plans": args.plans, + "layout": { + "targets_per_plan": args.targets_per_plan, + "shared_build_root": args.shared_build_root, + "existing_directories": args.existing_directories, + }, + "setup_wall_seconds": setup_wall, + "setup_cpu_seconds": setup_cpu, + "lock_preparation_and_wait_seconds": lock_seconds, + "current_plan_validation_seconds": current_seconds, + "committed_candidate_wall_seconds": committed_seconds, + "committed_candidate_cpu_seconds": committed_cpu, + "all_candidate_validation_wall_seconds": total_seconds, + "all_candidate_validation_cpu_seconds": total_cpu_seconds, + "reference_oracle_wall_seconds": oracle_wall, + "reference_oracle_cpu_seconds": oracle_cpu, + "candidate_filesystem_calls": _filesystem_counts(profile) + if not args.no_profile + else None, + "index_experiment": metrics, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--claims", type=int, default=64) + parser.add_argument("--plans", type=int, default=11) + parser.add_argument("--repeat", type=int, default=1) + parser.add_argument("--large", action="store_true") + parser.add_argument("--work", type=Path) + parser.add_argument("--targets-per-plan", type=int, default=1) + parser.add_argument("--shared-build-root", action="store_true") + parser.add_argument("--existing-directories", action="store_true") + parser.add_argument("--reference-oracle", action="store_true") + parser.add_argument( + "--no-profile", + action="store_true", + help="use wall/CPU timers and native counters without cProfile overhead", + ) + args = parser.parse_args() + if not 0 <= args.claims <= 4096 or not 1 <= args.plans <= 32: + parser.error("expected 0..4096 claims and 1..32 plans") + if args.claims > 128 and not args.large: + parser.error("more than 128 claims requires explicit --large opt-in") + if not 1 <= args.repeat <= 20 or not 1 <= args.targets_per_plan <= 8: + parser.error("expected 1..20 repetitions and 1..8 targets per plan") + if args.work: + work = args.work.absolute() + work.mkdir(parents=True, exist_ok=False) + else: + work = Path(tempfile.mkdtemp(prefix="protocyte-observation-commit-")) + module = _load(Path(__file__).resolve().parents[1], "commit_candidate_only") + results = { + "platform": platform.system(), + "python": platform.python_version(), + "timings_include_instrumentation": True, + "implementation_files": _implementation_fingerprint(module), + "samples": [], + } + print(f"Private synthetic work and path-free results: {work}", flush=True) + for repetition in range(args.repeat): + measured = { + "repetition": repetition, + **sample(module, work / f"r{repetition}", args), + } + results["samples"].append(measured) + (work / "results.json").write_text( + json.dumps(results, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(measured), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/benchmark_output_registry.py b/tests/benchmark_output_registry.py index 260240f..5e969b2 100644 --- a/tests/benchmark_output_registry.py +++ b/tests/benchmark_output_registry.py @@ -18,11 +18,14 @@ from __future__ import annotations import argparse +import cProfile +import contextlib import hashlib import importlib.util import json import os import platform +import pstats import statistics import sys import tempfile @@ -39,45 +42,170 @@ def _load(source: Path, label: str) -> ModuleType: module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) + module._benchmark_implementation_files = _implementation_fingerprint(module) return module -def _plan(module: ModuleType, work: Path, name: str) -> Any: +def _plan( + module: ModuleType, + work: Path, + name: str, + *, + targets_per_plan: int = 1, + shared_build_root: bool = False, +) -> Any: directory = work / name - build = directory / "build" - build.mkdir(parents=True) - target = hashlib.sha256(name.encode()).hexdigest() - staging = directory / f".protocyte-generation-staging-{target}" + build = work / "shared-build" if shared_build_root else directory / "build" + directory.mkdir(parents=True, exist_ok=True) + build.mkdir(parents=True, exist_ok=shared_build_root) path = directory / "outputs.plan" def encode(value: Path | str) -> str: return os.fspath(value).encode("utf-8").hex() - path.write_text( - "\n".join( + lines = [ + module.PLAN_HEADER, + "root-hex=" + encode(directory / "generated"), + "build-root-hex=" + encode(build), + ] + for number in range(targets_per_plan): + target_name = name if number == 0 else f"{name}/target-{number}" + target = hashlib.sha256(target_name.encode()).hexdigest() + staging = directory / f".protocyte-generation-staging-{target}" + relative = ( + "sample.protocyte.hpp" if number == 0 else f"sample-{number}.protocyte.hpp" + ) + lines.extend( [ - module.PLAN_HEADER, - "root-hex=" + encode(directory / "generated"), - "build-root-hex=" + encode(build), "target=" + target + "|" + encode(staging), - "output=" + target + "|" + encode("sample.protocyte.hpp"), + "output=" + target + "|" + encode(relative), ] ) - + "\n", - encoding="ascii", - ) + path.write_text("\n".join(lines) + "\n", encoding="ascii") return module.Plan.read(path) -def _sample(module: ModuleType, work: Path, claims: int, plans: int) -> dict[str, Any]: - engine = module.OutputCoordinator(work / "isolated-registry") - retained = [_plan(module, work, f"retained-{i:04}") for i in range(claims)] - current = [_plan(module, work, f"current-{i:04}") for i in range(plans)] +def _implementation_fingerprint(module: ModuleType) -> dict[str, str]: + paths = [Path(module.__file__)] + for name in ( + "ProtocyteOwnershipIndex.py", + "ProtocytePathObservation.py", + "ProtocyteObservationCommit.py", + ): + helper = paths[0].with_name(name) + if helper.is_file(): + paths.append(helper) + return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in paths} + + +def _filesystem_counts(profile: cProfile.Profile) -> dict[str, int]: + filesystem_calls = {} + for (_, _, name), (_, calls, _, _, _) in pstats.Stats(profile).stats.items(): + for operation in ( + "nt.stat", + "nt.lstat", + "nt._getfinalpathname", + "nt._path_lexists", + "posix.stat", + "posix.lstat", + ): + if name == f"": + filesystem_calls[operation] = calls + if name == "_windows_file_attributes": + # ctypes native calls are opaque to cProfile. Include their probe + # helper; replacing lstat does not eliminate filesystem queries. + filesystem_calls["windows_attribute_probes"] = calls + return filesystem_calls + + +def _prepare_fixture( + module: ModuleType, + work: Path, + claims: int, + plans: int, + *, + registry_validation: str = "reference", + targets_per_plan: int = 1, + shared_build_root: bool = False, + existing_directories: bool = False, +) -> tuple[Any, list[Any], float, float]: wall, cpu = time.perf_counter(), time.process_time() - if retained: - engine.reconcile_set((), retained) + work.mkdir(parents=True, exist_ok=False) + engine = ( + module.OutputCoordinator(work / "isolated-registry") + if registry_validation == "reference" + else module.OutputCoordinator( + work / "isolated-registry", registry_validation=registry_validation + ) + ) + layout = { + "targets_per_plan": targets_per_plan, + "shared_build_root": shared_build_root, + } + retained = [ + _plan(module, work, f"retained-{i:04}", **layout) for i in range(claims) + ] + current = [_plan(module, work, f"current-{i:04}", **layout) for i in range(plans)] + if existing_directories: + for plan in (*retained, *current): + plan.root.mkdir() + for target in plan.targets: + target.staging.mkdir() + # Setup only, as in issue #54's POC. Seed disjoint synthetic fixtures through + # the real private locked helpers, avoiding all-pairs fixture validation. + # The measured reconcile_set below is unchanged and skips no checks. + module._durable_mkdir(engine.lock_root) + reporter = ( + module._ReconcileProgress(plans, 0) + if hasattr(module, "_ReconcileProgress") + else contextlib.nullcontext(None) + ) + with reporter as progress, module.FileLock(engine.lock_root / "registry.lock"): + if progress is not None: + progress.phase( + f"fixture setup (0/{claims} claims seeded)", "reconciliation" + ) + for number, plan in enumerate(retained, start=1): + with ( + module.FileLock(engine._generation_lock(plan.root)), + module.FileLock(engine._publication_lock(plan.root)), + ): + state = engine._state_directory(plan.root) + engine._initialize_claim_locked(state, plan) + engine._reconcile_locked(state, plan) + if progress is not None: + progress.phase( + f"fixture setup ({number}/{claims} claims seeded)", "reconciliation" + ) seed_wall = time.perf_counter() - wall seed_cpu = time.process_time() - cpu + return engine, current, seed_wall, seed_cpu + + +def _sample( + module: ModuleType, + work: Path, + claims: int, + plans: int, + *, + registry_validation: str = "reference", + targets_per_plan: int = 1, + shared_build_root: bool = False, + existing_directories: bool = False, +) -> dict[str, Any]: + expected_sources = getattr(module, "_benchmark_implementation_files", None) + if expected_sources is None: + expected_sources = _implementation_fingerprint(module) + engine, current, seed_wall, seed_cpu = _prepare_fixture( + module, + work, + claims, + plans, + registry_validation=registry_validation, + targets_per_plan=targets_per_plan, + shared_build_root=shared_build_root, + existing_directories=existing_directories, + ) counts = { "registry_validations": 0, "registry_scans": 0, @@ -86,20 +214,51 @@ def _sample(module: ModuleType, work: Path, claims: int, plans: int) -> dict[str "path_projections_total": 0, } active = False + profile = cProfile.Profile() validation_wall = validation_cpu = 0.0 original_validate = engine._validate_registry original_load = engine._load_recorded_plan original_project = module.project_path original_scandir = module.os.scandir + original_lock = module.FileLock + original_current_validate = engine._validate_plan_set + lock_wait = registry_held = current_validation = 0.0 + + class TimedLock(original_lock): + def __enter__(self) -> Any: + nonlocal lock_wait + started = time.perf_counter() + result = super().__enter__() + self._acquired = time.perf_counter() + lock_wait += self._acquired - started + return result + + def __exit__(self, *args: Any) -> None: + nonlocal registry_held + try: + super().__exit__(*args) + finally: + if self.path == engine.lock_root / "registry.lock": + registry_held += time.perf_counter() - self._acquired + + def validate_current(*args: Any, **kwargs: Any) -> Any: + nonlocal current_validation + started = time.perf_counter() + try: + return original_current_validate(*args, **kwargs) + finally: + current_validation += time.perf_counter() - started def validate(*args: Any, **kwargs: Any) -> Any: nonlocal active, validation_wall, validation_cpu counts["registry_validations"] += 1 active = True start_wall, start_cpu = time.perf_counter(), time.process_time() + profile.enable() try: return original_validate(*args, **kwargs) finally: + profile.disable() validation_wall += time.perf_counter() - start_wall validation_cpu += time.process_time() - start_cpu active = False @@ -124,25 +283,63 @@ def scandir(path: Any) -> Any: engine._load_recorded_plan = load module.project_path = project module.os.scandir = scandir + module.FileLock = TimedLock + engine._validate_plan_set = validate_current wall, cpu = time.perf_counter(), time.process_time() try: tokens = engine.reconcile_set((), current) reconcile_wall = time.perf_counter() - wall reconcile_cpu = time.process_time() - cpu finally: + engine._validate_registry = original_validate + engine._load_recorded_plan = original_load + engine._validate_plan_set = original_current_validate + module.FileLock = original_lock module.project_path = original_project module.os.scandir = original_scandir assert len(tokens) == plans and all(tokens) + if _implementation_fingerprint(module) != expected_sources: + raise RuntimeError( + "coordinator sources changed during the sample; discard its timings" + ) + filesystem_calls = _filesystem_counts(profile) return { "retained_claims": claims, "current_plans": plans, + "layout": { + "targets_per_plan": targets_per_plan, + "shared_build_root": shared_build_root, + "existing_directories": existing_directories, + }, "seed_wall_seconds": seed_wall, "seed_cpu_seconds": seed_cpu, "validation_wall_seconds": validation_wall, "validation_cpu_seconds": validation_cpu, "reconcile_wall_seconds": reconcile_wall, "reconcile_cpu_seconds": reconcile_cpu, - **counts, + "lock_wait_wall_seconds": lock_wait, + "registry_lock_held_wall_seconds": registry_held, + "current_plan_validation_wall_seconds": current_validation, + "validation_engine": registry_validation, + "python_registry_scans": counts["registry_scans"], + "native_registry_inventory_scans": getattr( + engine, "validation_metrics", {} + ).get("commit_full_inventory_scans", 0), + "index_experiment": getattr(engine, "validation_metrics", {}), + "shadow_candidate_wall_seconds": getattr(engine, "validation_metrics", {}).get( + "preview_wall_seconds", 0.0 + ), + "reference_validation_wall_seconds": getattr( + engine, "validation_metrics", {} + ).get("reference_wall_seconds", validation_wall), + **{ + **counts, + "registry_scans": counts["registry_scans"] + + getattr(engine, "validation_metrics", {}).get( + "commit_full_inventory_scans", 0 + ), + }, + "validation_filesystem_calls": filesystem_calls, "completed_plans": len(tokens), } @@ -157,13 +354,30 @@ def main() -> None: parser.add_argument("--plans", type=int, nargs="+", default=[1, 4]) parser.add_argument("--repeat", type=int, default=3) parser.add_argument("--work", type=Path) + parser.add_argument("--targets-per-plan", type=int, default=1) + parser.add_argument("--shared-build-root", action="store_true") + parser.add_argument("--existing-directories", action="store_true") + parser.add_argument( + "--registry-validation", + choices=("reference", "shadow", "native-shadow", "commit-shadow"), + default="reference", + ) + parser.add_argument( + "--large", + action="store_true", + help="opt into 129..4096 retained claims (setup and validation may take minutes)", + ) args = parser.parse_args() if ( - any(not 0 <= value <= 500 for value in args.claims) - or any(not 1 <= value <= 16 for value in args.plans) + any(not 0 <= value <= 4096 for value in args.claims) + or any(not 1 <= value <= 32 for value in args.plans) or not 1 <= args.repeat <= 20 ): - parser.error("expected 0..500 claims, 1..16 plans, and 1..20 repetitions") + parser.error("expected 0..4096 claims, 1..32 plans, and 1..20 repetitions") + if max(args.claims) > 128 and not args.large: + parser.error("more than 128 claims requires explicit --large opt-in") + if not 1 <= args.targets_per_plan <= 8: + parser.error("expected 1..8 targets per plan") sources = {"candidate": args.source.resolve()} if args.baseline_source: sources = {"baseline": args.baseline_source.resolve(), **sources} @@ -177,12 +391,18 @@ def main() -> None: work = Path(tempfile.mkdtemp(prefix="protocyte-registry-benchmark-")) modules = {label: _load(source, label) for label, source in sources.items()} result: dict[str, Any] = { - "platform": platform.platform(), + "platform": platform.system(), "python": platform.python_version(), + "timings_include_instrumentation": True, + "setup_method": "private locked initialization/reconciliation (issue #54 POC)", "coordinator_sha256": { label: hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest() for label, module in modules.items() }, + "implementation_files": { + label: _implementation_fingerprint(module) + for label, module in modules.items() + }, "samples": [], "medians": [], } @@ -208,7 +428,18 @@ def main() -> None: sample = { "revision": label, "repetition": repetition, - **_sample(modules[label], sample_work, claims, plans), + **_sample( + modules[label], + sample_work, + claims, + plans, + registry_validation=args.registry_validation + if label == "candidate" + else "reference", + targets_per_plan=args.targets_per_plan, + shared_build_root=args.shared_build_root, + existing_directories=args.existing_directories, + ), } result["samples"].append(sample) print(json.dumps(sample), flush=True) diff --git a/tests/benchmark_ownership_preview.py b/tests/benchmark_ownership_preview.py new file mode 100644 index 0000000..e4456d7 --- /dev/null +++ b/tests/benchmark_ownership_preview.py @@ -0,0 +1,128 @@ +"""Read-only sampled-index experiment, NOT an authoritative validation benchmark. + +Uses the standard scaling benchmark's isolated fixture setup and ordinary locks. +Only the unverified preview algorithm is measured: no reference validation, +reconciliation or publication is performed after seeding. Preview timings cannot +be reported as a complete reconciler speedup. Publish only results.json, never +fixture directories or claim records containing local paths. +""" + +from __future__ import annotations + +import argparse +import cProfile +import contextlib +import json +import platform +import tempfile +import time +from pathlib import Path + +from benchmark_output_registry import ( + _filesystem_counts, + _implementation_fingerprint, + _load, + _prepare_fixture, +) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--claims", type=int, default=64) + parser.add_argument("--plans", type=int, default=11) + parser.add_argument("--large", action="store_true") + parser.add_argument("--work", type=Path) + parser.add_argument("--targets-per-plan", type=int, default=1) + parser.add_argument("--shared-build-root", action="store_true") + parser.add_argument("--existing-directories", action="store_true") + args = parser.parse_args() + if not 0 <= args.claims <= 4096 or not 1 <= args.plans <= 32: + parser.error("expected 0..4096 claims and 1..32 plans") + if args.claims > 128 and not args.large: + parser.error("more than 128 claims requires explicit --large opt-in") + if not 1 <= args.targets_per_plan <= 8: + parser.error("expected 1..8 targets per plan") + if args.work: + work = args.work.absolute() + work.mkdir(parents=True, exist_ok=False) + else: + work = Path(tempfile.mkdtemp(prefix="protocyte-index-preview-")) + module = _load(Path(__file__).resolve().parents[1], "preview_only") + implementation_files = _implementation_fingerprint(module) + engine, current, setup_wall, setup_cpu = _prepare_fixture( + module, + work / "sample", + args.claims, + args.plans, + targets_per_plan=args.targets_per_plan, + shared_build_root=args.shared_build_root, + existing_directories=args.existing_directories, + ) + profile = cProfile.Profile() + started = time.perf_counter() + with ( + module._ReconcileProgress(len(current), 0) as progress, + contextlib.ExitStack() as locks, + ): + progress.phase("waiting for preview locks", "lock_wait") + locks.enter_context(module.FileLock(engine.lock_root / "registry.lock")) + roots = {module._path_key(plan.root): plan.root for plan in current} + for root in sorted(roots.values(), key=module._portable_identity): + locks.enter_context(module.FileLock(engine._generation_lock(root))) + for root in sorted(roots.values(), key=module._portable_identity): + locks.enter_context(module.FileLock(engine._publication_lock(root))) + lock_seconds = time.perf_counter() - started + progress.phase("checking current plans for read-only preview", "validation") + started = time.perf_counter() + engine._validate_plan_set(current) + current_seconds = time.perf_counter() - started + engine.validation_metrics = {"mode": "preview-only", "authoritative": "none"} + progress.phase("read-only experimental ownership preview", "validation") + started, cpu = time.perf_counter(), time.process_time() + profile.enable() + try: + accepted = engine._preview_registry_index(current, set(), progress=progress) + finally: + profile.disable() + preview_seconds = time.perf_counter() - started + preview_cpu = time.process_time() - cpu + assert accepted and engine.validation_metrics["preview_claims"] == args.claims + assert engine.validation_metrics["preview_records_read"] == 2 * args.claims + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == args.claims + if _implementation_fingerprint(module) != implementation_files: + raise RuntimeError( + "coordinator sources changed during the preview; discard its timings" + ) + result = { + "scope": "read-only sampled algorithm; NOT reference verified or authorized", + "reference_validation_performed": False, + "reconciliation_authorized": False, + "tokens_produced": 0, + "platform": platform.system(), + "python": platform.python_version(), + "implementation_files": implementation_files, + "timings_include_instrumentation": True, + "retained_claims": args.claims, + "current_plans": args.plans, + "layout": { + "targets_per_plan": args.targets_per_plan, + "shared_build_root": args.shared_build_root, + "existing_directories": args.existing_directories, + }, + "setup_wall_seconds": setup_wall, + "setup_cpu_seconds": setup_cpu, + "lock_preparation_and_wait_seconds": lock_seconds, + "current_plan_validation_seconds": current_seconds, + "preview_wall_seconds": preview_seconds, + "preview_cpu_seconds": preview_cpu, + "preview_filesystem_calls": _filesystem_counts(profile), + "index_experiment": engine.validation_metrics, + } + (work / "results.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..563b475 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,84 @@ +"""Keep integration fixtures out of the user's shared ownership registry.""" + +from __future__ import annotations + +import os +import importlib.util +import sys +from pathlib import Path + +import pytest + + +_lock_module = None +_quiet_observer_files = { + "test_output_coordinator.py", + "test_ownership_index.py", + "test_observation_commit.py", + "test_parallel_probes.py", + "test_path_observation.py", + "test_consumer_registry_qualification.py", +} +_has_quiet_observers = True + + +@pytest.hookimpl(trylast=True) +def pytest_collection_modifyitems(items): + # Marker deselection has finished. CMake-only CI does not run quiet native + # scopes and may keep its ordinary process parallelism. Mixed invocations + # still coordinate every CLI/integration case with those native scopes. + global _has_quiet_observers + _has_quiet_observers = any( + item.path.name in _quiet_observer_files for item in items + ) + + +@pytest.fixture(autouse=True) +def quiet_registry_observers(request: pytest.FixtureRequest): + # Quiet certificate tests and default-enabled CLI subprocesses share volume + # ancestors. Serialize *test cases*, while preserving each case's deliberate + # worker/process concurrency. This does not alter production lock selection. + if ( + request.node.path.name not in _quiet_observer_files + and ( + not _has_quiet_observers + or request.node.get_closest_marker("cmake_integration") is None + ) + ): + yield + return + global _lock_module + if _lock_module is None: + source = ( + Path(__file__).resolve().parents[1] / "cmake/ProtocyteOutputCoordinator.py" + ) + spec = importlib.util.spec_from_file_location( + "protocyte_test_observer_lock", source + ) + assert spec and spec.loader + _lock_module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = _lock_module + exec(compile(source.read_bytes(), str(source), "exec"), _lock_module.__dict__) + base = request.getfixturevalue("tmp_path_factory").getbasetemp() + if getattr(request.config, "workerinput", None) is not None: + base = base.parent + with _lock_module.FileLock(base / "observation-commit-tests.lock"): + yield + + +@pytest.fixture(autouse=True) +def isolated_cmake_registry_cache( + request: pytest.FixtureRequest, +) -> None: + if request.node.get_closest_marker("cmake_integration") is None: + return + # Ownership fixtures already supply explicit lock roots. Older configure + # fixtures exercise the default selector; give that selector a private base + # too. All subprocesses/build trees in one test still share one namespace. + tmp_path: Path = request.getfixturevalue("tmp_path") + monkeypatch: pytest.MonkeyPatch = request.getfixturevalue("monkeypatch") + cache = tmp_path / "isolated-user-cache" + cache.mkdir() + monkeypatch.setenv( + "LOCALAPPDATA" if os.name == "nt" else "XDG_CACHE_HOME", str(cache) + ) diff --git a/tests/profile_output_registry.py b/tests/profile_output_registry.py new file mode 100644 index 0000000..f129cab --- /dev/null +++ b/tests/profile_output_registry.py @@ -0,0 +1,132 @@ +"""Offline, disjoint registry phase timings using fresh synthetic fixtures. + +Python 3.12+, stdlib only. This reuses benchmark_output_registry's real locked +fixture seeding and unchanged measured reconcile_set operation. Timers delegate +every check; nested calls belong only to their outermost measured phase. +Publish results.json only, never synthetic claim records or fixture directories. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import tempfile +import time +from pathlib import Path +from types import ModuleType +from typing import Any + +from benchmark_output_registry import _load, _sample + + +def profile(module: ModuleType, work: Path, claims: int, plans: int) -> dict[str, Any]: + phase: str | None = None + partition: dict[str, dict[str, float | int]] = {} + + def measured(name: str, original: Any, *args: Any, **kwargs: Any) -> Any: + nonlocal phase + if phase != "registry": + return original(*args, **kwargs) + started = time.perf_counter() + phase = name + try: + return original(*args, **kwargs) + finally: + row = partition.setdefault(name, {"calls": 0, "wall_seconds": 0.0}) + row["calls"] += 1 + row["wall_seconds"] += time.perf_counter() - started + phase = "registry" + + original_engine = module.OutputCoordinator + original_claim_paths = original_engine._claim_paths + originals = { + name: getattr(module, name) + for name in ("_load_json", "_paths_overlap", "_path_key", "project_path") + } + + class InstrumentedEngine(original_engine): + def _validate_registry(self, *args: Any, **kwargs: Any) -> Any: + nonlocal phase + previous, phase = phase, "registry" + try: + return super()._validate_registry(*args, **kwargs) + finally: + phase = previous + + def _load_recorded_plan(self, *args: Any, **kwargs: Any) -> Any: + return measured( + "recorded_plan_authentication", + super()._load_recorded_plan, + *args, + **kwargs, + ) + + def claim_paths(*args: Any, **kwargs: Any) -> Any: + return measured( + "claim_path_authentication", original_claim_paths, *args, **kwargs + ) + + original_engine._claim_paths = staticmethod(claim_paths) + module.OutputCoordinator = InstrumentedEngine + for name, original in originals.items(): + + def wrapper( + *args: Any, _name: str = name, _original: Any = original, **kwargs: Any + ) -> Any: + return measured(_name, _original, *args, **kwargs) + + setattr(module, name, wrapper) + try: + sample = _sample(module, work / "sample", claims, plans) + finally: + original_engine._claim_paths = staticmethod(original_claim_paths) + module.OutputCoordinator = original_engine + for name, original in originals.items(): + setattr(module, name, original) + # These counters confirm that the post-#52 measured scan still authenticates + # every retained claim/plan. Instrumentation never skips foreign records. + for name in ( + "recorded_plan_authentication", + "claim_path_authentication", + "_load_json", + ): + assert partition.get(name, {}).get("calls", 0) == claims + return {"sample": sample, "disjoint_direct_registry_phases": partition} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--claims", type=int, default=64) + parser.add_argument("--plans", type=int, default=11) + parser.add_argument("--work", type=Path) + args = parser.parse_args() + if not 0 <= args.claims <= 128 or not 1 <= args.plans <= 32: + parser.error( + "expected 0..128 claims and 1..32 plans; use the scaling benchmark for larger runs" + ) + if args.work: + work = args.work.absolute() + work.mkdir(parents=True, exist_ok=False) + else: + work = Path(tempfile.mkdtemp(prefix="protocyte-registry-phases-")) + module = _load(Path(__file__).resolve().parents[1], "phases") + result = { + "platform": platform.system(), + "python": platform.python_version(), + "coordinator_sha256": hashlib.sha256( + Path(module.__file__).read_bytes() + ).hexdigest(), + "timings_include_instrumentation": True, + "measurement": "Disjoint outermost function timers; every check delegates unchanged", + **profile(module, work, args.claims, args.plans), + } + (work / "results.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/registry_validation_poc.py b/tests/registry_validation_poc.py new file mode 100644 index 0000000..852cce2 --- /dev/null +++ b/tests/registry_validation_poc.py @@ -0,0 +1,303 @@ +"""Standalone output-registry scaling/progress POC; Python 3.12+, stdlib only. + +Run from a Protocyte checkout. All state lives in a NEW synthetic workspace; +the default/shared registry and source checkout are never modified. +Fixtures are retained locally. Publish only this script and results.json, +not the synthetic claim files (which necessarily contain local paths). + +From issue #54. The measured sample method is unchanged. Progress metadata +supports a reporter without a lifetime cap; the encoding lambda is spelled as +a function for repository lint. The original issue remains the baseline source. +Counters also include optional Windows attribute probes and native existence +queries so cheaper metadata cannot masquerade as eliminating FS observations. +""" + +from __future__ import annotations + +import argparse +import contextlib +import cProfile +import hashlib +import importlib.util +import io +import json +import os +import platform +import pstats +import re +import sys +import tempfile +import time +from pathlib import Path + + +def load(path): + spec = importlib.util.spec_from_file_location("coordinator_poc", path) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def plan(module, work, name): + directory = work / name + build = directory / "build" + build.mkdir(parents=True) + root = directory / "generated" + target = hashlib.sha256(name.encode()).hexdigest() + staging = directory / (".protocyte-generation-staging-" + target) + + def encoded(value): + return os.fspath(value).encode("utf-8").hex() + + path = directory / "outputs.plan" + path.write_text( + "\n".join( + [ + module.PLAN_HEADER, + "root-hex=" + encoded(root), + "build-root-hex=" + encoded(build), + "target=" + target + "|" + encoded(staging), + "output=" + target + "|" + encoded("sample.protocyte.hpp"), + ] + ) + + "\n", + encoding="ascii", + ) + return module.Plan.read(path) + + +def sample( + module, work, retained_count, current_count, registry_validation="reference" +): + setup_start = time.perf_counter() + retained = [plan(module, work, "retained-%04d" % i) for i in range(retained_count)] + current = [plan(module, work, "current-%04d" % i) for i in range(current_count)] + engine = ( + module.OutputCoordinator(work / "isolated-registry") + if registry_validation == "reference" + else module.OutputCoordinator( + work / "isolated-registry", registry_validation=registry_validation + ) + ) + + # Fixture seeding only: avoid quadratic conflict comparisons during setup. + # Use real initialization/reconciliation helpers under PRIVATE locks. + # No method is replaced during seeding; all roots/targets are disjoint. + module._durable_mkdir(engine.lock_root) + with module.FileLock(engine.lock_root / "registry.lock"): + for item in retained: + with ( + module.FileLock(engine._generation_lock(item.root)), + module.FileLock(engine._publication_lock(item.root)), + ): + state = engine._state_directory(item.root) + engine._initialize_claim_locked(state, item) + engine._reconcile_locked(state, item) + setup_seconds = time.perf_counter() - setup_start + + active = False + counts = {} + originals = {} + profile = cProfile.Profile() + validation_wall = validation_cpu = 0.0 + original_validate = engine._validate_registry + + def validate(*args, **kwargs): + nonlocal active, validation_wall, validation_cpu + counts["registry_validations"] = counts.get("registry_validations", 0) + 1 + active = True + wall, cpu = time.perf_counter(), time.process_time() + profile.enable() + try: + return original_validate(*args, **kwargs) + finally: + profile.disable() + validation_wall += time.perf_counter() - wall + validation_cpu += time.process_time() - cpu + active = False + + names = ( + "project_path", + "_paths_overlap", + "_path_key", + "_physical_location_key", + "_same_physical_path", + "_windows_file_attributes", + ) + for name in names: + if not hasattr(module, name): + continue + original = getattr(module, name) + originals[name] = original + + def counted(*args, _name=name, _original=original, **kwargs): + if active: + counts[_name] = counts.get(_name, 0) + 1 + return _original(*args, **kwargs) + + setattr(module, name, counted) + engine._validate_registry = validate + wall, cpu = time.perf_counter(), time.process_time() + try: + # This is the measured production operation, with every check, + # filesystem call, and lock delegated unchanged. + tokens = engine.reconcile_set((), current) + finally: + reconcile_wall = time.perf_counter() - wall + reconcile_cpu = time.process_time() - cpu + engine._validate_registry = original_validate + for name, original in originals.items(): + setattr(module, name, original) + assert len(tokens) == current_count and all(tokens) + + filesystem = {} + for (_, _, name), (_, calls, own, _, _) in pstats.Stats(profile).stats.items(): + for operation in ( + "nt.stat", + "nt.lstat", + "nt._getfinalpathname", + "nt._path_lexists", + ): + if name == "" % operation: + filesystem[operation] = { + "calls": calls, + "own_seconds": round(own, 6), + } + if name == "_windows_file_attributes": + filesystem["windows_attribute_probes"] = { + "calls": calls, + "own_seconds": round(own, 6), + } + return { + "retained_claims": retained_count, + "current_plans": current_count, + "setup_seconds": round(setup_seconds, 6), + "validation_wall_seconds": round(validation_wall, 6), + "validation_cpu_seconds": round(validation_cpu, 6), + "reconcile_wall_seconds": round(reconcile_wall, 6), + "reconcile_cpu_seconds": round(reconcile_cpu, 6), + "validation_operation_counts": counts, + "validation_filesystem_calls": filesystem, + "completed_plans": len(tokens), + "validation_engine": registry_validation, + "index_experiment": getattr(engine, "validation_metrics", {}), + } + + +def progress_demo(module): + """Demonstrate the cutoff quickly; only the reporting interval is scaled.""" + original_interval = module._ReconcileProgress.INTERVAL_SECONDS + max_reports = getattr(module._ReconcileProgress, "MAX_REPORTS", None) + stream = io.StringIO() + try: + module._ReconcileProgress.INTERVAL_SECONDS = 0.01 + with contextlib.redirect_stderr(stream): + with module._ReconcileProgress(1, 0) as progress: + progress.phase("validating registry", "validation") + progress.registry(states=100) + for _ in range(40): + progress.registry(claim=True) + time.sleep(0.01) + finally: + module._ReconcileProgress.INTERVAL_SECONDS = original_interval + lines = stream.getvalue().splitlines() + periodic = [line for line in lines if ": complete;" not in line] + last = periodic[-1] if periodic else "" + match = re.search(r"claims_checked=(\d+)", last) + return { + "production_interval_seconds": original_interval, + "production_max_periodic_reports": max_reports, + "nominal_production_cutoff_seconds": ( + original_interval * max_reports if max_reports is not None else None + ), + "demo_interval_seconds": 0.01, + "periodic_reports": len(periodic), + "claims_at_last_periodic_report": int(match[1]) if match else None, + "claims_at_completion": progress._claims, + "suppression_message_seen": "further progress suppressed" in last, + "completion_message_seen": any(": complete;" in line for line in lines), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--coordinator", + type=Path, + default=Path("cmake/ProtocyteOutputCoordinator.py"), + ) + parser.add_argument("--claims", type=int, nargs="+", default=[0, 8, 16]) + parser.add_argument("--plans", type=int, nargs="+", default=[1, 11]) + parser.add_argument("--repeat", type=int, default=1) + parser.add_argument("--work", type=Path) + parser.add_argument( + "--registry-validation", + choices=("reference", "shadow", "native-shadow", "commit-shadow"), + default="reference", + ) + args = parser.parse_args() + if ( + any(not 0 <= n <= 4096 for n in args.claims) + or any(not 1 <= n <= 32 for n in args.plans) + or not 1 <= args.repeat <= 10 + ): + parser.error("expected 0..4096 claims, 1..32 plans, 1..10 repetitions") + source = args.coordinator.resolve(strict=True) + module = load(source) + if args.work: + root = args.work.absolute() + root.mkdir(parents=True, exist_ok=False) + else: + root = Path(tempfile.mkdtemp(prefix="protocyte-registry-poc-")) + root = root.resolve(strict=True) + result = { + "os": platform.system(), + "python": platform.python_version(), + "coordinator_sha256": hashlib.sha256(source.read_bytes()).hexdigest(), + "implementation_files": { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in ( + source, + source.with_name("ProtocyteOwnershipIndex.py"), + source.with_name("ProtocytePathObservation.py"), + source.with_name("ProtocyteObservationCommit.py"), + ) + if path.is_file() + }, + "timings_include_instrumentation": True, + "samples": [], + } + for repetition in range(args.repeat): + for claims in args.claims: + for plans in args.plans: + work = root / ("r%d-c%d-p%d" % (repetition, claims, plans)) + row = { + "repetition": repetition, + **sample(module, work, claims, plans, args.registry_validation), + } + observed_files = { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in ( + source, + source.with_name("ProtocyteOwnershipIndex.py"), + source.with_name("ProtocytePathObservation.py"), + source.with_name("ProtocyteObservationCommit.py"), + ) + if path.is_file() + } + if observed_files != result["implementation_files"]: + raise RuntimeError( + "coordinator sources changed during the POC; discard timings" + ) + result["samples"].append(row) + print(json.dumps(row), flush=True) + result["progress_demo"] = progress_demo(module) + (root / "results.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(result["progress_demo"]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/test_consumer_registry_qualification.py b/tests/test_consumer_registry_qualification.py new file mode 100644 index 0000000..2ace4b9 --- /dev/null +++ b/tests/test_consumer_registry_qualification.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import importlib.util +import itertools +import json +import sys +from pathlib import Path + +import pytest + +_spec = importlib.util.spec_from_file_location( + "consumer_qualification_helpers", + Path(__file__).with_name("test_output_coordinator.py"), +) +assert _spec is not None and _spec.loader is not None +helpers = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = helpers +_spec.loader.exec_module(helpers) +_spec = importlib.util.spec_from_file_location( + "consumer_qualification_driver", + Path(__file__).with_name("verify_consumer_registry.py"), +) +assert _spec is not None and _spec.loader is not None +driver = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = driver +_spec.loader.exec_module(driver) +_modules = itertools.count() + + +def seeded(tmp_path: Path): + module = driver.load( + Path(__file__).resolve().parents[1] / "cmake/ProtocyteOutputCoordinator.py", + f"consumer_qualification_fixture_{next(_modules)}", + ) + input_file = tmp_path / "consumer.plan" + root, build = tmp_path / "generated", tmp_path / "build" + target = helpers._target("consumer-qualification") + helpers._write_plan(input_file, root, build, ((target, "sample.protocyte.hpp"),)) + plan = module.Plan.read(input_file) + engine = module.OutputCoordinator( + tmp_path / "registry", registry_validation="reference" + ) + token = engine.reconcile(plan) + stage = plan.staging_for_target(target) / "generated" + helpers._stage(stage, "sample.protocyte.hpp", b"// original generated file\n") + engine.publish(plan, target, stage) + manifest = { + "registry": str(engine.lock_root), + "current_plans": [str(input_file)], + "retired_plans": [], + } + work = tmp_path / "qualification" + work.mkdir() + return module, engine, plan, target, token, manifest, work + + +def test_capture_and_reference_keep_original_data_and_redact_receipt( + tmp_path: Path, +) -> None: + module, engine, plan, _, token, manifest, work = seeded(tmp_path) + original = driver.ledger(engine.lock_root) + output = plan.root / "sample.protocyte.hpp" + before = output.read_bytes(), output.stat().st_mtime_ns + receipt = driver.capture(module, manifest, work) + checked = driver.reference(module, manifest, work) + assert checked["result"] == "accepted" and checked["claims_checked"] == 1 + assert receipt["committed_output_files_checked"] == 1 + assert receipt["claims_plans_snapshots_and_outputs_unchanged"] + assert driver.ledger(engine.lock_root) == original + assert (output.read_bytes(), output.stat().st_mtime_ns) == before + serialized = json.dumps({"capture": receipt, "reference": checked}) + assert str(tmp_path) not in serialized and token not in serialized + with pytest.raises(RuntimeError, match="ownership/output mutation"): + module._atomic_write(output, b"forbidden") + with pytest.raises(RuntimeError, match="ownership/output mutation"): + engine.reconcile(plan) + assert output.read_bytes() == before[0] + + +def test_frozen_reference_preserves_original_lock_namespace_rejection( + tmp_path: Path, +) -> None: + module, engine, _, _, _, manifest, work = seeded(tmp_path) + driver.capture(module, manifest, work) + dangerous = work / "inputs/000.plan" + helpers._write_plan( + dangerous, + engine.lock_root / "unsafe-generated", + tmp_path / "other-build", + ((helpers._target("unsafe-namespace"), "sample.protocyte.hpp"),), + ) + with pytest.raises(module.CoordinatorError, match="lock namespace"): + driver.reference(module, manifest, work) + + +def test_frozen_reference_checks_foreign_staging_reservations(tmp_path: Path) -> None: + module, _, plan, target, _, manifest, work = seeded(tmp_path) + driver.capture(module, manifest, work) + helpers._write_plan( + work / "inputs/000.plan", + plan.staging_for_target(target) / "intruder", + tmp_path / "intruder-build", + ((helpers._target("intruder"), "sample.protocyte.hpp"),), + ) + with pytest.raises(module.CoordinatorError, match="staging reserved"): + driver.reference(module, manifest, work) + + +def test_capture_rejects_output_corruption_without_repairing_it(tmp_path: Path) -> None: + module, engine, plan, _, _, manifest, work = seeded(tmp_path) + output = plan.root / "sample.protocyte.hpp" + output.write_bytes(b"// externally changed\n") + before = driver.ledger(engine.lock_root) + with pytest.raises(AssertionError, match="differs from committed snapshot"): + driver.capture(module, manifest, work) + assert output.read_bytes() == b"// externally changed\n" + assert driver.ledger(engine.lock_root) == before + + +def test_capture_rejects_foreign_state_link_before_copying_ledger( + tmp_path: Path, +) -> None: + module, engine, _, _, _, manifest, work = seeded(tmp_path) + path = tmp_path / "foreign.plan" + helpers._write_plan( + path, + tmp_path / "foreign-generated", + tmp_path / "foreign-build", + ((helpers._target("foreign"), "foreign.protocyte.hpp"),), + ) + foreign = module.Plan.read(path) + engine.reconcile(foreign) + state = engine._state_directory(foreign.root) + preserved = tmp_path / "preserved-foreign-state" + assert state.resolve().is_relative_to(tmp_path.resolve()) + assert preserved.resolve().is_relative_to(tmp_path.resolve()) + claim = (state / "claim.json").read_bytes() + state.rename(preserved) + helpers._directory_link(state, preserved) + with pytest.raises(AssertionError, match="unsafe source registry state"): + driver.capture(module, manifest, work) + assert (preserved / "claim.json").read_bytes() == claim + assert not (work / "ledger/roots").exists() + + +@pytest.mark.parametrize("failed_certificate", [False, True]) +def test_indexed_qualification_requires_mutation_guard_and_restores_promotion_gate( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failed_certificate: bool +) -> None: + module, engine, _, _, _, manifest, work = seeded(tmp_path) + before = driver.ledger(engine.lock_root) + qualified = module._COMMITTED_INDEX_QUALIFIED + + def certificate(self, *args, **kwargs): + assert module._COMMITTED_INDEX_QUALIFIED is True + with pytest.raises(RuntimeError, match="ownership/output mutation"): + module._atomic_write(tmp_path / "forbidden", b"forbidden") + if failed_certificate: + raise RuntimeError("test certificate could not be verified") + self.validation_metrics.update( + commit_certificate="verified", + commit_state="closed", + commit_handles_opened=1, + commit_cleanup_failed=False, + commit_handles_closed=1, + commit_claims_checked=1, + commit_probe_state="closed", + commit_probe_native_retired=True, + commit_probe_active=0, + commit_probe_pending=0, + commit_probe_comparisons=0, + commit_fresh_comparisons=0, + commit_probe_workers=4, + commit_probe_peak_active=0, + commit_probe_peak_pending=0, + ) + return True + + monkeypatch.setattr( + module.OutputCoordinator, "_preview_committed_index", certificate + ) + if failed_certificate: + with pytest.raises(RuntimeError, match="required reference fallback"): + driver.candidate(module, manifest, work, integrated=True) + else: + receipt = driver.candidate(module, manifest, work, integrated=True) + assert receipt["native_metrics"]["authoritative"] == "index" + assert module._COMMITTED_INDEX_QUALIFIED is qualified + assert driver.ledger(engine.lock_root) == before + assert not (tmp_path / "forbidden").exists() diff --git a/tests/test_observation_commit.py b/tests/test_observation_commit.py new file mode 100644 index 0000000..485e030 --- /dev/null +++ b/tests/test_observation_commit.py @@ -0,0 +1,1012 @@ +from __future__ import annotations + +import ctypes +import importlib.util +import os +import struct +import sys +from collections import defaultdict +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +spec = importlib.util.spec_from_file_location( + "observation_commit_test_helpers", + Path(__file__).with_name("test_output_coordinator.py"), +) +assert spec and spec.loader +helpers = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = helpers +spec.loader.exec_module(helpers) +coordinator = helpers.coordinator +commit = coordinator._load_observation_commit() +native = coordinator._load_path_observation() +model = coordinator._load_ownership_index() + + +@pytest.fixture(autouse=True) +def qualify_native_commit_cases(monkeypatch): + # Exercise the guarded success path only in isolated test fixtures. + monkeypatch.setattr(coordinator, "_COMMITTED_INDEX_QUALIFIED", True) + + +@pytest.fixture +def native_capability(tmp_path): + if os.name != "nt": + pytest.skip("native commit witnesses require Windows") + scope = commit.WindowsObservationCommit(native, model) + try: + scope.project(tmp_path) + scope.seal() + except commit.CapabilityUnavailable as error: + pytest.skip(str(error)) + finally: + scope.close() + + +def _record(usn: int, file_id: int, reason: int, major: int = 2) -> bytes: + minimum = 60 if major == 2 else 76 + length = (minimum + 7) & ~7 + data = bytearray(length) + struct.pack_into(" None: + page = struct.pack(" None: + scope = object.__new__(commit.WindowsObservationCommit) + scope._counts = defaultdict(int) + scope._roots = {"c:\\": SimpleNamespace(guard=SimpleNamespace(volume=77))} + scope.reader = SimpleNamespace( + _native_name=lambda path: None, _open_existing=lambda path: 123 + ) + guard = SimpleNamespace(volume=77, file_id=1 if same_root_id else 2) + monkeypatch.setattr(scope, "_adopt", lambda handle, **kwargs: (guard, Path("D:\\"))) + with pytest.raises(commit.CapabilityUnavailable, match="duplicate volume binding"): + scope._root(Path("D:/generated")) + assert list(scope._roots) == ["c:\\"] + + +@pytest.mark.parametrize("reason", [0, 1, 0x200, 0x1000, 0x8000, 0x10000, 0x100000]) +def test_close_witness_must_not_hide_pending_changes(reason: int) -> None: + flags = 0 if reason == 0 else commit.CLOSE_REASON | reason + with pytest.raises(commit.ObservationChanged): + commit.verify_witnesses({100: 11}, [commit.JournalRecord(100, 11, flags)]) + + +@pytest.mark.parametrize( + "records", + [ + [], + [commit.JournalRecord(101, 11, commit.CLOSE_REASON)], + [commit.JournalRecord(100, 12, commit.CLOSE_REASON)], + [commit.JournalRecord(100, 11, commit.CLOSE_REASON)] * 2, + ], +) +def test_missing_wrong_or_duplicate_records_cannot_certify_a_read_set(records) -> None: + with pytest.raises(commit.CommitUnavailable): + commit.verify_witnesses({100: 11}, records) + + +@pytest.mark.parametrize( + "corruption", + ["short", "truncated", "version", "minor", "length", "name", "backward", "cursor"], +) +def test_journal_parser_fails_closed_on_unsupported_or_malformed_data( + corruption: str, +) -> None: + record = bytearray(_record(100, 11, commit.CLOSE_REASON)) + cursor = 200 + if corruption == "short": + page = b"short" + elif corruption == "truncated": + page = struct.pack(" None: + scope = object.__new__(commit.WindowsObservationCommit) + scope._counts = defaultdict(int) + scope.MAX_JOURNAL_BYTES = 8 if failure == "budget" else 1024 + epochs = iter( + [ + (2 if failure == "epoch" else 1, 101 if failure == "trim" else 0, 200), + (2 if failure == "epoch-after" else 1, 0, 200), + ] + ) + scope._epoch = lambda handle: next(epochs) + records = ( + b"" + if failure in ("missing", "stalled") + else _record(100, 11, commit.CLOSE_REASON | (1 if failure == "changed" else 0)) + ) + scope._io = lambda *args: ( + struct.pack(" None: + directory = tmp_path / "existing 🧬" + directory.mkdir() + assert readset.project(directory) == directory + assert not readset.overlaps(tmp_path / "missing-a", tmp_path / "missing-b") + # Only volume roots are retained. Ordinary directory observations close now. + roots = {id(view.guard) for view in readset._roots.values()} + assert all( + guard.handle is None or id(guard) in roots + for guard in readset._objects.values() + ) + readset.seal() + assert readset.metrics()["commit_state"] == "sealed" + assert readset.metrics()["commit_witnesses"] == len(readset._objects) + with pytest.raises(commit.ObservationChanged, match="outside"): + readset.project(directory) + + +def test_existing_object_delete_and_recreate_is_not_blocked_and_invalidates( + tmp_path: Path, readset +) -> None: + directory = tmp_path / "existing" + directory.mkdir() + readset.project(directory) + directory.rmdir() + directory.mkdir() + with pytest.raises(commit.ObservationChanged): + readset.seal() + + +def test_rename_aba_cannot_pass_even_when_name_and_identity_return( + tmp_path: Path, readset +) -> None: + directory, moved = tmp_path / "existing", tmp_path / "moved" + directory.mkdir() + readset.project(directory) + directory.rename(moved) + moved.rename(directory) + with pytest.raises(commit.ObservationChanged): + readset.seal() + + +def test_record_content_aba_with_restored_timestamp_invalidates( + tmp_path: Path, readset +) -> None: + record = tmp_path / "claim.json" + data = b'{"value":1}\n' + record.write_bytes(data) + assert readset.read_json(record, "test record") == {"value": 1} + original = record.stat() + record.write_bytes(b'{"value":2}\n') + record.write_bytes(data) + os.utime(record, ns=(original.st_atime_ns, original.st_mtime_ns)) + with pytest.raises(commit.ObservationChanged): + readset.seal() + + +@pytest.mark.parametrize("timing", ["before-seal", "after-version-read"]) +def test_reparse_aba_from_a_preexisting_attribute_writer_cannot_certify( + tmp_path: Path, readset, monkeypatch: pytest.MonkeyPatch, timing: str +) -> None: + from ctypes import wintypes as w + + directory, target = tmp_path / "existing", tmp_path / "target" + directory.mkdir() + target.mkdir() + create = readset.reader._kernel.CreateFileW + create.argtypes = ( + w.LPCWSTR, + w.DWORD, + w.DWORD, + w.LPVOID, + w.DWORD, + w.DWORD, + w.HANDLE, + ) + create.restype = w.HANDLE + writer = create(str(directory), 0x100, 7, None, 3, 0x02200000, None) + assert writer != ctypes.c_void_p(-1).value + + def reparse(set_point: bool): + if set_point: + substitute = ("\\??\\" + str(target)).encode("utf-16-le") + printable = str(target).encode("utf-16-le") + names = substitute + b"\x00\x00" + printable + b"\x00\x00" + data = ( + struct.pack( + " None: + path = tmp_path / "observed" + if mutation == "rename-aba": + path.mkdir() + readset.project(path) + guard = readset._view(path).guard + else: + path.write_bytes(b'{"value":1}\n') + readset.read_json(path, "test record") + guard = readset._view(path, leaf_may_be_file=True).guard + identity = guard.volume, guard.file_id + original_version = readset._version + changed = False + + def change_after_version(handle): + nonlocal changed + version = original_version(handle) + if not changed and readset._identity(handle) == identity: + changed = True + if mutation == "rename-aba": + moved = path.with_name("moved") + path.rename(moved) + moved.rename(path) + else: + original = path.stat() + path.write_bytes(b'{"value":2}\n') + path.write_bytes(b'{"value":1}\n') + os.utime(path, ns=(original.st_atime_ns, original.st_mtime_ns)) + return version + + monkeypatch.setattr(readset, "_version", change_after_version) + with pytest.raises( + commit.ObservationChanged, match="close witness contains accumulated changes" + ): + readset.seal() + assert changed + + +@pytest.mark.parametrize("phase", ["comparison", "seal"]) +def test_missing_component_creation_is_freshly_checked( + tmp_path: Path, readset, phase: str +) -> None: + missing = tmp_path / "missing" + assert not readset.overlaps(missing, tmp_path / "other") + missing.mkdir() + with pytest.raises(commit.ObservationChanged): + readset.overlaps( + missing, tmp_path / "other" + ) if phase == "comparison" else readset.seal() + + +def test_case_aliases_fall_back_without_resetting_prior_versions( + tmp_path: Path, readset +) -> None: + directory = tmp_path / "MixedCase" + directory.mkdir() + first = readset.facts(directory) + start = readset._objects[first.location[:2]].start_usn + with pytest.raises(commit.CapabilityUnavailable, match="noncanonical"): + readset.facts(tmp_path / "mixedcase") + assert readset._objects[first.location[:2]].start_usn == start + + +def test_overlapping_read_sets_invalidate_rather_than_certify_changed_versions( + tmp_path: Path, readset +) -> None: + other = commit.WindowsObservationCommit(native, model) + try: + readset.project(tmp_path) + other.project(tmp_path) + with pytest.raises(commit.ObservationChanged): + readset.seal() + other.seal() + finally: + other.close() + + +def _plan(tmp_path: Path, name: str): + return helpers._write_plan( + tmp_path / f"{name}.plan", + tmp_path / name / "generated", + tmp_path / name / "build", + ((helpers._target(name), "sample.protocyte.hpp"),), + ) + + +@pytest.mark.parametrize("phase", ["comparison", "seal"]) +def test_dangling_junction_cannot_masquerade_as_a_missing_component( + tmp_path: Path, readset, phase: str +) -> None: + missing, target = tmp_path / "missing", tmp_path / "target" + target.mkdir() + readset.project(missing / "generated") + helpers._directory_link(missing, target) + target.rmdir() + assert missing.is_junction() + with pytest.raises(commit.ObservationChanged): + readset.overlaps( + missing / "generated", tmp_path / "other" + ) if phase == "comparison" else readset.seal() + + +def test_default_never_loads_commit_reader( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + coordinator, + "_load_observation_commit", + lambda: pytest.fail("default loaded commit reader"), + ) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + assert engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["authoritative"] == "reference" + + +def test_negative_observations_are_refreshed_for_the_reverse_direction( + tmp_path: Path, readset, monkeypatch: pytest.MonkeyPatch +) -> None: + first, second = tmp_path / "first-missing", tmp_path / "second-missing" + readset.project(first) + readset.project(second) + original = readset._probe_absence + probes = 0 + + def replace_after_forward(request): + nonlocal probes + original(request) + probes += 1 + if probes == 2: + first.touch() + + monkeypatch.setattr(readset, "_probe_absence", replace_after_forward) + with pytest.raises(commit.ObservationChanged): + readset.overlaps(first, second) + + +@pytest.mark.parametrize("restore", [False, True]) +def test_case_mode_changes_preserve_exact_bindings_without_versioned_flags( + tmp_path: Path, readset, restore: bool +) -> None: + from ctypes import wintypes as w + + directory = tmp_path / "case-mode" + directory.mkdir() + create = readset.reader._kernel.CreateFileW + create.argtypes = ( + w.LPCWSTR, + w.DWORD, + w.DWORD, + w.LPVOID, + w.DWORD, + w.DWORD, + w.HANDLE, + ) + create.restype = w.HANDLE + writer = create(str(directory), 0x100, 7, None, 3, 0x02200000, None) + assert writer != ctypes.c_void_p(-1).value + set_info = readset.reader._kernel.SetFileInformationByHandle + set_info.argtypes = (w.HANDLE, ctypes.c_int, w.LPVOID, w.DWORD) + set_info.restype = w.BOOL + + def set_mode(enabled): + flag = w.DWORD(int(enabled)) + if not set_info(writer, 23, ctypes.byref(flag), ctypes.sizeof(flag)): + error = ctypes.get_last_error() + if error in (1, 5, 50, 87, 1314): + pytest.skip(f"case sensitivity mutation unavailable: error {error}") + raise ctypes.WinError(error) + + try: + readset.project(directory) + before = readset._objects[readset.facts(directory).location[:2]].start_usn + set_mode(True) + if restore: + set_mode(False) + # On NTFS this mode can change without advancing the USN. The read set + # must not depend on mode stability: it only reuses exact name bindings. + with readset._lease(readset._view(directory).guard) as handle: + versioned = readset._version(handle) != before + if versioned: + with pytest.raises(commit.ObservationChanged): + readset.seal() + else: + readset.seal() + finally: + try: + set_mode(False) + finally: + assert readset.reader._close(writer) + + +@pytest.mark.parametrize("positive_mask", range(8)) +def test_partitioned_index_matches_reference_ownership_and_retirement( + positive_mask: int, +) -> None: + names = ("root", "stage", "other") + facts = {} + for number, name in enumerate(names, start=2): + key = (7, number, ()) + facts[name] = model.DirectoryObservation("/" + name, key, (key, (7, 1, ()))) + + class Filesystem: + def is_stable(self, path): + return bool(positive_mask & (1 << names.index(path))) + + def facts(self, path): + return facts[path] + + def overlaps(self, first, second): + # Independent exhaustive predicate, as used by the reference path. + left, right = facts[first], facts[second] + return ( + left.portable == right.portable + or left.portable.startswith(right.portable + "/") + or right.portable.startswith(left.portable + "/") + or left.location in right.ancestors + or right.location in left.ancestors + ) + + filesystem = Filesystem() + reservations = ( + model.Reservation("root", "old", "build", None, facts["root"]), + model.Reservation("staging", "old", "build", "target", facts["stage"]), + ) + cases = ( + ("root", None, "new", "build", "target", set(), "root-root"), + ("root", None, "old", "other-build", "target", set(), None), + ("stage", None, "old", "build", "target", set(), "root-staging"), + ("other", "root", "new", "build", "target", set(), "staging-root"), + ("other", "stage", "old", "build", "target", set(), None), + ("other", "stage", "new", "build", "target", {"old"}, None), + ("other", "stage", "new", "other-build", "target", {"old"}, "staging-staging"), + ("other", "stage", "new", "build", "other-target", {"old"}, "staging-staging"), + ("other", "stage", "new", "build", "target", set(), "staging-staging"), + ) + for root, stage, root_key, build, target, retiring, expected in cases: + index = commit.ProvisionalOwnershipIndex( + model, + filesystem, + tuple( + (reservation, path, filesystem.is_stable(path)) + for reservation, path in zip(reservations, names) + ), + ) + assert ( + index.conflict( + root=root, + root_key=root_key, + build_id=build, + staging=() if stage is None else ((target, stage),), + retiring_root_keys=retiring, + ) + == expected + ) + + +@pytest.mark.parametrize( + "error", + [commit.CapabilityUnavailable("no capability"), RuntimeError("unexpected failure")], +) +@pytest.mark.parametrize("mode", ["commit-shadow", "indexed"]) +def test_unavailable_or_failed_commit_uses_reference_and_preserves_existing_token( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error: Exception, mode: str +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + plan = _plan(tmp_path, "current") + token = engine.reconcile(plan) + state = engine._state_directory(plan.root) + claim_bytes = (state / "claim.json").read_bytes() + + def unavailable(*args, **kwargs): + raise error + + monkeypatch.setattr(engine, "_preview_committed_index", unavailable) + engine.registry_validation = mode + assert engine.reconcile(plan) == token + assert (state / "claim.json").read_bytes() == claim_bytes + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["commit_certificate"] == "unverified" + assert engine.validation_metrics["reference_result"] == "accepted" + + +def test_commit_conflict_disagreement_cannot_initialize_a_new_claim( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + engine.reconcile(_plan(tmp_path, "retained")) + monkeypatch.setattr( + engine, "_preview_committed_index", lambda *args, **kwargs: False + ) + engine.registry_validation = "commit-shadow" + with pytest.raises(coordinator.CoordinatorError, match="disagrees"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "accepted" + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +@pytest.mark.parametrize( + "certificate", + [ + {}, + {"commit_certificate": "verified", "commit_state": "closed"}, + { + "commit_certificate": "unverified", + "commit_state": "closed", + "commit_handles_opened": 2, + "commit_handles_closed": 2, + }, + { + "commit_certificate": "verified", + "commit_state": "sealed", + "commit_handles_opened": 2, + "commit_handles_closed": 2, + }, + { + "commit_certificate": "verified", + "commit_state": "closed", + "commit_handles_opened": 2, + "commit_handles_closed": 1, + }, + { + "commit_certificate": "verified", + "commit_state": "closed", + "commit_handles_opened": 0, + "commit_handles_closed": 0, + }, + { + "commit_certificate": "verified", + "commit_state": "closed", + "commit_handles_opened": 1, + "commit_handles_closed": True, + }, + ], +) +def test_indexed_incomplete_certificate_runs_reference_before_mutation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, certificate: dict +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + plan = _plan(tmp_path, "current") + + def incomplete(*args, **kwargs): + engine.validation_metrics.update( + commit_cleanup_failed=False, + commit_probe_state="closed", + commit_probe_native_retired=True, + commit_probe_active=0, + commit_probe_pending=0, + commit_probe_comparisons=0, + commit_fresh_comparisons=0, + ) + engine.validation_metrics.update(certificate) + return True + + monkeypatch.setattr(engine, "_preview_committed_index", incomplete) + original = engine._initialize_claim_locked + + def initialize(state, current): + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + original(state, current) + + monkeypatch.setattr(engine, "_initialize_claim_locked", initialize) + assert engine.reconcile(plan) + + +def test_indexed_conflict_uses_reference_diagnostics_and_acceptance( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + monkeypatch.setattr( + engine, "_preview_committed_index", lambda *args, **kwargs: False + ) + retained = _plan(tmp_path, "retained") + assert engine.reconcile(retained) + assert engine.validation_metrics["reference_result"] == "accepted" + retained.root.touch() + with pytest.raises(coordinator.CoordinatorError, match="non-directory"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "rejected" + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +def test_failed_promotion_gate_blocks_api_and_cli_before_index_authority( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + monkeypatch.setattr(coordinator, "_COMMITTED_INDEX_QUALIFIED", False) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + + def forbidden(*args, **kwargs): + pytest.fail("unqualified index was consulted") + + monkeypatch.setattr(engine, "_preview_committed_index", forbidden) + assert engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["index_authorization_blocked"] + assert engine.validation_metrics["authoritative"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + rejected = tmp_path / "unqualified-cli-locks" + assert ( + coordinator.main( + [ + "reconcile", + "--lock-root", + str(rejected), + "--experimental-committed-index", + ] + ) + == 1 + ) + assert "not qualified for consumer use" in capsys.readouterr().err + assert not rejected.exists() + + +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +def test_indexed_verified_readset_closes_before_mutation_without_reference( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native_capability +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + retained = [_plan(tmp_path, f"retained-{number}") for number in range(3)] + engine.reconcile_set((), retained) + engine.registry_validation = "indexed" + + def forbidden(*args, **kwargs): + pytest.fail("verified native read set unexpectedly ran reference") + + monkeypatch.setattr(engine, "_validate_registry_reference", forbidden) + original = engine._initialize_claim_locked + + def initialize(state, plan): + metrics = engine.validation_metrics + assert metrics["authoritative"] == "index" + assert metrics["commit_certificate"] == "verified" + assert metrics["commit_state"] == "closed" + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + assert metrics["commit_claims_checked"] == 3 + assert metrics["commit_records_read"] == 6 + original(state, plan) + + monkeypatch.setattr(engine, "_initialize_claim_locked", initialize) + assert engine.reconcile(_plan(tmp_path, "current")) + + +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +def test_indexed_abandoned_state_falls_back_to_reference_cleanup( + tmp_path: Path, native_capability +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + abandoned = engine.lock_root / "roots" / ("a" * 64) + abandoned.mkdir(parents=True) + (abandoned / "snapshot.json").write_bytes(b"{}") + assert engine.reconcile(_plan(tmp_path, "current")) + assert not abandoned.exists() + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + + +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +@pytest.mark.parametrize("replacement", ["file", "junction"]) +def test_indexed_success_keeps_fresh_mutation_time_path_guards( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native_capability, replacement: str +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + engine.reconcile(_plan(tmp_path, "retained")) + current = _plan(tmp_path, "current") + outside = tmp_path / "outside" + outside.mkdir() + sentinel = outside / "sample.protocyte.hpp" + sentinel.write_bytes(b"// preserve external output\n") + engine.registry_validation = "indexed" + validate = engine._validate_registry + + def change_after_validation(*args, **kwargs): + validate(*args, **kwargs) + assert engine.validation_metrics["authoritative"] == "index" + assert engine.validation_metrics["commit_state"] == "closed" + if replacement == "file": + current.root.touch() + else: + helpers._directory_link(current.root, outside) + + monkeypatch.setattr(engine, "_validate_registry", change_after_validation) + with pytest.raises( + coordinator.CoordinatorError, match="non-directory|symbolic link or junction" + ): + engine.reconcile(current) + assert sentinel.read_bytes() == b"// preserve external output\n" + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +@pytest.mark.skipif(os.name != "nt", reason="Windows observer coordination") +def test_independent_registries_serialize_observers_and_release_before_reference( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import concurrent.futures + import contextlib + import threading + + monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local")) + first = coordinator.OutputCoordinator( + tmp_path / "first", registry_validation="indexed" + ) + second = coordinator.OutputCoordinator( + tmp_path / "second", registry_validation="indexed" + ) + assert first._observation_lock().path == second._observation_lock().path + entered, attempted, release = ( + threading.Event(), + threading.Event(), + threading.Event(), + ) + order = [] + actual_lock = second._observation_lock + + @contextlib.contextmanager + def second_lock(): + attempted.set() + with actual_lock(): + yield + + def observe_first(*args, **kwargs): + order.append("first") + entered.set() + assert release.wait(5) + return False + + def observe_second(*args, **kwargs): + order.append("second") + return False + + def reference_first(*args, **kwargs): + # The second observer can enter while the first reference is active. + assert second_entered.wait(5) + + second_entered = threading.Event() + + def reference_second(*args, **kwargs): + second_entered.set() + + monkeypatch.setattr(first, "_preview_committed_index", observe_first) + monkeypatch.setattr(second, "_preview_committed_index", observe_second) + monkeypatch.setattr(second, "_observation_lock", second_lock) + monkeypatch.setattr(first, "_validate_registry_reference", reference_first) + monkeypatch.setattr(second, "_validate_registry_reference", reference_second) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + one = pool.submit(first._validate_registry, []) + assert entered.wait(5) + two = pool.submit(second._validate_registry, []) + try: + assert attempted.wait(5) + assert order == ["first"] + finally: + release.set() + one.result(timeout=10) + two.result(timeout=10) + assert order == ["first", "second"] + + +@pytest.mark.parametrize( + "other_flag", + [ + "--experimental-registry-index", + "--experimental-native-observation", + "--experimental-committed-index", + ], +) +def test_commit_flag_rejects_other_experiments_before_mutation( + tmp_path: Path, capsys, other_flag: str +) -> None: + locks = tmp_path / "locks" + assert ( + coordinator.main( + [ + "reconcile", + "--lock-root", + str(locks), + "--experimental-observation-commit", + other_flag, + ] + ) + == 1 + ) + assert "choose one experimental" in capsys.readouterr().err + assert not locks.exists() + + +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +def test_commit_shadow_authenticates_records_closes_scopes_then_uses_reference( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native_capability +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + engine.reconcile_set((), [_plan(tmp_path, f"retained-{n}") for n in range(3)]) + engine.registry_validation = "commit-shadow" + initialize = engine._initialize_claim_locked + + def checked(state, plan): + assert engine.validation_metrics["reference_result"] == "accepted" + assert engine.validation_metrics["commit_certificate"] == "verified" + assert engine.validation_metrics["commit_state"] == "closed" + initialize(state, plan) + + monkeypatch.setattr(engine, "_initialize_claim_locked", checked) + assert engine.reconcile(_plan(tmp_path, "current")) + metrics = engine.validation_metrics + assert metrics["agreement"] is True + assert metrics["commit_claims_checked"] == 3 + assert metrics["commit_records_read"] == 6 + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + + +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +def test_changed_but_safe_observation_falls_back_without_breaking_a_build( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native_capability +) -> None: + retained = _plan(tmp_path, "retained") + engine = coordinator.OutputCoordinator(tmp_path / "locks") + engine.reconcile(retained) + engine.registry_validation = "commit-shadow" + + def inject(phase): + if phase == "before-observation-commit": + retained.root.mkdir() + + monkeypatch.setattr(engine, "_inject", inject) + assert engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + + +@pytest.mark.parametrize( + "phase", ["before-observation-commit", "after-observation-commit"] +) +@pytest.mark.skipif(os.name != "nt", reason="native commit witnesses require Windows") +def test_foreign_change_before_or_after_commit_cannot_bypass_reference( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, phase: str, native_capability +) -> None: + retained = _plan(tmp_path, "retained") + engine = coordinator.OutputCoordinator(tmp_path / "locks") + engine.reconcile(retained) + engine.registry_validation = "commit-shadow" + + def inject(current): + if current == phase: + retained.root.touch() + + monkeypatch.setattr(engine, "_inject", inject) + with pytest.raises(coordinator.CoordinatorError, match="non-directory"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "rejected" + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 diff --git a/tests/test_output_coordinator.py b/tests/test_output_coordinator.py index 9fe66a5..bb3ff56 100644 --- a/tests/test_output_coordinator.py +++ b/tests/test_output_coordinator.py @@ -1,5 +1,6 @@ from __future__ import annotations +import errno import hashlib import importlib.util import json @@ -23,6 +24,18 @@ def _load_coordinator() -> ModuleType: module = importlib.util.module_from_spec(specification) sys.modules[specification.name] = module specification.loader.exec_module(module) + test_mode = os.environ.get("PROTOCYTE_TEST_REGISTRY_VALIDATION", "reference") + if test_mode == "indexed": + # This module is used exclusively by isolated test registries. + module._COMMITTED_INDEX_QUALIFIED = True + original_initialize = module.OutputCoordinator.__init__ + + def initialize( + self: object, lock_root: Path, *, registry_validation: str | None = test_mode + ) -> None: + original_initialize(self, lock_root, registry_validation=test_mode if registry_validation is None else registry_validation) + + module.OutputCoordinator.__init__ = initialize return module @@ -108,6 +121,45 @@ def resolve_after_deletion(path: Path, strict: bool = False) -> Path: assert interrupted +@pytest.mark.parametrize("replacement", ["absent", "file", "directory-link"]) +def test_projection_rechecks_a_leaf_replaced_before_chain_validation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replacement: str +) -> None: + leaf = tmp_path / "disappearing" + leaf.mkdir() + original_lexists = coordinator.os.path.lexists + original_is_link = coordinator._is_link + removed = False + inspected: list[Path] = [] + + def lexists(path: Path) -> bool: + nonlocal removed + result = original_lexists(path) + if path == leaf and not removed: + removed = True + leaf.rmdir() + if replacement == "file": + leaf.touch() + elif replacement == "directory-link": + _directory_link(leaf, tmp_path) + return result + + def is_link(path: Path) -> bool: + inspected.append(path) + return original_is_link(path) + + monkeypatch.setattr(coordinator.os.path, "lexists", lexists) + monkeypatch.setattr(coordinator, "_is_link", is_link) + if replacement == "absent": + assert coordinator.project_path(leaf) == leaf + else: + with pytest.raises( + coordinator.CoordinatorError, match="symbolic link or junction|non-directory" + ): + coordinator.project_path(leaf) + assert removed and leaf in inspected + + def test_durable_directory_creation_resyncs_a_preexisting_retry_chain( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1588,7 +1640,9 @@ def plan(name: str) -> object: retained = [plan(f"retained-{index}") for index in range(4)] current = [plan(f"current-{index}") for index in range(current_count)] - engine = coordinator.OutputCoordinator(tmp_path / "locks") + # This is the production reference contract; shadow deliberately reads each + # record once in its preview and once in the mandatory reference phase. + engine = coordinator.OutputCoordinator(tmp_path / "locks", registry_validation="reference") engine.reconcile_set((), retained) expected = {engine._state_directory(value.root) for value in retained} loaded: list[Path] = [] @@ -1680,19 +1734,41 @@ def test_physical_containment_checks_ancestors_of_missing_paths( first, alias = tmp_path / "first", tmp_path / "alias" first.mkdir() alias.mkdir() - original_samefile = coordinator.os.path.samefile + original_lstat = Path.lstat - def samefile(left: object, right: object) -> bool: - if {Path(left), Path(right)} == {first, alias}: - return True - return original_samefile(left, right) + def lstat(path: Path) -> os.stat_result: + # Model the actual samefile identity relation, including ancestor IDs. + return original_lstat(first if path == alias else path) - monkeypatch.setattr(coordinator.os.path, "samefile", samefile) + monkeypatch.setattr(Path, "lstat", lstat) assert coordinator._paths_overlap(first, alias / "missing" / "nested") assert coordinator._paths_overlap(alias / "missing" / "nested", first) assert not coordinator._paths_overlap(first, tmp_path / "unrelated") +@pytest.mark.skipif(os.name != "nt", reason="requires Windows short directory names") +def test_overlap_preserves_windows_short_name_aliases(tmp_path: Path) -> None: + import ctypes + + directory = tmp_path / "directory-with-a-long-name" + directory.mkdir() + get_short_path = ctypes.WinDLL("kernel32", use_last_error=True).GetShortPathNameW + get_short_path.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) + get_short_path.restype = ctypes.c_uint32 + buffer = ctypes.create_unicode_buffer(32768) + length = get_short_path(str(directory), buffer, len(buffer)) + if ( + not length + or length >= len(buffer) + or buffer.value.casefold() == str(directory).casefold() + ): + pytest.skip("filesystem does not provide a distinct 8.3 directory spelling") + alias = Path(buffer.value) + assert coordinator._path_key(directory) == coordinator._path_key(alias) + assert coordinator._paths_overlap(directory / "missing", alias / "missing/child") + assert coordinator._paths_overlap(alias / "missing/child", directory / "missing") + + @pytest.mark.parametrize("replacement", ["file", "directory-link"]) @pytest.mark.parametrize("side", [0, 1]) def test_overlap_rejects_path_replacement_during_the_comparison( @@ -1745,6 +1821,88 @@ def lstat_with_alias(path: Path) -> os.stat_result: assert not coordinator._paths_overlap(first / "missing", alias / "other") +@pytest.mark.parametrize("depth", [1, 16, 64]) +def test_physical_ancestry_observations_are_linear_in_missing_depth( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, depth: int +) -> None: + child = tmp_path.joinpath(*(f"missing-{index}" for index in range(depth))) + observed: list[Path] = [] + original_lstat = Path.lstat + + def lstat(path: Path) -> os.stat_result: + observed.append(path) + return original_lstat(path) + + monkeypatch.setattr(Path, "lstat", lstat) + keys = list(coordinator._physical_ancestor_keys(child)) + assert len(observed) == len(child.parents) + 1 + assert len(set(observed)) == len(observed) + assert len(keys) == len(observed) + anchor = original_lstat(tmp_path) + assert keys[0] == ( + anchor.st_dev, + anchor.st_ino, + tuple(f"missing-{index}" for index in range(depth)), + ) + + +@pytest.mark.parametrize("depth", [1, 64]) +def test_overlap_metadata_probes_stay_linear_in_missing_depth( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, depth: int +) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + first.mkdir() + second.mkdir() + for index in range(depth): + first /= f"missing-{index}" + second /= f"missing-{index}" + original_lstat = Path.lstat + observations = 0 + + def lstat(path: Path) -> os.stat_result: + nonlocal observations + observations += 1 + return original_lstat(path) + + monkeypatch.setattr(Path, "lstat", lstat) + assert not coordinator._paths_overlap(first, second) + # Includes fresh projections, both directional physical checks and platform + # pathlib behavior. A generous linear bound still catches repeated searches + # of the missing suffix for each ancestor (the former quadratic behavior). + assert observations <= 12 * (len(first.parents) + len(second.parents)) + + +@pytest.mark.parametrize("replacement", ["file", "directory-link"]) +def test_physical_ancestry_rejects_ancestor_replacement_after_projection( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replacement: str +) -> None: + parent = tmp_path / "parent" + ancestor = tmp_path / "ancestor" + ancestor.mkdir() + child = ancestor / "missing" + original_project = coordinator.project_path + + def project(path: Path, **options: object) -> Path: + result = original_project(path, **options) + if path == child: + ancestor.rmdir() + if replacement == "file": + ancestor.touch() + else: + _directory_link(ancestor, tmp_path) + return result + + monkeypatch.setattr(coordinator, "project_path", project) + with pytest.raises( + coordinator.CoordinatorError, + # POSIX can reject the child with ENOTDIR before reaching its replaced + # ancestor; Windows can report the child missing and inspect the parent. + match="symbolic link or junction|non-directory|could not identify physical filesystem location", + ): + coordinator._paths_overlap(parent, child) + + def _directory_link(link: Path, destination: Path) -> None: try: link.symlink_to(destination, target_is_directory=True) @@ -1785,16 +1943,26 @@ def test_registry_comparisons_reject_a_replaced_retained_root( original_overlap = coordinator._paths_overlap changed = False - def overlap(first: Path, second: Path) -> bool: + def replace_retained_root(first: Path, second: Path, result: bool) -> bool: nonlocal changed - result = original_overlap(first, second) if not changed and first == retained_root and second == current[0].root: changed = True # The previously missing directory is replaced after one comparison. _directory_link(retained_root, tmp_path) return result + def overlap(first: Path, second: Path) -> bool: + return replace_retained_root(first, second, original_overlap(first, second)) + monkeypatch.setattr(coordinator, "_paths_overlap", overlap) + if engine.registry_validation == "indexed" and os.name == "nt": + scope_type = coordinator._load_observation_commit().WindowsObservationCommit + native_overlap = scope_type._overlaps_views + + def indexed_overlap(self: object, first: object, second: object) -> bool: + return replace_retained_root(first.path, second.path, native_overlap(self, first, second)) + + monkeypatch.setattr(scope_type, "_overlaps_views", indexed_overlap) with pytest.raises(coordinator.CoordinatorError, match="symbolic link or junction"): engine.reconcile_set((), current) assert changed @@ -1824,10 +1992,9 @@ def validate(*args: object, **kwargs: object) -> None: assert not list((engine.lock_root / "roots").glob("*/claim.json")) -def test_progress_is_bounded_path_free_and_keeps_stdout_clean( - capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +def test_progress_continues_past_former_cutoff_and_keeps_stdout_clean( + capsys: pytest.CaptureFixture[str], ) -> None: - monkeypatch.setattr(coordinator._ReconcileProgress, "MAX_REPORTS", 3) with coordinator._ReconcileProgress(4, 1) as progress: progress.phase("waiting for registry lock", "lock_wait") assert progress._report() @@ -1836,17 +2003,19 @@ def test_progress_is_bounded_path_free_and_keeps_stdout_clean( assert progress._report() progress.phase("reconciling outputs", "reconciliation") assert progress._report() - for _ in range(10): - assert not progress._report() + for _ in range(20): + progress.registry(claim=True) + assert progress._report() output = capsys.readouterr() assert not output.out - assert len(output.err.splitlines()) == 4 + assert len(output.err.splitlines()) == 24 assert "waiting for registry lock" in output.err assert "validating registry" in output.err assert "current_plans=4 retired_plans=1" in output.err assert "claims_checked=1 registry_entries=8" in output.err assert "lock_wait=" in output.err and "validation=" in output.err - assert "further progress suppressed" in output.err + assert "claims_checked=21 registry_entries=8" in output.err + assert "further progress suppressed" not in output.err assert "complete;" in output.err @@ -1866,6 +2035,27 @@ def test_progress_reports_failure_and_fast_operations_stay_silent( assert "failed;" in output.err +def test_progress_worker_keeps_reporting_until_stopped( + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + progress = coordinator._ReconcileProgress(11, 0) + progress.phase("validating registry", "validation") + progress.registry(states=24) + + class ControlledStop: + def wait(self, interval: float) -> bool: + assert interval == progress.INTERVAL_SECONDS + progress.registry(claim=True) + return progress._claims == 24 + + monkeypatch.setattr(progress, "_stop", ControlledStop()) + progress._run() + output = capsys.readouterr() + assert not output.out + assert len(output.err.splitlines()) == 23 + assert "claims_checked=23 registry_entries=24" in output.err + + @pytest.mark.skipif(os.name == "nt", reason="requires case-sensitive paths") def test_case_distinct_build_roots_cannot_share_a_claim(tmp_path: Path) -> None: root = tmp_path / "generated" @@ -1924,6 +2114,78 @@ def reject_state(path: Path) -> object: engine.reconcile(second) +def test_unreadable_recorded_plan_metadata_fails_closed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + retained = _write_plan( + tmp_path / "retained.plan", + tmp_path / "retained/generated", + tmp_path / "retained/build", + ((_target("retained"), "sample.protocyte.hpp"),), + ) + current = _write_plan( + tmp_path / "current.plan", + tmp_path / "current/generated", + tmp_path / "current/build", + ((_target("current"), "sample.protocyte.hpp"),), + ) + engine = coordinator.OutputCoordinator(tmp_path / "locks") + token = engine.reconcile(retained) + recorded = engine._state_directory(retained.root) / "plan.json" + original_lstat = Path.lstat + + def denied(path: Path, *args: object, **kwargs: object) -> os.stat_result: + if path == recorded: + raise PermissionError("metadata denied by test") + return original_lstat(path, *args, **kwargs) + + monkeypatch.setattr(Path, "lstat", denied) + if engine.registry_validation == "indexed" and os.name == "nt": + scope_type = coordinator._load_observation_commit().WindowsObservationCommit + record_exists = scope_type.record_exists + + def inaccessible_record(self: object, path: Path) -> bool: + if path == recorded: + raise PermissionError("metadata denied by test") + return record_exists(self, path) + + monkeypatch.setattr(scope_type, "record_exists", inaccessible_record) + with pytest.raises(coordinator.CoordinatorError, match="could not inspect configured output plan"): + engine.reconcile(current) + claim = engine._state_directory(retained.root) / "claim.json" + assert json.loads(claim.read_bytes())["token"] == token + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +def test_dangling_recorded_plan_is_rejected_instead_of_treated_as_absent( + tmp_path: Path, +) -> None: + retained = _write_plan( + tmp_path / "retained.plan", + tmp_path / "retained/generated", + tmp_path / "retained/build", + ((_target("retained"), "sample.protocyte.hpp"),), + ) + current = _write_plan( + tmp_path / "current.plan", + tmp_path / "current/generated", + tmp_path / "current/build", + ((_target("current"), "sample.protocyte.hpp"),), + ) + engine = coordinator.OutputCoordinator(tmp_path / "locks") + engine.reconcile(retained) + recorded = engine._state_directory(retained.root) / "plan.json" + recorded.unlink() + target = tmp_path / "removed-plan-target" + target.mkdir() + _directory_link(recorded, target) + target.rmdir() + assert not recorded.exists() and os.path.lexists(recorded) + with pytest.raises(coordinator.CoordinatorError, match="symbolic link or junction"): + engine.reconcile(current) + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + def test_physical_output_root_aliases_cannot_receive_distinct_claims( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1945,8 +2207,14 @@ def test_physical_output_root_aliases_cannot_receive_distinct_claims( ((_target("second"), "second.protocyte.hpp"),), ) original_samefile = coordinator.os.path.samefile + original_lstat = Path.lstat aliases = {os.path.normcase(os.fspath(root_a)), os.path.normcase(os.fspath(root_b))} + def lstat_with_root_alias(path: Path) -> os.stat_result: + # Non-link physical aliases have matching directory IDs, not just a + # samefile override. Exercise the non-following containment checks too. + return original_lstat(root_a if path == root_b else path) + def samefile_with_root_alias(first_path: object, second_path: object) -> bool: pair = { os.path.normcase(os.fspath(first_path)), @@ -1957,11 +2225,33 @@ def samefile_with_root_alias(first_path: object, second_path: object) -> bool: return original_samefile(first_path, second_path) monkeypatch.setattr(coordinator.os.path, "samefile", samefile_with_root_alias) + monkeypatch.setattr(Path, "lstat", lstat_with_root_alias) engine = coordinator.OutputCoordinator(lock_root) with pytest.raises(coordinator.CoordinatorError, match="overlapping roots"): engine._validate_plan_set((first, second)) + if engine.registry_validation == "indexed" and os.name == "nt": + scope_type = coordinator._load_observation_commit().WindowsObservationCommit + native_identity = scope_type._identity + scope = scope_type(coordinator._load_path_observation(), coordinator._load_ownership_index()) + try: + handle = scope.reader._open_existing(root_a) + assert handle is not None + try: + alias_identity = native_identity(scope, handle) + finally: + scope._release(handle) + finally: + scope.close() + + def identity_with_root_alias(self: object, handle: object) -> tuple[int, int]: + identity = native_identity(self, handle) + canonical = self.reader._describe(handle, leaf_may_be_file=True) + return alias_identity if canonical == root_b else identity + + monkeypatch.setattr(scope_type, "_identity", identity_with_root_alias) + engine.reconcile(first) with pytest.raises(coordinator.CoordinatorError, match="root claimed"): engine.reconcile(second) @@ -2405,16 +2695,23 @@ def test_reset_rejects_an_unowned_generated_symlink(tmp_path: Path) -> None: token = engine.reconcile(plan) outside = tmp_path / "outside.hpp" outside.write_text("// outside\n", encoding="utf-8") + root.mkdir() unexpected = root / "stale.protocyte.hpp" try: unexpected.symlink_to(outside) except OSError as error: + if ( + error.errno not in (errno.EACCES, errno.EPERM, errno.ENOSYS, errno.ENOTSUP) + and getattr(error, "winerror", None) not in (1, 50, 1314) + ): + raise pytest.skip(f"file symlinks are unavailable: {error}") with pytest.raises(coordinator.CoordinatorError, match="unowned generated-looking"): engine.reset(plan, token) assert unexpected.is_symlink() + assert outside.read_text(encoding="utf-8") == "// outside\n" assert (lock_root / "roots" / _identity(root)).is_dir() diff --git a/tests/test_output_coordinator_cmake.py b/tests/test_output_coordinator_cmake.py index c6447e6..1a6f4ec 100644 --- a/tests/test_output_coordinator_cmake.py +++ b/tests/test_output_coordinator_cmake.py @@ -1,6 +1,8 @@ from __future__ import annotations import json +import ast +import hashlib import importlib.util import os import shutil @@ -30,6 +32,125 @@ def _configure(source: Path, build: Path) -> subprocess.CompletedProcess[str]: return _configure_out_dir_owner_project(source, build, "-G", "Ninja") +def test_default_registry_selector_uses_the_isolated_test_cache(tmp_path: Path) -> None: + source = tmp_path / "project" + source.mkdir() + repo_root = Path(__file__).resolve().parents[1] + result_path = tmp_path / "selected.txt" + (source / "CMakeLists.txt").write_text( + "\n".join( + [ + "cmake_minimum_required(VERSION 3.24)", + "project(registry_isolation LANGUAGES NONE)", + f'include("{(repo_root / "cmake/ProtocyteFunctions.cmake").as_posix()}")', + "_protocyte_shared_output_lock_directory(selected)", + f'file(WRITE "{result_path.as_posix()}" "${{selected}}")', + ] + ) + + "\n", + encoding="utf-8", + ) + result = subprocess.run( + ["cmake", "-S", str(source), "-B", str(tmp_path / "build")], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert ( + Path(result_path.read_text()).resolve() + == (tmp_path / "isolated-user-cache/protocyte/output-locks-v1").resolve() + ) + + +@pytest.mark.parametrize( + "experimental_flag", + [ + None, + "--reference-registry-validation", + "--experimental-registry-index", + "--experimental-native-observation", + "--experimental-observation-commit", + "--experimental-committed-index", + ], +) +def test_installed_coordinator_is_relocatable_and_keeps_prefix_unchanged( + tmp_path: Path, + experimental_flag: str | None, +) -> None: + _, prefix = _test_cmake._configure_fetchcontent_install_fixture( + tmp_path, protocyte_install=True + ) + relocated = tmp_path / "relocated-prefix" + prefix.rename(relocated) + script = next(relocated.rglob("ProtocyteOutputCoordinator.py")) + assert script.with_name("ProtocyteOwnershipIndex.py").is_file() + assert script.with_name("ProtocytePathObservation.py").is_file() + assert script.with_name("ProtocyteObservationCommit.py").is_file() + + def contents() -> dict[str, bytes]: + return { + path.relative_to(relocated).as_posix(): hashlib.sha256( + path.read_bytes() + ).digest() + for path in relocated.rglob("*") + if path.is_file() + } + + before = contents() + build = tmp_path / "consumer-build" + build.mkdir() + root = tmp_path / "generated" + target = hashlib.sha256(b"installed-shadow").hexdigest() + staging = tmp_path / f".protocyte-generation-staging-{target}" + plan = tmp_path / "outputs.plan" + + def encoded(path: Path | str) -> str: + return os.fspath(path).encode().hex() + + plan.write_text( + "\n".join( + [ + "protocyte-output-plan-v1", + "root-hex=" + encoded(root), + "build-root-hex=" + encoded(build), + "target=" + target + "|" + encoded(staging), + "output=" + target + "|" + encoded("sample.protocyte.hpp"), + ] + ) + + "\n", + encoding="ascii", + ) + result = subprocess.run( + [ + sys.executable, + str(script), + "reconcile", + "--lock-root", + str(tmp_path / "locks"), + "--plan", + str(plan), + *([experimental_flag] if experimental_flag else []), + ], + check=False, + capture_output=True, + text=True, + ) + tree = ast.parse(script.read_bytes()) + qualified = next(node.value.value for node in tree.body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == "_COMMITTED_INDEX_QUALIFIED" for target in node.targets)) + if experimental_flag == "--experimental-committed-index" and not qualified: + assert result.returncode == 1, result.stdout + result.stderr + assert "not qualified for consumer use" in result.stderr + assert not result.stdout + assert not (tmp_path / "locks").exists() + else: + assert result.returncode == 0, result.stdout + result.stderr + assert len(result.stdout.strip()) == 64 + assert len(result.stdout.splitlines()) == 1 + assert contents() == before + + def test_coordinator_recovers_default_output_after_build_tree_recreation( tmp_path: Path, ) -> None: @@ -184,7 +305,8 @@ def test_configure_surfaces_lock_progress_without_corrupting_claim_tokens( assert time.monotonic() < deadline, diagnostic time.sleep(0.05) progress_lines = [ - line for line in diagnostic.splitlines() + line + for line in diagnostic.splitlines() if "Protocyte output coordinator:" in line ] assert progress_lines and all( @@ -278,7 +400,8 @@ def test_reconfigure_retires_interrupted_staging_for_a_removed_target( assert configured.returncode == 0, configured.stdout + configured.stderr plan = next((build / "CMakeFiles" / "protocyte-output-plans").glob("*.plan")) target_line = next( - line for line in plan.read_text(encoding="ascii").splitlines() + line + for line in plan.read_text(encoding="ascii").splitlines() if line.startswith("target=") ) staging = Path(bytes.fromhex(target_line.split("|", 1)[1]).decode("utf-8")) @@ -330,12 +453,8 @@ def test_conflicting_root_move_preserves_the_last_successful_outputs( second_build = tmp_path / "second-build" second_output = tmp_path / "second-generated" locks = tmp_path / "locks" - _write_out_dir_owner_project( - first_source, first_output, output_lock_root=locks - ) - _write_out_dir_owner_project( - second_source, second_output, output_lock_root=locks - ) + _write_out_dir_owner_project(first_source, first_output, output_lock_root=locks) + _write_out_dir_owner_project(second_source, second_output, output_lock_root=locks) assert _configure(first_source, first_build).returncode == 0 assert _build_out_dir_owner_project(first_build).returncode == 0 assert _configure(second_source, second_build).returncode == 0 @@ -346,9 +465,7 @@ def test_conflicting_root_move_preserves_the_last_successful_outputs( prior_plan_text = prior_plan.read_text(encoding="ascii") first_header = first_output / "demo_0.protocyte.hpp" first_header_bytes = first_header.read_bytes() - _write_out_dir_owner_project( - first_source, second_output, output_lock_root=locks - ) + _write_out_dir_owner_project(first_source, second_output, output_lock_root=locks) rejected = _configure(first_source, first_build) @@ -389,9 +506,7 @@ def test_public_reset_rejects_duplicate_single_value_keywords(tmp_path: Path) -> assert configured.returncode != 0 diagnostic = " ".join((configured.stdout + configured.stderr).split()) - assert ( - "duplicate single-value keyword(s): OUT_DIR, EXPECTED_CLAIM" in diagnostic - ) + assert "duplicate single-value keyword(s): OUT_DIR, EXPECTED_CLAIM" in diagnostic def test_coordinator_skips_an_inherited_incompatible_python(tmp_path: Path) -> None: @@ -422,9 +537,10 @@ def test_coordinator_skips_an_inherited_incompatible_python(tmp_path: Path) -> N ) assert configured.returncode == 0, configured.stdout + configured.stderr - assert Path(result_file.read_text(encoding="utf-8")).resolve() != Path( - shutil.which("cmake") or "" - ).resolve() + assert ( + Path(result_file.read_text(encoding="utf-8")).resolve() + != Path(shutil.which("cmake") or "").resolve() + ) def test_reconfigure_discards_an_already_released_retired_plan( @@ -502,11 +618,13 @@ def test_build_root_is_physical_when_configured_through_a_directory_link( assert configured.returncode == 0, configured.stdout + configured.stderr assert generated.returncode == 0, generated.stdout + generated.stderr - plan = next( - (real_build / "CMakeFiles" / "protocyte-output-plans").glob("*.plan") + plan = next((real_build / "CMakeFiles" / "protocyte-output-plans").glob("*.plan")) + encoded_build_root = ( + plan.read_text(encoding="ascii").splitlines()[2].split("=", 1)[1] + ) + assert ( + Path(bytes.fromhex(encoded_build_root).decode("utf-8")) == real_build.resolve() ) - encoded_build_root = plan.read_text(encoding="ascii").splitlines()[2].split("=", 1)[1] - assert Path(bytes.fromhex(encoded_build_root).decode("utf-8")) == real_build.resolve() def test_public_reset_requires_token_and_releases_claim(tmp_path: Path) -> None: diff --git a/tests/test_ownership_index.py b/tests/test_ownership_index.py new file mode 100644 index 0000000..fa168ca --- /dev/null +++ b/tests/test_ownership_index.py @@ -0,0 +1,429 @@ +from __future__ import annotations + +import importlib.util +import random +import sys +from pathlib import Path + +import pytest + +_spec = importlib.util.spec_from_file_location( + "protocyte_ownership_index_test_helpers", + Path(__file__).with_name("test_output_coordinator.py"), +) +assert _spec is not None and _spec.loader is not None +_helpers = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = _helpers +_spec.loader.exec_module(_helpers) +_directory_link = _helpers._directory_link +_target = _helpers._target +_write_plan = _helpers._write_plan +coordinator = _helpers.coordinator + + +model = coordinator._load_ownership_index() + + +def _directory(name: str, inode: int, parents: tuple[int, ...] = (1,)) -> object: + key = (7, inode, ()) + return model.DirectoryObservation( + name, key, (key, *((7, parent, ()) for parent in parents)) + ) + + +def _oracle_overlap(first: object, second: object) -> bool: + def contains(parent: str, child: str) -> bool: + return child == parent or child.startswith(parent + "/") + + return ( + contains(first.portable, second.portable) + or contains(second.portable, first.portable) + or any(first.location == key for key in second.ancestors) + or any(second.location == key for key in first.ancestors) + ) + + +def test_index_matches_exhaustive_geometry_across_aliases_and_missing_suffixes() -> ( + None +): + randomizer = random.Random(5411) + parents: dict[int, tuple[int, ...]] = {1: ()} + for inode in range(2, 72): + parent = randomizer.randrange(1, inode) + parents[inode] = (parent, *parents[parent]) + observations = [] + for index in range(300): + inode = randomizer.randrange(1, 72) + suffix = tuple( + randomizer.choice(("nested", "nested-other", "unicode-ü", "leaf")) + for _ in range(randomizer.randrange(4)) + ) + alias = "alias" if index % 3 == 0 else "tree" + name = f"/{alias}/node-{inode}" + ("/" + "/".join(suffix) if suffix else "") + keys = tuple( + (7, inode, suffix[:length]) for length in range(len(suffix), -1, -1) + ) + keys += tuple((7, parent, ()) for parent in parents[inode]) + observations.append(model.DirectoryObservation(name, (7, inode, suffix), keys)) + observations.extend((_directory("", 1, ()), _directory("/tree/node-2-other", 900))) + reservations = tuple( + model.Reservation("root", str(index), "owner", None, facts) + for index, facts in enumerate(observations) + ) + index = model.OwnershipIndex(reservations) + for facts in observations: + expected = tuple( + reservation + for reservation in reservations + if _oracle_overlap(reservation.directory, facts) + ) + assert index.overlapping(facts) == expected + + +@pytest.mark.parametrize( + ( + "current_root", + "current_stage", + "root_key", + "build_id", + "target", + "retiring", + "expected", + ), + [ + ("root", None, "new", "build", "target", set(), "root-root"), + ("root", None, "old", "another-build", "target", set(), None), + ("stage", None, "old", "build", "target", set(), "root-staging"), + ("other", "root", "new", "build", "target", set(), "staging-root"), + ("other", "stage", "old", "build", "target", set(), None), + ("other", "stage", "new", "build", "target", {"old"}, None), + ( + "other", + "stage", + "new", + "another-build", + "target", + {"old"}, + "staging-staging", + ), + ( + "other", + "stage", + "new", + "build", + "another-target", + {"old"}, + "staging-staging", + ), + ("other", "stage", "new", "build", "target", set(), "staging-staging"), + ], +) +def test_index_preserves_ownership_and_retiring_staging_exceptions( + current_root: str, + current_stage: str | None, + root_key: str, + build_id: str, + target: str, + retiring: set[str], + expected: str | None, +) -> None: + facts = { + "root": _directory("/reserved-output", 2), + "stage": _directory("/stage", 3), + "other": _directory("/other", 4), + } + index = model.OwnershipIndex( + ( + model.Reservation("root", "old", "build", None, facts["root"]), + model.Reservation("staging", "old", "build", "target", facts["stage"]), + ) + ) + assert ( + index.conflict( + root=facts[current_root], + root_key=root_key, + build_id=build_id, + staging=() if current_stage is None else ((target, facts[current_stage]),), + retiring_root_keys=retiring, + ) + == expected + ) + + +def _plan(tmp_path: Path, name: str, root: Path | None = None) -> object: + return _write_plan( + tmp_path / f"{name}.plan", + root or tmp_path / name / "generated", + tmp_path / name / "build", + ((_target(name), "sample.protocyte.hpp"),), + ) + + +def test_reference_mode_never_loads_or_consults_the_preview( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def unexpected() -> object: + pytest.fail("default validation loaded the experimental index") + + monkeypatch.setattr(coordinator, "_load_ownership_index", unexpected) + engine = coordinator.OutputCoordinator(tmp_path / "locks") + assert engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["mode"] == "reference" + assert engine.validation_metrics["authoritative"] == "reference" + + +def test_shadow_authenticates_all_records_in_both_phases_before_mutation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="shadow" + ) + retained = [_plan(tmp_path, f"retained-{index}") for index in range(3)] + engine.reconcile_set((), retained) + expected = {engine._state_directory(plan.root) for plan in retained} + loaded: dict[str, list[Path]] = {"preview": [], "reference": []} + original_load = engine._load_recorded_plan + original_initialize = engine._initialize_claim_locked + + def load(state: Path, claim: object, **kwargs: object) -> object: + phase = "preview" if kwargs.get("_filesystem") is not None else "reference" + if state in expected: + loaded[phase].append(state) + return original_load(state, claim, **kwargs) + + def initialize(state: Path, plan: object) -> None: + assert engine.validation_metrics["reference_result"] == "accepted" + assert engine.validation_metrics["agreement"] is True + original_initialize(state, plan) + + monkeypatch.setattr(engine, "_load_recorded_plan", load) + monkeypatch.setattr(engine, "_initialize_claim_locked", initialize) + assert ( + len( + engine.reconcile_set( + (), [_plan(tmp_path, "first"), _plan(tmp_path, "second")] + ) + ) + == 2 + ) + assert sorted(loaded["preview"]) == sorted(expected) + assert sorted(loaded["reference"]) == sorted(expected) + assert engine.validation_metrics["preview_claims"] == 3 + assert engine.validation_metrics["indexed_reservations"] == 6 + assert engine.validation_metrics["index_queries"] == 4 + + +@pytest.mark.parametrize( + "replacement", ["file", "root-link", "staging-link", "ancestor-link"] +) +def test_foreign_changes_after_preview_are_rejected_before_new_claims( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replacement: str +) -> None: + retained = _plan(tmp_path, "retained") + current = _plan(tmp_path, "current") + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="shadow" + ) + engine.reconcile(retained) + changed = False + + def inject(stage: str) -> None: + nonlocal changed + if stage != "after-index-preview" or changed: + return + changed = True + if replacement == "file": + retained.root.touch() + elif replacement == "ancestor-link": + retained.root.parent.rename(tmp_path / "moved-retained") + _directory_link(retained.root.parent, tmp_path) + else: + path = ( + retained.root + if replacement == "root-link" + else retained.targets[0].staging + ) + _directory_link(path, tmp_path) + + monkeypatch.setattr(engine, "_inject", inject) + with pytest.raises( + coordinator.CoordinatorError, match="symbolic link or junction|non-directory" + ): + engine.reconcile(current) + assert changed + assert engine.validation_metrics["preview_result"] == "accepted" + assert engine.validation_metrics["reference_result"] == "rejected" + assert engine.validation_metrics["agreement"] is False + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +@pytest.mark.parametrize("preview", [False, RuntimeError("injected preview error")]) +def test_preview_false_positive_or_error_cannot_authorize_mutation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preview: object +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="shadow" + ) + + def sample(*args: object, **kwargs: object) -> bool: + if isinstance(preview, Exception): + raise preview + return bool(preview) + + monkeypatch.setattr(engine, "_preview_registry_index", sample) + with pytest.raises( + coordinator.CoordinatorError, match="disagrees with the fresh reference" + ): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "accepted" + assert not list((engine.lock_root / "roots").glob("*/claim.json")) + + +def test_preview_false_negative_never_bypasses_reference_rejection( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="shadow" + ) + retained = _plan(tmp_path, "retained") + engine.reconcile(retained) + monkeypatch.setattr(engine, "_preview_registry_index", lambda *args, **kwargs: True) + current = _plan(tmp_path, "current", retained.root / "nested") + with pytest.raises(coordinator.CoordinatorError, match="overlaps a root"): + engine.reconcile(current) + assert engine.validation_metrics["agreement"] is False + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +def test_samples_expire_and_index_only_authorization_is_not_available( + tmp_path: Path, +) -> None: + sample = coordinator._SampledRegistryFilesystem(model) + sample.project(tmp_path) + sample.close() + for operation in (sample.project, sample.facts, sample.path_key): + with pytest.raises(coordinator.CoordinatorError, match="outside its preview"): + operation(tmp_path) + with pytest.raises(coordinator.CoordinatorError, match="outside its preview"): + sample.same_path(tmp_path, tmp_path) + with pytest.raises(coordinator.CoordinatorError, match="registry validation must be"): + coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="index-only" + ) + + +def test_read_only_preview_never_cleans_unclaimed_state_or_writes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + engine = coordinator.OutputCoordinator(tmp_path / "locks") + retained = _plan(tmp_path, "retained") + engine.reconcile(retained) + abandoned = engine.lock_root / "roots" / ("a" * 64) + abandoned.mkdir() + (abandoned / "snapshot.json").write_text("{}\n") + current = _plan(tmp_path, "current") + + def mutation(*args: object, **kwargs: object) -> None: + pytest.fail("read-only preview attempted a filesystem mutation") + + for name in ("_atomic_write", "_durable_mkdir", "_durable_rmtree"): + monkeypatch.setattr(coordinator, name, mutation) + assert engine._preview_registry_index((current,), set()) + assert abandoned.exists() + assert engine.validation_metrics["preview_claims"] == 1 + assert engine.validation_metrics["preview_unclaimed_states"] == 1 + + +def test_foreign_physical_alias_introduced_after_preview_is_not_missed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + retained = _plan(tmp_path, "retained") + current = _plan(tmp_path, "current") + retained.root.mkdir() + current.root.mkdir() + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="shadow" + ) + engine.reconcile(retained) + original_lstat = Path.lstat + + def alias_lstat(path: Path) -> object: + return original_lstat(current.root if path == retained.root else path) + + def inject(stage: str) -> None: + if stage == "after-index-preview": + monkeypatch.setattr(Path, "lstat", alias_lstat) + + monkeypatch.setattr(engine, "_inject", inject) + with pytest.raises(coordinator.CoordinatorError, match="overlaps a root"): + engine.reconcile(current) + assert engine.validation_metrics["preview_result"] == "accepted" + assert engine.validation_metrics["agreement"] is False + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 + + +@pytest.mark.parametrize("count", [16, 1024]) +def test_disjoint_index_query_does_not_compare_every_reservation( + monkeypatch: pytest.MonkeyPatch, count: int +) -> None: + calls = 0 + original = model.DirectoryObservation.overlaps + + def overlap(first: object, second: object) -> bool: + nonlocal calls + calls += 1 + return original(first, second) + + monkeypatch.setattr(model.DirectoryObservation, "overlaps", overlap) + index = model.OwnershipIndex( + model.Reservation( + "root", + str(number), + "build", + None, + _directory(f"/retained/{number}", number + 2), + ) + for number in range(count) + ) + assert not index.overlapping(_directory("/current/generated", count + 1000)) + assert calls == 0 + + +def test_optional_index_loader_does_not_write_bytecode_into_the_package_prefix( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + helper_source = Path(coordinator.__file__).with_name("ProtocyteOwnershipIndex.py") + (tmp_path / helper_source.name).write_bytes(helper_source.read_bytes()) + module_name = f"{coordinator.__name__}_ownership_index" + monkeypatch.setitem(sys.modules, module_name, sys.modules[module_name]) + monkeypatch.setattr( + coordinator, "__file__", str(tmp_path / "ProtocyteOutputCoordinator.py") + ) + monkeypatch.setattr(coordinator, "_ownership_module", None) + loaded = coordinator._load_ownership_index() + assert loaded.OwnershipIndex(()) + assert not (tmp_path / "__pycache__").exists() + + +def test_shadow_cli_preserves_the_claim_token_stdout_protocol( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + _plan(tmp_path, "current") + result = coordinator.main( + [ + "reconcile", + "--lock-root", + str(tmp_path / "locks"), + "--plan", + str(tmp_path / "current.plan"), + "--experimental-registry-index", + ] + ) + captured = capsys.readouterr() + assert result == 0 + tokens = captured.out.splitlines() + assert len(tokens) == 1 and coordinator._is_sha256(tokens[0]) + assert all( + line.startswith("Protocyte output coordinator:") + for line in captured.err.splitlines() + ) diff --git a/tests/test_parallel_probes.py b/tests/test_parallel_probes.py new file mode 100644 index 0000000..05c9669 --- /dev/null +++ b/tests/test_parallel_probes.py @@ -0,0 +1,1030 @@ +from __future__ import annotations + +import importlib.util +import itertools +import ctypes +import os +import random +import sys +import threading +from pathlib import Path + +import pytest + + +spec = importlib.util.spec_from_file_location( + "parallel_probe_helpers", Path(__file__).with_name("test_output_coordinator.py") +) +assert spec and spec.loader +helpers = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = helpers +spec.loader.exec_module(helpers) +coordinator = helpers.coordinator +commit = coordinator._load_observation_commit() +model = coordinator._load_ownership_index() +_modules = itertools.count() + + +@pytest.fixture(autouse=True) +def qualify_native_cases(monkeypatch): + monkeypatch.setattr(coordinator, "_COMMITTED_INDEX_QUALIFIED", True) + + +@pytest.fixture +def scope(tmp_path): + if os.name != "nt": + pytest.skip("native root-relative comparisons require Windows") + result = commit.WindowsObservationCommit( + coordinator._load_path_observation(), model + ) + try: + result.project(tmp_path) + # Qualify the transport separately, then use a new read set for tests. + result.seal() + except commit.CapabilityUnavailable as error: + pytest.skip(str(error)) + finally: + result.close() + result = commit.WindowsObservationCommit( + coordinator._load_path_observation(), model + ) + try: + yield result + finally: + result.close() + metrics = result.metrics() + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + + +@pytest.mark.parametrize("workers", [1, 2, 4]) +@pytest.mark.parametrize("size", [0, 1, 31, 32, 33, 257]) +def test_bounded_batches_preserve_order_and_retire(workers, size): + session = commit.ProbeSession(lambda number: number % 3 == 0, workers=workers) + try: + assert session.compare((number, number) for number in range(size)) == list( + range(0, size, 3) + ) + finally: + session.close() + metrics = session.metrics() + assert metrics["commit_probe_state"] == "closed" + assert metrics["commit_probe_active"] == metrics["commit_probe_pending"] == 0 + assert metrics["commit_probe_comparisons"] == size + assert ( + metrics["commit_probe_batches_started"] + == metrics["commit_probe_batches_finished"] + ) + assert metrics["commit_probe_peak_pending"] <= workers * 2 + assert metrics["commit_probe_peak_active"] <= workers + assert metrics["commit_probe_threads"] <= workers + with pytest.raises(commit.ObservationChanged, match="after retirement"): + session.compare([(0, 0)]) + + +def raw_coordinator(): + source = Path(__file__).resolve().parents[1] / "cmake/ProtocyteOutputCoordinator.py" + specification = importlib.util.spec_from_file_location( + f"parallel_default_{next(_modules)}", source + ) + module = importlib.util.module_from_spec(specification) + sys.modules[specification.name] = module + specification.loader.exec_module(module) + return module + + +@pytest.mark.parametrize("qualified", [False, True]) +@pytest.mark.parametrize("selection", [None, "auto", "reference", "REFERENCE", ""]) +def test_automatic_default_and_simple_reference_escape_hatch( + tmp_path, monkeypatch, qualified, selection +): + module = raw_coordinator() + monkeypatch.setattr(module, "_COMMITTED_INDEX_QUALIFIED", qualified) + if selection is None: + monkeypatch.delenv("PROTOCYTE_REGISTRY_VALIDATION", raising=False) + else: + monkeypatch.setenv("PROTOCYTE_REGISTRY_VALIDATION", selection) + engine = module.OutputCoordinator(tmp_path / "locks") + expected = ( + "indexed" + if qualified and os.name == "nt" and selection not in ("reference", "REFERENCE") + else "reference" + ) + assert engine.registry_validation == expected + + +def test_invalid_default_override_is_rejected_and_explicit_reference_recovers( + tmp_path, monkeypatch +): + module = raw_coordinator() + monkeypatch.setenv("PROTOCYTE_REGISTRY_VALIDATION", "unrecognized") + locks = tmp_path / "locks" + with pytest.raises(module.CoordinatorError, match="must be auto or reference"): + module.OutputCoordinator(locks) + assert not locks.exists() + assert ( + module.OutputCoordinator( + locks, registry_validation="reference" + ).registry_validation + == "reference" + ) + + +@pytest.mark.parametrize( + "override", + [ + {"commit_probe_state": "active"}, + {"commit_probe_state": "failed"}, + {"commit_probe_native_retired": False}, + {"commit_probe_native_retired": 1}, + {"commit_probe_active": 1}, + {"commit_probe_active": False}, + {"commit_probe_pending": 1}, + {"commit_probe_pending": False}, + {"commit_probe_comparisons": 1}, + {"commit_probe_comparisons": False}, + {"commit_cleanup_failed": True}, + {"commit_cleanup_failed": 0}, + ], +) +def test_incomplete_worker_accounting_cannot_authorize_mutation( + tmp_path, monkeypatch, override +): + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + plan = helpers._write_plan( + tmp_path / "plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("worker-accounting"), "sample.protocyte.hpp"),), + ) + + def incomplete(*args, **kwargs): + engine.validation_metrics.update( + commit_certificate="verified", + commit_state="closed", + commit_cleanup_failed=False, + commit_handles_opened=2, + commit_handles_closed=2, + commit_probe_state="closed", + commit_probe_native_retired=True, + commit_probe_active=0, + commit_probe_pending=0, + commit_probe_comparisons=0, + commit_fresh_comparisons=0, + ) + engine.validation_metrics.update(override) + return True + + monkeypatch.setattr(engine, "_preview_committed_index", incomplete) + assert engine.reconcile(plan) + assert engine.validation_metrics["authoritative"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + + +def test_workers_overlap_and_cannot_control_the_session(): + rendezvous = threading.Barrier(4) + entered = threading.local() + session = None + + def compare(number): + if not getattr(entered, "ready", False): + entered.ready = True + rendezvous.wait(timeout=5) + with pytest.raises(commit.ObservationChanged, match="control used by a worker"): + session.close() + return False + + session = commit.ProbeSession(compare) + try: + assert session.compare((number, number) for number in range(256)) == [] + finally: + session.close() + assert session.metrics()["commit_probe_peak_active"] == 4 + assert session.metrics()["commit_probe_threads"] == 4 + + +@pytest.mark.parametrize("error_type", [RuntimeError, KeyboardInterrupt, SystemExit]) +@pytest.mark.parametrize( + "site", ["worker", "submit-after-queue", "shutdown", "wait", "notify"] +) +def test_every_failure_drains_admitted_work(error_type, site): + first_started = threading.Event() + second_started = threading.Event() + failed = threading.Event() + wait_interrupted = threading.Event() + release = threading.Event() + finished = threading.Event() + errors, sessions, actual_shutdowns = [], [], [] + + def compare(number): + if number == 0: + first_started.set() + assert second_started.wait(5) + if site in ("worker", "shutdown", "wait", "notify"): + failed.set() + raise error_type("injected worker failure") + assert release.wait(5) + elif number == 32: + second_started.set() + assert release.wait(5) + return False + + def control(): + session = commit.ProbeSession(compare, workers=2) + sessions.append(session) + real_submit = session._executor.submit + real_shutdown = session._executor.shutdown + actual_shutdowns.append(real_shutdown) + if site == "submit-after-queue": + submissions = 0 + + def submit(*args, **kwargs): + nonlocal submissions + future = real_submit(*args, **kwargs) + submissions += 1 + if submissions == 2: + assert second_started.wait(5) + failed.set() + raise error_type("submit queued work before failing") + return future + + session._executor.submit = submit + if site == "shutdown": + + def shutdown(**kwargs): + raise error_type("injected shutdown failure") + + session._executor.shutdown = shutdown + if site in ("wait", "notify"): + real_wait = session._condition.wait + interrupted = False + + def wait(*args, **kwargs): + nonlocal interrupted + if site == "notify": + wait_interrupted.set() + elif not interrupted: + interrupted = True + wait_interrupted.set() + raise error_type("injected interruption while draining") + return real_wait(*args, **kwargs) + + session._condition.wait = wait + if site == "notify": + real_notify = session._condition.notify_all + + def notify(): + if session._active == 0: + raise error_type("injected final retirement notification failure") + return real_notify() + + session._condition.notify_all = notify + try: + session.compare((number, number) for number in range(128)) + except BaseException as error: + errors.append(error) + finally: + try: + session.close() + except BaseException: + pass + finished.set() + + thread = threading.Thread(target=control) + thread.start() + try: + assert first_started.wait(5) and second_started.wait(5) and failed.wait(5) + if site in ("wait", "notify"): + assert wait_interrupted.wait(5) + assert not finished.is_set(), ( + "retired a session with an admitted query still active" + ) + assert sessions[0].metrics()["commit_probe_active"] >= 1 + finally: + release.set() + thread.join(timeout=10) + for shutdown in actual_shutdowns: + shutdown(wait=True, cancel_futures=True) + assert not thread.is_alive() and finished.is_set() + assert len(errors) == 1 + expected = ( + commit.ProbeCleanupFailed + if site in ("shutdown", "wait") and error_type is RuntimeError + else error_type + ) + assert isinstance(errors[0], expected) + session = sessions[0] + assert session.metrics()["commit_probe_active"] == 0 + assert session.metrics()["commit_probe_pending"] == 0 + assert session.native_retired is True + # Even a job hidden by a failed submit cannot read prepared facts after close. + with pytest.raises(commit.ObservationChanged, match="after retirement"): + session._run(object()) + + +@pytest.mark.parametrize("error_type", [MemoryError, KeyboardInterrupt, SystemExit]) +@pytest.mark.parametrize("site", ["admission", "completion"]) +def test_worker_bookkeeping_failure_retires_without_holding_owner(error_type, site): + failed = threading.Event() + finished = threading.Event() + sessions, errors = [], [] + + class ThreadSet(set): + def add(self, item): + failed.set() + raise error_type("injected admission bookkeeping failure") + + class ComparisonCount(int): + def __add__(self, value): + failed.set() + raise error_type("injected completion bookkeeping failure") + + def control(): + session = commit.ProbeSession(lambda value: False, workers=1) + sessions.append(session) + if site == "admission": + session._threads = ThreadSet() + else: + session._comparisons = ComparisonCount(0) + try: + session.compare([(0, None)]) + except BaseException as error: + errors.append(error) + finally: + try: + session.close() + finally: + finished.set() + + owner = threading.Thread(target=control) + owner.start() + try: + assert failed.wait(5) + retired = finished.wait(5) + finally: + if not finished.is_set(): + # Bound this regression even on the old implementation's leaked + # counter. No native query ran in this isolated faulting session. + with sessions[0]._condition: + sessions[0]._active = 0 + sessions[0]._condition.notify_all() + owner.join(timeout=10) + assert retired, "worker accounting stranded the owner in close()" + assert not owner.is_alive() and len(errors) == 1 + assert isinstance(errors[0], error_type) + assert sessions[0].native_retired + assert sessions[0].metrics()["commit_probe_active"] == 0 + assert sessions[0].metrics()["commit_probe_pending"] == 0 + + +def test_parallel_index_matches_serial_on_randomized_ownership_and_retirement(): + def overlaps(pair): + left, right = pair + return ( + left.portable == right.portable + or left.portable.startswith(right.portable + "/") + or right.portable.startswith(left.portable + "/") + or left.location in right.ancestors + or right.location in left.ancestors + ) + + session = commit.ProbeSession(overlaps) + randomizer = random.Random(54) + try: + for _ in range(64): + facts, stable = {}, {} + paths = [Path(f"path-{number}") for number in range(96)] + for path in paths: + parent, leaf = randomizer.randrange(8), randomizer.randrange(8) + location = (7, parent * 8 + leaf + 2, ()) + ancestors = (location, (7, parent + 100, ()), (7, 1, ())) + facts[path] = model.DirectoryObservation( + f"/p{parent}/p{leaf}", location, ancestors + ) + stable[path] = randomizer.choice((True, False)) + + class Serial: + def is_stable(self, path): + return stable[path] + + def facts(self, path): + return facts[path] + + def overlaps(self, first, second): + return overlaps((facts[first], facts[second])) + + class Parallel(Serial): + probe_session = session + + def prepare_overlap(self, first, second): + return facts[first], facts[second] + + entries = [ + ( + model.Reservation( + randomizer.choice(("root", "staging")), + f"k{randomizer.randrange(8)}", + f"b{randomizer.randrange(2)}", + f"t{randomizer.randrange(2)}", + facts[path], + ), + path, + stable[path], + ) + for path in paths[:64] + ] + for _ in range(16): + arguments = dict( + root=randomizer.choice(paths), + root_key=f"k{randomizer.randrange(8)}", + build_id=f"b{randomizer.randrange(2)}", + staging=tuple( + (f"t{n}", randomizer.choice(paths)) for n in range(2) + ), + retiring_root_keys={f"k{randomizer.randrange(8)}"}, + ) + serial = commit.ProvisionalOwnershipIndex(model, Serial(), entries) + parallel = commit.ProvisionalOwnershipIndex(model, Parallel(), entries) + assert parallel.conflict(**arguments) == serial.conflict(**arguments) + finally: + session.close() + + +def test_frozen_phase_allows_only_prepared_comparisons(tmp_path, scope, monkeypatch): + first, second = tmp_path / "missing-first", tmp_path / "missing-second" + scope.facts(first) + scope.facts(second) + views = dict(scope._views) + with scope.comparisons() as reader: + with pytest.raises(commit.ObservationChanged): + scope.project(first) + with pytest.raises(commit.ObservationChanged): + scope.seal() + with pytest.raises( + commit.CommitUnavailable, match="not observed before freezing" + ): + reader.prepare_overlap(tmp_path / "never-observed", second) + prepared = reader.prepare_overlap(first, second) + assert reader.probe_session.compare([(0, prepared)] * 128) == [] + assert scope._views == views + assert reader.probe_session.metrics()["commit_probe_state"] == "closed" + with pytest.raises(commit.ObservationChanged): + reader.facts(first) + with pytest.raises(commit.ObservationChanged): + scope.facts(first) + scope.seal() + + +def test_unproved_retirement_preserves_bindings_until_cleanup_retries( + tmp_path, scope, monkeypatch +): + first, second = tmp_path / "first", tmp_path / "second" + scope.facts(first) + scope.facts(second) + with pytest.raises(commit.ProbeCleanupFailed, match="retirement is unproved"): + with scope.comparisons() as reader: + original = reader.probe_session.close + + def interrupted_before_retirement(): + raise KeyboardInterrupt("interrupted before the admission fence") + + monkeypatch.setattr( + reader.probe_session, "close", interrupted_before_retirement + ) + reader.probe_session.compare([(0, reader.prepare_overlap(first, second))]) + assert not reader.probe_session.native_retired + assert scope._state == "comparing" + assert not reader._closed and reader._views + assert scope.reader.handles_opened > scope.reader.handles_closed + with pytest.raises(commit.ProbeCleanupFailed, match="root handles cannot close"): + scope.close() + assert scope.reader.handles_opened > scope.reader.handles_closed + monkeypatch.setattr(reader.probe_session, "close", original) + scope.close() + assert reader.probe_session.native_retired + assert scope.reader.handles_opened == scope.reader.handles_closed + + +def test_impersonation_cannot_move_probes_to_a_different_context(tmp_path, scope): + from ctypes import wintypes as w + + scope.facts(tmp_path / "missing") + security = ctypes.WinDLL("advapi32", use_last_error=True) + impersonate = security.ImpersonateSelf + impersonate.argtypes = (ctypes.c_int,) + impersonate.restype = w.BOOL + revert = security.RevertToSelf + revert.argtypes = () + revert.restype = w.BOOL + if not impersonate(2): # SecurityImpersonation; only our own test-process token. + pytest.skip("self-impersonation is unavailable") + try: + with pytest.raises(commit.CapabilityUnavailable, match="impersonating caller"): + with scope.comparisons(): + pytest.fail("created workers for an impersonating caller") + assert scope._comparison_reader is None + finally: + assert revert() + # The rejection neither poisons the ordinary caller nor opens worker leases. + with scope.comparisons() as reader: + assert reader.probe_session.metrics()["commit_probe_threads"] == 0 + scope.seal() + + +@pytest.mark.parametrize("reply", ["failure", "emulated", "unknown-native"]) +def test_uncertain_process_context_rejects_workers(scope, monkeypatch, reply): + from ctypes import wintypes as w + + def machine(process, emulated, native): + ctypes.cast(emulated, ctypes.POINTER(w.WORD)).contents.value = ( + 0x14C if reply == "emulated" else 0 + ) + ctypes.cast(native, ctypes.POINTER(w.WORD)).contents.value = ( + 0 if reply == "unknown-native" else 0x8664 + ) + return reply != "failure" + + monkeypatch.setattr(scope.reader._kernel, "IsWow64Process2", machine) + with pytest.raises( + commit.CapabilityUnavailable, match="emulated filesystem context" + ): + with scope.comparisons(): + pytest.fail("started a worker in an unqualified process context") + assert scope._comparison_reader is None + + +@pytest.mark.parametrize("replacement", ["file", "dangling-junction"]) +def test_reverse_probe_still_detects_mutation_in_parallel( + tmp_path, scope, monkeypatch, replacement +): + first, second = tmp_path / "missing-first", tmp_path / "missing-second" + scope.facts(first) + scope.facts(second) + request = scope._views[str(first)].probe + original = scope._probe_absence + owner = threading.get_ident() + changed = threading.Event() + + def mutate_after_forward(observed): + original(observed) + if ( + observed is request + and threading.get_ident() != owner + and not changed.is_set() + ): + changed.set() + if replacement == "file": + first.touch() + else: + target = tmp_path / "junction-target" + target.mkdir() + helpers._directory_link(first, target) + target.rmdir() + + monkeypatch.setattr(scope, "_probe_absence", mutate_after_forward) + with pytest.raises(commit.ObservationChanged): + with scope.comparisons() as reader: + reader.probe_session.compare([(0, reader.prepare_overlap(first, second))]) + assert changed.is_set() + metrics = scope.metrics() + assert metrics["commit_probe_state"] == "closed" + assert metrics["commit_probe_active"] == metrics["commit_probe_pending"] == 0 + + +@pytest.mark.parametrize("cleanup_failure", [False, True]) +def test_worker_failure_fallback_and_fatal_cleanup_preserve_claims( + tmp_path, monkeypatch, cleanup_failure +): + if os.name != "nt": + pytest.skip("native coordinator qualification requires Windows") + plan = helpers._write_plan( + tmp_path / "current.plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("parallel"), "sample.protocyte.hpp"),), + ) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + token = engine.reconcile(plan) + state = engine._state_directory(plan.root) + claim = (state / "claim.json").read_bytes() + engine.registry_validation = "indexed" + if cleanup_failure: + original = commit.concurrent.futures.ThreadPoolExecutor.shutdown + + def failed_shutdown(self, *args, **kwargs): + original(self, *args, **kwargs) + raise RuntimeError("injected executor retirement failure") + + monkeypatch.setattr( + commit.concurrent.futures.ThreadPoolExecutor, "shutdown", failed_shutdown + ) + monkeypatch.setattr( + engine, + "_validate_registry_reference", + lambda *a, **k: pytest.fail("unsafe cleanup used reference authority"), + ) + with pytest.raises( + coordinator.CoordinatorError, match="could not be retired safely" + ): + engine.reconcile(plan) + else: + + def failed_comparison(self, prepared): + raise RuntimeError("injected native worker failure") + + monkeypatch.setattr(commit._FrozenComparisons, "_compare", failed_comparison) + assert engine.reconcile(plan) == token + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + assert (state / "claim.json").read_bytes() == claim + metrics = engine.validation_metrics + assert metrics["commit_probe_active"] == metrics["commit_probe_pending"] == 0 + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + + +@pytest.mark.parametrize("site", ["short-open", "root"]) +@pytest.mark.parametrize( + "failure", + ["false", "exception", "interrupt", "after-close", "after-close-interrupt"], +) +def test_native_release_failure_aborts_before_reference_or_mutation( + tmp_path, scope, monkeypatch, site, failure +): + plan = helpers._write_plan( + tmp_path / "current.plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("failed-release"), "sample.protocyte.hpp"),), + ) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + token = engine.reconcile(plan) + state = engine._state_directory(plan.root) + before = {path.name: path.read_bytes() for path in state.iterdir()} + original = commit.WindowsObservationCommit.__init__ + scopes, attempts, manual_cleanup = [], [], [] + + def initialize(readset, *args, **kwargs): + original(readset, *args, **kwargs) + scopes.append(readset) + raw_close = readset.reader._close + + def close(handle): + is_root = any( + volume.handle is handle for volume in readset._volumes.values() + ) + if (site == "root") == is_root and not attempts: + attempts.append(handle) + if failure in ("after-close", "after-close-interrupt"): + assert raw_close(handle) + if failure == "after-close-interrupt": + raise KeyboardInterrupt( + "interrupted after the OS closed the handle" + ) + raise RuntimeError("failed after the OS closed the handle") + manual_cleanup.append((raw_close, handle)) + if failure == "exception": + raise RuntimeError("injected native release failure") + if failure == "interrupt": + raise KeyboardInterrupt("injected native release interruption") + return False + if attempts and handle is attempts[0]: + attempts.append(handle) + return raw_close(handle) + + readset.reader._close = close + + monkeypatch.setattr(commit.WindowsObservationCommit, "__init__", initialize) + monkeypatch.setattr( + engine, + "_validate_registry_reference", + lambda *a, **k: pytest.fail("failed native cleanup authorized reference"), + ) + monkeypatch.setattr( + engine, + "_reconcile_locked", + lambda *a, **k: pytest.fail("failed native cleanup authorized mutation"), + ) + engine.registry_validation = "indexed" + expected = ( + KeyboardInterrupt + if failure in ("interrupt", "after-close-interrupt") + else coordinator.CoordinatorError + ) + try: + with pytest.raises(expected): + engine.reconcile(plan) + finally: + # Only the injector knows that these failures occurred before the OS + # call. Production must treat their completion as uncertain. + for raw_close, handle in manual_cleanup: + assert raw_close(handle) + assert len(attempts) == 1, "retried a native handle after uncertain completion" + assert {path.name: path.read_bytes() for path in state.iterdir()} == before + assert coordinator._load_json(state / "claim.json", "claim")["token"] == token + assert len(scopes) == 1 + metrics = scopes[0].metrics() + assert metrics["commit_cleanup_failed"] + assert metrics["commit_state"] == "failed" + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + 1 + + +def test_failed_scope_close_never_retries_an_uncertain_handle( + scope, tmp_path, monkeypatch +): + readset = commit.WindowsObservationCommit( + coordinator._load_path_observation(), model + ) + readset.project(tmp_path) + roots = { + id(guard.handle): guard.handle + for guard in readset._objects.values() + if guard.handle + } + raw_close = readset.reader._close + attempts = [] + + def close(handle): + if id(handle) in roots: + attempts.append(handle) + return False + return raw_close(handle) + + monkeypatch.setattr(readset.reader, "_close", close) + try: + for _ in range(2): + with pytest.raises(commit.ProbeCleanupFailed): + readset.close() + assert len(attempts) == len(roots) + metrics = readset.metrics() + assert metrics["commit_state"] == "failed" + assert metrics["commit_handles_opened"] > metrics["commit_handles_closed"] + finally: + for handle in roots.values(): + assert raw_close(handle) + + +@pytest.mark.parametrize("site", ["root", "relative"]) +@pytest.mark.parametrize("error_type", [RuntimeError, KeyboardInterrupt, SystemExit]) +@pytest.mark.parametrize("failed_close", [False, True]) +def test_interrupted_native_open_releases_unpublished_handle_before_fallback( + tmp_path, scope, monkeypatch, site, error_type, failed_close +): + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + plan = helpers._write_plan( + tmp_path / "plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("interrupted-open"), "sample.protocyte.hpp"),), + ) + token = engine.reconcile(plan) + state = engine._state_directory(plan.root) + claim = (state / "claim.json").read_bytes() + original = commit.WindowsObservationCommit.__init__ + scopes, handles, opened = [], [], [] + closed_values = set() + + def initialize(readset, *args, **kwargs): + original(readset, *args, **kwargs) + scopes.append(readset) + raw_open, raw_close = readset.reader._open, readset.reader._close + + def open_native(*args): + status = raw_open(*args) + is_root = not args[2]._obj.RootDirectory + if status >= 0 and (site == "root") == is_root and not handles: + value = ctypes.cast( + args[0], ctypes.POINTER(readset.w.HANDLE) + ).contents.value + handles.append(value) + opened.append((raw_close, readset.w.HANDLE(value))) + raise error_type("injected exception after native open completed") + return status + + def close(handle): + if failed_close and handles and handle.value == handles[0]: + return False + result = raw_close(handle) + if result: + closed_values.add(handle.value) + return result + + readset.reader._open = open_native + readset.reader._close = close + + monkeypatch.setattr(commit.WindowsObservationCommit, "__init__", initialize) + engine.registry_validation = "indexed" + try: + if failed_close: + monkeypatch.setattr( + engine, + "_validate_registry_reference", + lambda *a, **k: pytest.fail( + "unreleased native open used reference authority" + ), + ) + with pytest.raises(coordinator.CoordinatorError): + engine.reconcile(plan) + elif error_type is RuntimeError: + assert engine.reconcile(plan) == token + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + else: + with pytest.raises(error_type): + engine.reconcile(plan) + finally: + for raw_close, handle in opened: + if handle.value not in closed_values: + assert raw_close(handle) + assert len(handles) == 1 and len(scopes) == 1 + metrics = scopes[0].metrics() + assert metrics["commit_handles_opened"] > 0 + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + int( + failed_close + ) + assert (state / "claim.json").read_bytes() == claim + + +@pytest.mark.parametrize("previous_has_cleanup_error", [False, True]) +def test_previous_helper_during_upgrade_uses_reference_without_token_rotation( + tmp_path, monkeypatch, previous_has_cleanup_error +): + from types import ModuleType + + previous = ModuleType("previous_observation_helper") + # Both pre-pool and pre-review helper API shapes remain safe fallbacks. + # Actual pinned implementations run in verify_coordinator_upgrade.py; + # ordinary unit tests must work in archives and shallow/squashed checkouts. + if previous_has_cleanup_error: + previous.ProbeCleanupFailed = type("ProbeCleanupFailed", (RuntimeError,), {}) + assert not hasattr(previous, "COMMIT_CONTRACT_VERSION") + + def unavailable(*args, **kwargs): + pytest.fail("opened an incompatible helper during a partial upgrade") + + previous.WindowsObservationCommit = unavailable + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + plan = helpers._write_plan( + tmp_path / "plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("mixed-helper"), "sample.protocyte.hpp"),), + ) + token = engine.reconcile(plan) + state = engine._state_directory(plan.root) + claim = (state / "claim.json").read_bytes() + monkeypatch.setattr(coordinator, "_observation_commit_module", previous) + monkeypatch.setattr(coordinator, "_load_observation_commit", lambda: previous) + engine.registry_validation = "indexed" + assert engine.reconcile(plan) == token + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + assert (state / "claim.json").read_bytes() == claim + + +@pytest.mark.parametrize("contract", [None, False, 1, 3, "2", 2.0]) +def test_unknown_helper_contract_falls_back_before_acquiring_handles( + tmp_path, monkeypatch, contract +): + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + plan = helpers._write_plan( + tmp_path / "plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("helper-contract"), "sample.protocyte.hpp"),), + ) + token = engine.reconcile(plan) + monkeypatch.setattr(commit, "COMMIT_CONTRACT_VERSION", contract) + monkeypatch.setattr( + commit, + "WindowsObservationCommit", + lambda *a, **k: pytest.fail("opened a scope through an incompatible helper"), + ) + engine.registry_validation = "indexed" + assert engine.reconcile(plan) == token + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "accepted" + assert "commit_handles_opened" not in engine.validation_metrics + + +@pytest.mark.parametrize("dependency", ["ownership", "path"]) +@pytest.mark.parametrize("contract", [None, True, 0, 2, "1", 1.0]) +def test_unknown_dependency_contract_falls_back_before_acquiring_handles( + tmp_path, monkeypatch, dependency, contract +): + module, marker = ( + (model, "OWNERSHIP_CONTRACT_VERSION") + if dependency == "ownership" + else (coordinator._load_path_observation(), "PATH_CONTRACT_VERSION") + ) + monkeypatch.setattr(module, marker, contract) + monkeypatch.setattr( + commit, + "WindowsObservationCommit", + lambda *a, **k: pytest.fail( + "opened a scope through an incompatible dependency" + ), + ) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + plan = helpers._write_plan( + tmp_path / "plan", + tmp_path / "generated", + tmp_path / "build", + ((helpers._target("dependency-contract"), "sample.protocyte.hpp"),), + ) + assert engine.reconcile(plan) + assert engine.validation_metrics["fallback"] == "reference" + assert "commit_handles_opened" not in engine.validation_metrics + + +@pytest.mark.parametrize( + "filename,marker,loader", + [ + ( + "ProtocyteObservationCommit.py", + "COMMIT_CONTRACT_VERSION", + "_load_observation_commit", + ), + ( + "ProtocyteOwnershipIndex.py", + "OWNERSHIP_CONTRACT_VERSION", + "_load_ownership_index", + ), + ( + "ProtocytePathObservation.py", + "PATH_CONTRACT_VERSION", + "_load_path_observation", + ), + ], +) +def test_valid_truncated_helper_cannot_authorize_an_index( + tmp_path, monkeypatch, filename, marker, loader +): + from types import ModuleType + + path = Path(__file__).resolve().parents[1] / "cmake" / filename + source = path.read_text() + if filename == "ProtocyteObservationCommit.py": + # Keep a valid but incomplete conflict() that checks roots and then + # implicitly accepts without checking current staging reservations. + source = source.rsplit(" for target, path in staging:", 1)[0] + else: + source = source.rsplit(marker + " =", 1)[0] + incomplete = ModuleType(f"incomplete_helper_{next(_modules)}") + sys.modules[incomplete.__name__] = incomplete + exec(compile(source, filename, "exec"), incomplete.__dict__) + assert not hasattr(incomplete, marker) + # Older coordinators do not inspect the marker themselves. The helper's + # entry point must reject the partial file before touching OS resources. + if filename == "ProtocyteObservationCommit.py": + with pytest.raises(incomplete.CapabilityUnavailable, match="incomplete"): + incomplete.WindowsObservationCommit( + coordinator._load_path_observation(), model + ) + elif filename == "ProtocytePathObservation.py": + with pytest.raises(incomplete.ObservationUnavailable, match="incomplete"): + incomplete.FreshPathObserver() + else: + with pytest.raises(RuntimeError, match="incomplete"): + incomplete.OwnershipIndex(()) + monkeypatch.setattr(coordinator, loader, lambda: incomplete) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="indexed" + ) + target = helpers._target("truncated-contract") + current_root = tmp_path / "generated" + staging = tmp_path / f".protocyte-generation-staging-{target}" + retained = helpers._write_plan( + tmp_path / "retained.plan", + staging / "foreign", + tmp_path / "old-build", + ((helpers._target("foreign"), "old.protocyte.hpp"),), + ) + engine.registry_validation = "reference" + engine.reconcile(retained) + current = helpers._write_plan( + tmp_path / "current.plan", + current_root, + tmp_path / "build", + ((target, "sample.protocyte.hpp"),), + ) + engine.registry_validation = "indexed" + with pytest.raises( + coordinator.CoordinatorError, match="staging overlaps a claimed output root" + ): + engine.reconcile(current) + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["reference_result"] == "rejected" + assert not engine._state_directory(current.root).exists() diff --git a/tests/test_path_observation.py b/tests/test_path_observation.py new file mode 100644 index 0000000..0392dbc --- /dev/null +++ b/tests/test_path_observation.py @@ -0,0 +1,361 @@ +from __future__ import annotations + +import importlib.util +import ctypes +import os +import struct +import sys +from pathlib import Path + +import pytest + + +_spec = importlib.util.spec_from_file_location( + "path_observation_test_helpers", + Path(__file__).with_name("test_output_coordinator.py"), +) +assert _spec is not None and _spec.loader is not None +_helpers = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = _helpers +_spec.loader.exec_module(_helpers) +coordinator = _helpers.coordinator +native = coordinator._load_path_observation() + + +@pytest.fixture +def observer(): + if os.name != "nt": + pytest.skip("native no-reparse opens require Windows") + reader = native.FreshPathObserver() + try: + yield reader + finally: + reader.close() + assert reader.handles_opened == reader.handles_closed + + +def _plan(tmp_path: Path, name: str): + return _helpers._write_plan( + tmp_path / f"{name}.plan", + tmp_path / name / "generated", + tmp_path / name / "build", + ((_helpers._target(name), "sample.protocyte.hpp"),), + ) + + +@pytest.mark.parametrize("missing_depth", [0, 1, 6]) +def test_native_projection_matches_reference_for_existing_and_missing_paths( + tmp_path: Path, observer, missing_depth: int +) -> None: + existing = tmp_path / "mixed Case ü 🧬" + existing.mkdir() + path = existing.joinpath(*(f"missing-{n}" for n in range(missing_depth))) + assert observer.project(path) == coordinator.project_path(path) + assert observer.handles_opened == observer.handles_closed + assert observer.project(path) == coordinator.project_path(path) + assert observer.projections == 2 + + +def test_native_observations_do_not_cache_absence_or_existing_identity( + tmp_path: Path, observer +) -> None: + path = tmp_path / "changing" + assert observer.project(path) == path + opened = observer.open_calls + path.mkdir() + assert observer.project(path) == path + assert observer.open_calls > opened + path.rmdir() + path.write_text("foreign file") + with pytest.raises(native.UnsafeObservation, match="non-directory"): + observer.project(path) + + +def test_native_projection_distinguishes_regular_file_leaf_from_ancestor( + tmp_path: Path, observer +) -> None: + path = tmp_path / "sample.json" + path.write_text("{}") + assert observer.project(path, leaf_may_be_file=True) == path + for candidate in (path, path / "nested"): + with pytest.raises((native.UnsafeObservation, OSError)): + observer.project(candidate) + + +def test_native_reparse_traversal_is_rejected_at_leaf_and_ancestor( + tmp_path: Path, observer +) -> None: + target = tmp_path / "ordinary" + target.mkdir() + link = tmp_path / "link" + _helpers._directory_link(link, target) + for path in (link, link / "missing", link / "missing" / "leaf"): + with pytest.raises((native.UnsafeObservation, OSError)): + observer.project(path) + + +def test_native_rejects_missing_ancestor_replaced_by_junction_on_next_call( + tmp_path: Path, observer +) -> None: + path = tmp_path / "missing" / "generated" + assert observer.project(path) == path + outside = tmp_path / "outside" + outside.mkdir() + _helpers._directory_link(path.parent, outside) + with pytest.raises((native.UnsafeObservation, OSError)): + observer.project(path) + + +def test_readonly_handle_cannot_be_treated_as_a_reparse_stability_lease( + tmp_path: Path, observer +) -> None: + """Counterexample to promoting share-restricted handles into cached authority.""" + from ctypes import wintypes as w + + victim, target = tmp_path / "victim", tmp_path / "target" + victim.mkdir() + target.mkdir() + create = observer._kernel.CreateFileW + create.argtypes = ( + w.LPCWSTR, + w.DWORD, + w.DWORD, + w.LPVOID, + w.DWORD, + w.DWORD, + w.HANDLE, + ) + create.restype = w.HANDLE + control = observer._kernel.DeviceIoControl + control.argtypes = ( + w.HANDLE, + w.DWORD, + w.LPVOID, + w.DWORD, + w.LPVOID, + w.DWORD, + ctypes.POINTER(w.DWORD), + w.LPVOID, + ) + control.restype = w.BOOL + invalid = ctypes.c_void_p(-1).value + handles = [] + try: + # Denying write/delete sharing does not constrain attribute-only access. + pin = create(str(victim), 0x80, 1, None, 3, 0x02200000, None) + assert pin != invalid + handles.append(pin) + writer = create(str(victim), 0x100, 7, None, 3, 0x02200000, None) + assert writer != invalid + handles.append(writer) + substitute = ("\\??\\" + str(target)).encode("utf-16-le") + printable = str(target).encode("utf-16-le") + names = substitute + b"\x00\x00" + printable + b"\x00\x00" + data = ( + struct.pack( + " None: + def fail(*args, **kwargs): + raise RuntimeError("injected description failure") + + monkeypatch.setattr(observer, "_describe", fail) + with pytest.raises(RuntimeError, match="description failure"): + observer.project(tmp_path) + assert observer.handles_opened == observer.handles_closed + observer.close() + with pytest.raises(native.UnsafeObservation, match="outside its scope"): + observer.project(tmp_path) + + +def test_unexpected_success_status_closes_its_native_handle( + tmp_path: Path, observer, monkeypatch: pytest.MonkeyPatch +) -> None: + original = observer._open + + def informational(*args): + assert original(*args) == 0 + return 1 + + monkeypatch.setattr(observer, "_open", informational) + with pytest.raises(native.UnsafeObservation, match="unsupported result"): + observer.project(tmp_path) + assert observer.handles_opened == observer.handles_closed == 1 + + +def test_permission_error_is_not_cached_or_reinterpreted_as_absence( + tmp_path: Path, observer, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(observer, "_open", lambda *args: -1073741790) # ACCESS_DENIED + with pytest.raises(PermissionError): + observer.project(tmp_path) + assert observer.open_calls == 1 + assert observer.handles_opened == 0 + + +@pytest.mark.parametrize( + "name", + ["relative", "C:\\data:stream", "\\\\server\\share\\folder", "\\\\?\\C:\\folder"], +) +def test_unsupported_names_cannot_acquire_native_authority(name: str) -> None: + with pytest.raises(native.ObservationUnavailable): + native.FreshPathObserver._native_name(Path(name)) + + +def test_default_validation_never_loads_native_observer( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def unexpected(): + pytest.fail("reference validation loaded the native observer") + + monkeypatch.setattr(coordinator, "_load_path_observation", unexpected) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="reference" + ) + assert engine.reconcile(_plan(tmp_path, "current")) + + +def test_native_shadow_authenticates_all_records_and_reference_remains_authority( + tmp_path: Path, +) -> None: + if os.name != "nt": + pytest.skip("native no-reparse opens require Windows") + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="native-shadow" + ) + engine.reconcile_set((), [_plan(tmp_path, "first"), _plan(tmp_path, "second")]) + assert engine.reconcile(_plan(tmp_path, "current")) + metrics = engine.validation_metrics + assert metrics["authoritative"] == "reference" + assert metrics["agreement"] is True + assert metrics["native_claims_checked"] == 2 + assert metrics["native_handles_opened"] == metrics["native_handles_closed"] + + +def test_native_capability_failure_uses_reference_without_migration_or_new_flags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def unavailable(): + raise native.ObservationUnavailable("injected unsupported filesystem") + + monkeypatch.setattr(native, "FreshPathObserver", unavailable) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="native-shadow" + ) + assert engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["fallback"] == "reference" + assert engine.validation_metrics["agreement"] is None + + +def test_extended_namespace_upgrade_preserves_claim_through_reference_fallback( + tmp_path: Path, +) -> None: + if os.name != "nt": + pytest.skip("explicit Windows namespace paths require Windows") + root = Path("\\\\?\\" + str(tmp_path / "generated")) + plan = _helpers._write_plan( + tmp_path / "extended.plan", + root, + tmp_path / "build", + ((_helpers._target("extended"), "sample.protocyte.hpp"),), + ) + locks = tmp_path / "locks" + reference = coordinator.OutputCoordinator(locks, registry_validation="reference") + token = reference.reconcile(plan) + before = (reference._state_directory(plan.root) / "claim.json").read_bytes() + observed = coordinator.OutputCoordinator(locks, registry_validation="native-shadow") + assert observed.reconcile(plan) == token + assert observed.validation_metrics["fallback"] == "reference" + assert (reference._state_directory(plan.root) / "claim.json").read_bytes() == before + + +def test_native_sample_error_cannot_authorize_even_if_reference_accepts( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def broken(): + raise RuntimeError("injected observer failure") + + monkeypatch.setattr(native, "FreshPathObserver", broken) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="native-shadow" + ) + with pytest.raises(coordinator.CoordinatorError, match="disagrees"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "accepted" + assert not list((engine.lock_root / "roots").glob("*/claim.json")) + + +def test_native_scope_close_error_still_runs_reference_before_fail_closed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + if os.name != "nt": + pytest.skip("native no-reparse opens require Windows") + original = native.FreshPathObserver.close + + def broken_close(self): + original(self) + raise RuntimeError("injected scope close failure") + + monkeypatch.setattr(native.FreshPathObserver, "close", broken_close) + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="native-shadow" + ) + with pytest.raises(coordinator.CoordinatorError, match="disagrees"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["reference_result"] == "accepted" + assert not list((engine.lock_root / "roots").glob("*/claim.json")) + + +def test_foreign_replacement_after_native_phase_is_rejected_before_new_claims( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + if os.name != "nt": + pytest.skip("native no-reparse opens require Windows") + engine = coordinator.OutputCoordinator( + tmp_path / "locks", registry_validation="native-shadow" + ) + retained = _plan(tmp_path, "retained") + engine.reconcile(retained) + + def replace(stage: str): + if stage == "after-native-observation": + retained.root.touch() + + monkeypatch.setattr(engine, "_inject", replace) + with pytest.raises(coordinator.CoordinatorError, match="non-directory"): + engine.reconcile(_plan(tmp_path, "current")) + assert engine.validation_metrics["preview_result"] == "accepted" + assert engine.validation_metrics["reference_result"] == "rejected" + assert len(list((engine.lock_root / "roots").glob("*/claim.json"))) == 1 diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 166965c..150cab1 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -4354,10 +4354,17 @@ def test_command_line_plugin_formatter_timeout_stops_hanging_process_tree( ) -> None: grandchild_ready = tmp_path / "formatter-grandchild-ready" child_survived = tmp_path / "formatter-child-survived" - grandchild = ( - "from pathlib import Path; import time; " - f"Path({str(grandchild_ready)!r}).touch(); time.sleep(1); " - f"Path({str(child_survived)!r}).touch()" + child_release = tmp_path / "formatter-child-release" + grandchild = "\n".join( + [ + "from pathlib import Path", + "import time", + f"Path({str(grandchild_ready)!r}).touch()", + "deadline = time.monotonic() + 15", + f"while not Path({str(child_release)!r}).exists() and time.monotonic() < deadline:", + " time.sleep(0.01)", + f"Path({str(child_survived)!r}).touch()", + ] ) child = ( "import subprocess, sys, time; " @@ -4392,21 +4399,27 @@ def test_command_line_plugin_formatter_timeout_stops_hanging_process_tree( ) formatter.chmod(0o755) + # Windows can start several interpreter/redirector processes here. Give + # startup its own margin, then release the descendant only after timeout; + # this tests tree termination rather than a 0.5-second startup assumption. response = generate_response( _basic_request( parameter=( - f"clang_format={formatter.as_posix()},formatter_timeout_seconds=0.5" + f"clang_format={formatter.as_posix()},formatter_timeout_seconds=5" ) ), use_plugin_defaults=True, ) - assert ( - "clang-format timed out for simple.protocyte.hpp after 0.5 seconds" - in response.error - ) - assert not response.file - assert grandchild_ready.is_file() + try: + assert ( + "clang-format timed out for simple.protocyte.hpp after 5.0 seconds" + in response.error + ) + assert not response.file + assert grandchild_ready.is_file() + finally: + child_release.touch() time.sleep(1.25) assert not child_survived.exists() diff --git a/tests/verify_consumer_registry.py b/tests/verify_consumer_registry.py new file mode 100644 index 0000000..363d213 --- /dev/null +++ b/tests/verify_consumer_registry.py @@ -0,0 +1,451 @@ +"""Non-authorizing qualification against private, real consumer inputs. + +The private manifest supplies registry/current_plans/legacy_coordinator paths. +Capture copies immutable ledger bytes under the original locks; references run +against those frozen bytes and the original output/build/staging paths. Live +candidate/indexed runs always use the original registry and lock namespace. +Indexed exercises the production validation entry point, without proceeding to +reconciliation. No command resets, publishes, or changes defaults. Publish only +the sanitized result receipts; the preservation manifest stays private. +""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import inspect +import json +import os +import platform +import stat +import sys +import time +from pathlib import Path +from types import ModuleType + +LEGACY_SHA256 = "2ff54b69242d46eb8e35a52d30b32bc9afd815c00b6c0abeb8765d6fe7ddbb85" +IMPLEMENTATION = ( + "ProtocyteOutputCoordinator.py", + "ProtocyteOwnershipIndex.py", + "ProtocytePathObservation.py", + "ProtocyteObservationCommit.py", +) + + +def digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def load(path: Path, name: str) -> ModuleType: + specification = importlib.util.spec_from_file_location(name, path) + assert specification is not None and specification.loader is not None + module = importlib.util.module_from_spec(specification) + sys.modules[name] = module + exec(compile(path.read_bytes(), str(path), "exec"), module.__dict__) + return module + + +def forbid_mutations(module: ModuleType) -> None: + def forbidden(*args, **kwargs): + raise RuntimeError("qualification attempted an ownership/output mutation") + + for name in ( + "_atomic_write", + "_durable_rmtree", + "_durable_unlink", + "_durable_rename", + ): + if hasattr(module, name): + setattr(module, name, forbidden) + for name in ( + "reconcile", + "reconcile_set", + "_reconcile_locked", + "publish", + "reset", + "_recover", + "_apply_pending", + "_publish_one", + "_initialize_claim_locked", + "_release_claim", + "_retire_unplanned", + "_retire_staging", + ): + if hasattr(module.OutputCoordinator, name): + setattr(module.OutputCoordinator, name, forbidden) + + +def ledger(registry: Path) -> dict[str, dict[str, str]]: + def plain(info, expected_type) -> bool: + return ( + expected_type(info.st_mode) + and not stat.S_ISLNK(info.st_mode) + and not getattr(info, "st_file_attributes", 0) & 0x400 + ) + + result = {} + roots = registry / "roots" + assert plain(roots.lstat(), stat.S_ISDIR), "unsafe source registry directory" + for state in sorted(roots.iterdir()): + assert len(state.name) == 64 and all( + c in "0123456789abcdef" for c in state.name + ) + assert plain(state.lstat(), stat.S_ISDIR), "unsafe source registry state" + values = {} + for name in ("claim.json", "plan.json"): + record = state / name + try: + info = record.lstat() + except FileNotFoundError: + continue + assert plain(info, stat.S_ISREG), "unsafe source registry record" + data = record.read_bytes() + values[name] = digest(data) + result[state.name] = values + return result + + +@contextlib.contextmanager +def original_locks(module, engine, plans, *, progress=None): + with contextlib.ExitStack() as stack: + if progress is not None: + progress.phase("waiting for original registry lock", "lock_wait") + stack.enter_context(module.FileLock(engine.lock_root / "registry.lock")) + roots = {module._path_key(plan.root): plan.root for plan in plans} + ordered = sorted(roots.values(), key=module._portable_identity) + if progress is not None: + progress.phase("waiting for original generation locks", "lock_wait") + for root in ordered: + stack.enter_context(module.FileLock(engine._generation_lock(root))) + if progress is not None: + progress.phase("waiting for original publication locks", "lock_wait") + for root in ordered: + stack.enter_context(module.FileLock(engine._publication_lock(root))) + yield + + +def output_fingerprints(module, engine, plans) -> dict: + result = {} + for number, plan in enumerate(plans): + state = engine._state_directory(plan.root) + claim = engine._load_claim(state, plan) + engine._require_current_plan(state, plan, claim) + snapshot = engine._load_snapshot(state, claim) + for relative, entry in snapshot["entries"].items(): + path = plan.root / relative + assert module.project_path(path, leaf_may_be_file=True) == path + assert not module._is_link(path), "consumer output is a link" + data = path.read_bytes() + assert digest(data) == entry["sha256"], ( + "consumer output differs from committed snapshot" + ) + # File names and tokens stay in the private in-memory audit only. + result[str(path)] = (digest(data), path.stat().st_mtime_ns) + assert not list((state / "transactions").iterdir()), ( + "consumer has pending recovery" + ) + result[f"claim-{number}"] = digest((state / "claim.json").read_bytes()) + result[f"snapshot-{number}"] = digest((state / "snapshot.json").read_bytes()) + return result + + +def capture(module, manifest: dict, work: Path) -> dict: + registry = Path(manifest["registry"]) + engine = module.OutputCoordinator(registry) + paths = [Path(path) for path in manifest["current_plans"]] + assert paths and not manifest.get("retired_plans"), ( + "this qualification requires a stable current plan set" + ) + plans = [module.Plan.read(path) for path in paths] + destination = work / "ledger" + destination.mkdir() + with ( + module._ReconcileProgress(len(plans), 0) as progress, + original_locks(module, engine, plans, progress=progress), + ): + progress.phase("capturing read-only consumer ledger", "validation") + forbid_mutations(module) + before = ledger(registry) + assert all("claim.json" in files for files in before.values()) + outputs_before = output_fingerprints(module, engine, plans) + (destination / "roots").mkdir() + for state, files in before.items(): + copied = destination / "roots" / state + copied.mkdir() + for name, expected in files.items(): + data = (registry / "roots" / state / name).read_bytes() + assert digest(data) == expected + (copied / name).write_bytes(data) + inputs = work / "inputs" + inputs.mkdir() + for number, path in enumerate(paths): + (inputs / f"{number:03}.plan").write_bytes(path.read_bytes()) + assert ledger(registry) == before + assert ledger(destination) == before + assert output_fingerprints(module, engine, plans) == outputs_before + (work / "preservation.private.json").write_text( + json.dumps({"ledger": before, "outputs": outputs_before}) + "\n" + ) + receipt = { + "registry_entries": len(before), + "ledger_records": sum(map(len, before.values())), + "current_plans": len(plans), + "targets_per_plan": [len(plan.targets) for plan in plans], + "declared_outputs": sum(len(plan.outputs) for plan in plans), + "committed_output_files_checked": len(outputs_before) - 2 * len(plans), + "claims_plans_snapshots_and_outputs_unchanged": True, + "snapshot_byte_identical": True, + "tokens_produced": 0, + "reconciliation_authorized": False, + } + (work / "capture.json").write_text(json.dumps(receipt, indent=2) + "\n") + return receipt + + +def reference(module, manifest: dict, work: Path) -> dict: + # The namespace-only pass executes the actual reference checks with its + # original registry location. Only its root listing is empty; the separate + # full pass below validates every copied foreign record without filtering. + original = module.OutputCoordinator(Path(manifest["registry"])) + plans = [ + module.Plan.read(path) for path in sorted((work / "inputs").glob("*.plan")) + ] + call_name = ( + "_validate_registry_reference" + if hasattr(original, "_validate_registry_reference") + else "_validate_registry" + ) + forbid_mutations(module) + real_scandir = module.os.scandir + + class EmptyListing: + def __enter__(self): + return iter(()) + + def __exit__(self, *args): + pass + + def namespace_listing(path): + if Path(path) == original.lock_root / "roots": + return EmptyListing() + return real_scandir(path) + + module.os.scandir = namespace_listing + try: + getattr(original, call_name)(plans, set()) + finally: + module.os.scandir = real_scandir + engine = module.OutputCoordinator(work / "ledger") + before = ledger(engine.lock_root) + start, cpu = time.perf_counter(), time.process_time() + with module._ReconcileProgress(len(plans), 0) as progress: + progress.phase("read-only frozen consumer reference", "validation") + module.OutputCoordinator._validate_plan_set(plans) + function = getattr(engine, call_name) + kwargs = ( + {"progress": progress} + if "progress" in inspect.signature(function).parameters + else {} + ) + function(plans, set(), **kwargs) + checked = progress._claims + seconds = time.perf_counter() - start + cpu_seconds = time.process_time() - cpu + assert ledger(engine.lock_root) == before + return { + "result": "accepted", + "registry_entries": len(before), + "claims_checked": checked, + "validation_seconds": seconds, + "validation_cpu_seconds": cpu_seconds, + "frozen_ledger": True, + "original_output_paths": True, + "original_namespace_checked_separately": True, + "live_shared_lock_held": False, + "ownership_or_output_mutations": 0, + } + + +def candidate( + module, + manifest: dict, + work: Path, + *, + integrated: bool = False, + default_mode: bool = False, +) -> dict: + engine = module.OutputCoordinator( + Path(manifest["registry"]), + **( + {} + if default_mode + else {"registry_validation": "indexed" if integrated else "reference"} + ), + ) + if default_mode: + assert module._COMMITTED_INDEX_QUALIFIED is True + assert engine.registry_validation == "indexed" + if integrated: + # A failed timing gate must not hold the live shared lock for a slow + # reference pass. The full reference oracles are qualified separately; + # successful production entry-point execution must never call this. + def unexpected_reference(*args, **kwargs): + raise RuntimeError("live indexed qualification required reference fallback") + + engine._validate_registry_reference = unexpected_reference + start = time.perf_counter() + plans = [module.Plan.read(Path(path)) for path in manifest["current_plans"]] + parse_seconds = time.perf_counter() - start + start = time.perf_counter() + with ( + module._ReconcileProgress(len(plans), 0) as progress, + original_locks(module, engine, plans, progress=progress), + ): + lock_seconds = time.perf_counter() - start + forbid_mutations(module) + progress.phase("read-only live consumer candidate", "validation") + start, cpu = time.perf_counter(), time.process_time() + engine.validation_metrics = { + "mode": "consumer-candidate-only", + "authoritative": "none", + } + module.OutputCoordinator._validate_plan_set(plans) + if integrated: + qualified = module._COMMITTED_INDEX_QUALIFIED + try: + # The ownership/output mutation guard above is already active. + # Override only this import, never a consumer process or file. + module._COMMITTED_INDEX_QUALIFIED = True + engine._validate_registry(plans, set(), progress=progress) + finally: + module._COMMITTED_INDEX_QUALIFIED = qualified + accepted = True + else: + accepted = engine._preview_committed_index(plans, set(), progress=progress) + seconds = time.perf_counter() - start + parse_seconds + cpu_seconds = time.process_time() - cpu + metrics = engine.validation_metrics + assert metrics["commit_certificate"] == "verified" + assert metrics["commit_state"] == "closed" + assert metrics["commit_handles_opened"] == metrics["commit_handles_closed"] + assert metrics["commit_cleanup_failed"] is False + assert metrics["commit_probe_state"] == "closed" + assert metrics["commit_probe_native_retired"] is True + assert metrics["commit_probe_active"] == metrics["commit_probe_pending"] == 0 + assert metrics["commit_probe_comparisons"] == metrics["commit_fresh_comparisons"] + assert metrics["commit_probe_peak_active"] <= metrics["commit_probe_workers"] <= 4 + assert metrics["commit_probe_peak_pending"] <= 2 * metrics["commit_probe_workers"] + if integrated: + assert metrics["authoritative"] == "index" + assert metrics["reference_wall_seconds"] == 0 + return { + "result": "accepted" if accepted else "conflict", + "validation_seconds": seconds, + "validation_cpu_seconds": cpu_seconds, + "plan_parse_seconds": parse_seconds, + "lock_wait_seconds": lock_seconds, + "current_plans": len(plans), + "registry_entries": metrics["commit_claims_checked"], + "original_live_registry_and_locks": True, + "native_metrics": metrics, + "ownership_or_output_mutations": 0, + "tokens_produced": 0, + } + + +def audit(module, manifest: dict, work: Path) -> dict: + engine = module.OutputCoordinator( + Path(manifest["registry"]), registry_validation="reference" + ) + plans = [module.Plan.read(Path(path)) for path in manifest["current_plans"]] + expected = json.loads((work / "preservation.private.json").read_bytes()) + with original_locks(module, engine, plans): + forbid_mutations(module) + assert ledger(engine.lock_root) == expected["ledger"] + outputs = output_fingerprints(module, engine, plans) + assert json.loads(json.dumps(outputs)) == expected["outputs"] + return { + "registry_entries": len(expected["ledger"]), + "committed_output_files_checked": len(outputs) - 2 * len(plans), + "claims_plans_snapshots_outputs_and_mtimes_unchanged": True, + "ownership_or_output_mutations": 0, + "tokens_produced": 0, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--work", type=Path, required=True) + parser.add_argument( + "--mode", + choices=( + "capture", + "candidate", + "indexed", + "default", + "audit", + "reference", + "legacy-reference", + ), + required=True, + ) + args = parser.parse_args() + driver_fingerprint = digest(Path(__file__).read_bytes()) + args.work = args.work.absolute() + sys.dont_write_bytecode = True + os.environ.pop("PROTOCYTE_COORDINATOR_CRASH_AFTER", None) + manifest = json.loads(args.manifest.read_bytes()) + if args.mode == "capture": + args.work.mkdir(parents=True, exist_ok=False) + else: + assert args.work.is_dir() + source = Path(__file__).resolve().parents[1] / "cmake/ProtocyteOutputCoordinator.py" + if args.mode == "legacy-reference": + source = Path(manifest["legacy_coordinator"]) + assert digest(source.read_bytes()) == LEGACY_SHA256 + fingerprints = {source.name: digest(source.read_bytes())} + if args.mode != "legacy-reference": + fingerprints = { + name: digest(source.with_name(name).read_bytes()) for name in IMPLEMENTATION + } + module = load(source, "qualified_consumer_" + args.mode.replace("-", "_")) + production_qualified = getattr(module, "_COMMITTED_INDEX_QUALIFIED", False) + if args.mode == "capture": + result = capture(module, manifest, args.work) + elif args.mode in ("candidate", "indexed", "default"): + result = candidate( + module, + manifest, + args.work, + integrated=args.mode != "candidate", + default_mode=args.mode == "default", + ) + elif args.mode == "audit": + result = audit(module, manifest, args.work) + else: + result = reference(module, manifest, args.work) + assert all( + digest(source.with_name(name).read_bytes()) == expected + for name, expected in fingerprints.items() + ) + assert digest(Path(__file__).read_bytes()) == driver_fingerprint + report = { + "mode": args.mode, + "platform": platform.system(), + "python": platform.python_version(), + "implementation_files": fingerprints, + "qualification_driver_sha256": driver_fingerprint, + "index_authorization_enabled": production_qualified, + **result, + } + (args.work / f"{args.mode}-{time.time_ns()}-results.json").write_text( + json.dumps(report, indent=2) + "\n" + ) + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/verify_coordinator_upgrade.py b/tests/verify_coordinator_upgrade.py new file mode 100644 index 0000000..ab0066d --- /dev/null +++ b/tests/verify_coordinator_upgrade.py @@ -0,0 +1,564 @@ +"""Offline protocol-v1 upgrade/rollback and crash-recovery qualification. + +Run with Python 3.12+ from a checkout containing the pinned public source blob +and preservation checkpoint. Every case uses a fresh private registry. No consumer +registry or remote service is accessed. Publish upgrade-results.json only; the +fixture records and subprocess logs can contain private paths and claim tokens. +""" + +from __future__ import annotations + +import ast +import argparse +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--work", type=Path, help="new private result/fixture directory" + ) + options = parser.parse_args() + REPO = Path(__file__).resolve().parents[1] + WORK = ( + options.work.absolute() + if options.work + else Path(tempfile.mkdtemp(prefix="protocyte-upgrade-")) + ) + if options.work: + WORK.mkdir(parents=True, exist_ok=False) + LEGACY = WORK / "legacy/ProtocyteOutputCoordinator.py" + CURRENT = REPO / "cmake/ProtocyteOutputCoordinator.py" + LEGACY.parent.mkdir() + LEGACY.write_bytes( + subprocess.check_output( + [ + "git", + "show", + "25f1660190d3d1015fef3955814c8c737bd686c5", + ], + cwd=REPO, + ) + ) + assert ( + hashlib.sha256(LEGACY.read_bytes()).hexdigest() + == "2ff54b69242d46eb8e35a52d30b32bc9afd815c00b6c0abeb8765d6fe7ddbb85" + ) + IMPLEMENTATION = ( + CURRENT, + *( + CURRENT.with_name(name) + for name in ( + "ProtocyteOwnershipIndex.py", + "ProtocytePathObservation.py", + "ProtocyteObservationCommit.py", + ) + ), + ) + EXPECTED_SOURCES = { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in IMPLEMENTATION + } + + def load(name: str, script: Path): + spec = importlib.util.spec_from_file_location(name, script) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + exec(compile(script.read_bytes(), os.fspath(script), "exec"), module.__dict__) + return module + + old = load("review_legacy", LEGACY) + new = load("review_current", CURRENT) + production_qualified = new._COMMITTED_INDEX_QUALIFIED + # Only isolated fixture registries below can exercise provisional authority. + new._COMMITTED_INDEX_QUALIFIED = True + assert old.PROTOCOL_VERSION == new.PROTOCOL_VERSION == 1 + assert old.PLAN_HEADER == new.PLAN_HEADER + + def functions(source: bytes): + tree = ast.parse(source) + return { + node.name: node + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.ClassDef)) + } + + checkpoint = functions( + subprocess.check_output( + ["git", "show", "f804fd1:cmake/ProtocyteOutputCoordinator.py"], cwd=REPO + ) + ) + candidate = functions(CURRENT.read_bytes()) + old_methods = { + node.name: node + for node in checkpoint["OutputCoordinator"].body + if isinstance(node, ast.FunctionDef) + } + new_methods = { + node.name: node + for node in candidate["OutputCoordinator"].body + if isinstance(node, ast.FunctionDef) + } + unchanged = [] + for name in ( + "reconcile_set", + "_reconcile_locked", + "validate", + "publish", + "reset", + "_recover", + "_apply_pending", + "_publish_one", + "_initialize_claim_locked", + "_release_claim", + "_generation_lock", + "_publication_lock", + ): + assert ast.dump(old_methods[name]) == ast.dump(new_methods[name]), name + unchanged.append(name) + reference = new_methods["_validate_registry_reference"] + reference.name = "_validate_registry" + reference_unchanged = ast.dump(old_methods["_validate_registry"]) == ast.dump( + reference + ) + assert ast.dump(checkpoint["FileLock"]) == ast.dump(candidate["FileLock"]) + + indexed_validations = [] + + def engine(version: str, locks: Path): + if version == "old": + return old.OutputCoordinator(locks) + result = new.OutputCoordinator( + locks, **({} if version == "default" else {"registry_validation": version}) + ) + if version in ("indexed", "default"): + validate = result._validate_registry + + def recorded(*args, **kwargs): + validate(*args, **kwargs) + indexed_validations.append(dict(result.validation_metrics)) + + result._validate_registry = recorded + return result + + def module(version: str): + return old if version == "old" else new + + def fixture(name: str): + directory = WORK / "fixtures" / name + directory.mkdir(parents=True, exist_ok=False) + build = directory / "build" + build.mkdir() + root = directory / "generated" + locks = directory / "locks" + plan = directory / "outputs.plan" + target = hashlib.sha256(b"upgrade-target").hexdigest() + staging = directory / (".protocyte-generation-staging-" + target) / "generated" + + def encode(value): + return os.fspath(value).encode().hex() + + plan.write_text( + "\n".join( + [ + old.PLAN_HEADER, + "root-hex=" + encode(root), + "build-root-hex=" + encode(build), + "target=" + target + "|" + encode(staging.parent), + "output=" + target + "|" + encode("demo.protocyte.cpp"), + "output=" + target + "|" + encode("demo.protocyte.hpp"), + ] + ) + + "\n", + encoding="ascii", + ) + assert old.Plan.read(plan).payload == new.Plan.read(plan).payload + assert old.Plan.read(plan).digest == new.Plan.read(plan).digest + return root, locks, plan, target, staging + + def stage(staging: Path, generation: int): + staging.mkdir(parents=True, exist_ok=True) + for suffix in ("cpp", "hpp"): + (staging / ("demo.protocyte." + suffix)).write_bytes( + f"// generated {generation}\n".encode() + ) + + def verify_outputs(root: Path, generation: int): + for suffix in ("cpp", "hpp"): + assert ( + root / ("demo.protocyte." + suffix) + ).read_bytes() == f"// generated {generation}\n".encode() + + def run(version: str, command: str, locks: Path, plan: Path, extras=(), crash=None): + args = [ + sys.executable, + os.fspath(LEGACY if version == "old" else CURRENT), + command, + "--lock-root", + os.fspath(locks), + "--plan", + os.fspath(plan), + *extras, + ] + if version == "shadow": + args.append("--experimental-registry-index") + elif version == "native-shadow": + args.append("--experimental-native-observation") + elif version == "commit-shadow": + args.append("--experimental-observation-commit") + elif version == "reference": + args.append("--reference-registry-validation") + if version in ("indexed", "default"): + if version == "indexed": + args.append("--experimental-committed-index") + if version in ("indexed", "default") and not production_qualified: + qualified_main = ( + "import importlib.util,sys; " + "spec=importlib.util.spec_from_file_location('qualified_upgrade_cli',sys.argv[1]); " + "module=importlib.util.module_from_spec(spec); " + "sys.modules[spec.name]=module; spec.loader.exec_module(module); " + "module._COMMITTED_INDEX_QUALIFIED=True; " + "raise SystemExit(module.main(sys.argv[2:]))" + ) + args = [sys.executable, "-c", qualified_main, *args[1:]] + environment = os.environ.copy() + environment.pop("PROTOCYTE_COORDINATOR_CRASH_AFTER", None) + if crash: + environment["PROTOCYTE_COORDINATOR_CRASH_AFTER"] = crash + completed = subprocess.run( + args, env=environment, capture_output=True, timeout=40 + ) + assert completed.returncode == (86 if crash else 0), ( + version, + command, + crash, + completed.returncode, + completed.stderr, + ) + return completed + + results = [] + transitions = ( + ("old", "reference"), + ("old", "shadow"), + ("reference", "old"), + ("shadow", "old"), + ("old", "native-shadow"), + ("native-shadow", "old"), + ("old", "commit-shadow"), + ("commit-shadow", "old"), + ("old", "indexed"), + ("indexed", "old"), + ("old", "default"), + ("default", "old"), + ) + for writer, reader in transitions: + root, locks, plan, target, staging = fixture(f"steady-{writer}-{reader}") + first, second = engine(writer, locks), engine(reader, locks) + first_plan, second_plan = ( + module(writer).Plan.read(plan), + module(reader).Plan.read(plan), + ) + token = first.reconcile(first_plan) + state = first._state_directory(root) + assert first._generation_lock(root) == second._generation_lock(root) + assert first._publication_lock(root) == second._publication_lock(root) + claim = (state / "claim.json").read_bytes() + stage(staging, 1) + first.publish(first_plan, target, staging) + unchanged_outputs = { + path.name: (path.read_bytes(), path.stat().st_mtime_ns) + for path in root.iterdir() + } + assert second.reconcile(second_plan) == token + second.validate(second_plan) + assert (state / "claim.json").read_bytes() == claim + assert unchanged_outputs == { + path.name: (path.read_bytes(), path.stat().st_mtime_ns) + for path in root.iterdir() + } + stage(staging, 2) + second.publish(second_plan, target, staging) + first.validate(first_plan) + assert first.reconcile(first_plan) == token + verify_outputs(root, 2) + results.append( + { + "kind": "upgrade-rollback-noop-token-and-publication", + "writer": writer, + "reader": reader, + "passed": True, + } + ) + + for writer, reader in ( + ("old", "reference"), + ("old", "shadow"), + ("shadow", "old"), + ("old", "native-shadow"), + ("native-shadow", "old"), + ("old", "commit-shadow"), + ("commit-shadow", "old"), + ("old", "indexed"), + ("indexed", "old"), + ("old", "default"), + ("default", "old"), + ): + for phase in ( + "after-pending", + "after-output-1", + "after-output-2", + "after-snapshot", + ): + root, locks, plan, target, staging = fixture( + f"publish-{writer}-{reader}-{phase}" + ) + first = engine(writer, locks) + p = module(writer).Plan.read(plan) + token = first.reconcile(p) + stage(staging, 1) + first.publish(p, target, staging) + stage(staging, 2) + run( + writer, + "publish", + locks, + plan, + ("--target", target, "--staging-root", os.fspath(staging)), + crash=phase, + ) + for payload in staging.iterdir(): + payload.unlink() + second = engine(reader, locks) + assert second.reconcile(module(reader).Plan.read(plan)) == token + verify_outputs(root, 2) + assert not list((second._state_directory(root) / "transactions").iterdir()) + results.append( + { + "kind": "publication-crash-recovery", + "writer": writer, + "reader": reader, + "cut": phase, + "passed": True, + } + ) + for phase in ("after-initial-snapshot", "after-claim"): + root, locks, plan, target, staging = fixture( + f"init-{writer}-{reader}-{phase}" + ) + run(writer, "reconcile", locks, plan, crash=phase) + second = engine(reader, locks) + assert len(second.reconcile(module(reader).Plan.read(plan))) == 64 + second.validate(module(reader).Plan.read(plan)) + results.append( + { + "kind": "initialization-crash-recovery", + "writer": writer, + "reader": reader, + "cut": phase, + "passed": True, + } + ) + for phase in ( + "after-reset-intent", + "after-reset-output-1", + "after-reset-disposable", + ): + root, locks, plan, target, staging = fixture( + f"reset-{writer}-{reader}-{phase}" + ) + first = engine(writer, locks) + p = module(writer).Plan.read(plan) + token = first.reconcile(p) + stage(staging, 1) + first.publish(p, target, staging) + run(writer, "reset", locks, plan, ("--expected-claim", token), crash=phase) + second = engine(reader, locks) + second.reset(module(reader).Plan.read(plan), token) + assert not second._state_directory(root).exists() + assert not list(root.glob("*.protocyte.*")) + results.append( + { + "kind": "reset-crash-recovery", + "writer": writer, + "reader": reader, + "cut": phase, + "passed": True, + } + ) + + # Historical source checks are deliberately in this explicit qualifier, + # not routine unit tests: a squash merge need not retain branch commits. + mixed_source_hashes = {} + for revision in ("8851bde", "1d1e1b0"): + path = WORK / f"legacy/helper-{revision}.py" + path.write_bytes( + subprocess.check_output( + ["git", "show", f"{revision}:cmake/ProtocyteObservationCommit.py"], + cwd=REPO, + ) + ) + previous_helper = load(f"mixed_helper_{revision}", path) + mixed_source_hashes[f"helper-{revision}"] = hashlib.sha256( + path.read_bytes() + ).hexdigest() + root, locks, plan_file, _, _ = fixture(f"mixed-helper-{revision}") + reader = engine("reference", locks) + plan = new.Plan.read(plan_file) + token = reader.reconcile(plan) + state = reader._state_directory(root) + claim = (state / "claim.json").read_bytes() + load_commit, commit_module = ( + new._load_observation_commit, + new._observation_commit_module, + ) + try: + new._load_observation_commit = lambda: previous_helper + new._observation_commit_module = previous_helper + reader.registry_validation = "indexed" + assert reader.reconcile(plan) == token + assert reader.validation_metrics["fallback"] == "reference" + assert reader.validation_metrics["reference_result"] == "accepted" + assert "commit_handles_opened" not in reader.validation_metrics + assert (state / "claim.json").read_bytes() == claim + finally: + new._load_observation_commit, new._observation_commit_module = ( + load_commit, + commit_module, + ) + results.append( + { + "kind": "actual-previous-helper-reference-fallback", + "revision": revision, + "passed": True, + } + ) + + path = WORK / "legacy/pre-review-coordinator.py" + path.write_bytes( + subprocess.check_output( + ["git", "show", "1d1e1b0:cmake/ProtocyteOutputCoordinator.py"], cwd=REPO + ) + ) + previous = load("mixed_previous_coordinator", path) + mixed_source_hashes["coordinator-1d1e1b0"] = hashlib.sha256( + path.read_bytes() + ).hexdigest() + previous._COMMITTED_INDEX_QUALIFIED = True + previous._load_ownership_index = new._load_ownership_index + previous._load_path_observation = new._load_path_observation + previous._load_observation_commit = new._load_observation_commit + updated_helper = new._load_observation_commit() + previous._observation_commit_module = updated_helper + for failed_cleanup in (False, True): + root, locks, plan_file, _, _ = fixture( + f"previous-coordinator-updated-helper-{failed_cleanup}" + ) + reader = previous.OutputCoordinator(locks, registry_validation="reference") + plan = previous.Plan.read(plan_file) + token = reader.reconcile(plan) + claim = (reader._state_directory(root) / "claim.json").read_bytes() + constructor = updated_helper.WindowsObservationCommit.__init__ + failed = [] + if failed_cleanup: + + def initialize(readset, *args, **kwargs): + constructor(readset, *args, **kwargs) + raw_close = readset.reader._close + + def close(handle): + if not failed: + failed.append((raw_close, handle)) + return False + return raw_close(handle) + + readset.reader._close = close + + updated_helper.WindowsObservationCommit.__init__ = initialize + try: + reader.registry_validation = "indexed" + if failed_cleanup: + try: + reader.reconcile(plan) + except previous.CoordinatorError as error: + assert "could not be retired safely" in str(error) + else: + raise AssertionError( + "previous coordinator accepted failed native cleanup" + ) + assert reader.validation_metrics["reference_wall_seconds"] == 0.0 + else: + assert reader.reconcile(plan) == token + assert reader.validation_metrics["authoritative"] == "index" + assert (reader._state_directory(root) / "claim.json").read_bytes() == claim + finally: + updated_helper.WindowsObservationCommit.__init__ = constructor + # Only the injector knows that no OS close was attempted. + for raw_close, handle in failed: + assert raw_close(handle) + results.append( + { + "kind": "actual-previous-coordinator-updated-helper", + "failed_cleanup": failed_cleanup, + "passed": True, + } + ) + + assert { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in IMPLEMENTATION + } == EXPECTED_SOURCES, "sources changed during qualification; discard the run" + report = { + "scope": "isolated Windows cross-version checks; no consumer registry accessed", + "legacy_git_blob": "25f1660190d3d1015fef3955814c8c737bd686c5", + "legacy_coordinator_sha256": hashlib.sha256(LEGACY.read_bytes()).hexdigest(), + "candidate_coordinator_sha256": hashlib.sha256( + CURRENT.read_bytes() + ).hexdigest(), + "implementation_files": EXPECTED_SOURCES, + "candidate_helper_sha256": { + name: hashlib.sha256((CURRENT.parent / name).read_bytes()).hexdigest() + for name in ( + "ProtocyteOwnershipIndex.py", + "ProtocytePathObservation.py", + "ProtocyteObservationCommit.py", + ) + }, + "mixed_source_sha256": mixed_source_hashes, + "unchanged_ast_methods_since_checkpoint": unchanged, + "reference_validator_ast_unchanged_since_checkpoint": reference_unchanged, + "file_lock_ast_unchanged_since_checkpoint": True, + "passed_cases": len(results), + "production_index_authorization_qualified": production_qualified, + "index_authority_enabled_only_in_isolated_fixture_module": not production_qualified, + "indexed_validations": len(indexed_validations), + "index_authorized_validations": sum( + metrics["authoritative"] == "index" for metrics in indexed_validations + ), + "indexed_reference_fallbacks": sum( + metrics.get("fallback") == "reference" for metrics in indexed_validations + ), + "cases": results, + } + (WORK / "upgrade-results.json").write_text(json.dumps(report, indent=2) + "\n") + print( + json.dumps( + { + "passed_cases": len(results), + "protocol": 1, + "unchanged_reference_validator": reference_unchanged, + "unchanged_file_locks": True, + } + ) + ) + + +if __name__ == "__main__": + main()