From 590d1096f0427252808413224c93bc66ac200fc4 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:59:04 +0100 Subject: [PATCH 1/3] integration(mvp): source-exact early admission plus owner generation CAS Bring durable owner-model TLC blue and mandatory red orphan control, strict isolated CAS storage and tests onto early entrypoint writer lease. Preserve both independent formal families and every mandatory unit test. Synthetic race accepts only explicit lock contention or stale generation; no production pointer switch or cross-host safety claim. --- .github/workflows/formal-cross-layer-tlc.yml | 26 ++- api/core/persistent_owner.py | 173 ++++++++++++++++++ formal/PERSISTENT_SESSION_OWNER.md | 78 ++++++++ formal/tests/test_persistent_session_owner.py | 100 ++++++++++ formal/tla/PersistentSessionOwner.cfg | 2 + formal/tla/PersistentSessionOwner.tla | 63 +++++++ formal/tla/PersistentSessionOwnerUnsafe.cfg | 2 + formal/tla/PersistentSessionOwnerUnsafe.tla | 38 ++++ scripts/ci/test.sh | 1 + tests/test_persistent_owner.py | 137 ++++++++++++++ 10 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 api/core/persistent_owner.py create mode 100644 formal/PERSISTENT_SESSION_OWNER.md create mode 100644 formal/tests/test_persistent_session_owner.py create mode 100644 formal/tla/PersistentSessionOwner.cfg create mode 100644 formal/tla/PersistentSessionOwner.tla create mode 100644 formal/tla/PersistentSessionOwnerUnsafe.cfg create mode 100644 formal/tla/PersistentSessionOwnerUnsafe.tla create mode 100644 tests/test_persistent_owner.py diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index 863c3946..5ab5d0a1 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -11,6 +11,10 @@ on: - "api/server.py" - "api/utils/files.py" - "api/core/writer_admission.py" + - "api/core/persistent_owner.py" + - "tests/test_persistent_owner.py" + - "scripts/ci/classify-startup-logs.py" + - "tests/test_startup_checkpoint_redaction.py" - "docker/entrypoint.sh" - "scripts/init/10-setup-infra.sh" - "tests/test_early_writer_admission.py" @@ -56,7 +60,7 @@ jobs: run: | set -euo pipefail cd formal/tla - for model in ControlLease SessionHandover ReleaseAdmission SessionWriterFence; do + for model in ControlLease SessionHandover ReleaseAdmission SessionWriterFence PersistentSessionOwner; do echo "TLC_MODEL=$model" timeout 90s java -Xmx768m -XX:+UseParallelGC \ -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ @@ -122,6 +126,26 @@ jobs: exit 1 fi echo "FORMAL_TWO_WRITER_NEGATIVE=STALE_COMMIT_COUNTEREXAMPLE_CONFIRMED" + - name: Prove that ephemeral pointer loss strands durable handover intent + shell: bash + run: | + set -euo pipefail + cd formal/tla + if timeout 45s java -Xmx512m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config PersistentSessionOwnerUnsafe.cfg \ + PersistentSessionOwnerUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-ephemeral-owner.log" 2>&1; then + echo "FORMAL_POINTER_NEGATIVE=UNEXPECTED_NO_COUNTEREXAMPLE" + exit 1 + fi + if ! grep -Fq 'Invariant NoOrphanAtRest is violated' \ + "$RUNNER_TEMP/formal/unsafe-ephemeral-owner.log"; then + echo "FORMAL_POINTER_NEGATIVE=NO_EXPECTED_ORPHAN" + grep -E '^(Error:|Invariant |Semantic errors|.*Error.*)' \ + "$RUNNER_TEMP/formal/unsafe-ephemeral-owner.log" | head -n 20 || true + exit 1 + fi + echo "FORMAL_POINTER_NEGATIVE=ORPHANED_INTENT_COUNTEREXAMPLE_CONFIRMED" - name: Run dependency-free model contract tests shell: bash run: | diff --git a/api/core/persistent_owner.py b/api/core/persistent_owner.py new file mode 100644 index 00000000..b6a2c950 --- /dev/null +++ b/api/core/persistent_owner.py @@ -0,0 +1,173 @@ +"""A versioned durable owner pointer primitive for a single admitted Linux root. + +Not yet wired to shell startup, resume, or crash reconciliation. An admitted +writer must still prove the host's shared filesystem flock behavior. +""" + +import json +import os +import re +import stat +from dataclasses import dataclass +from pathlib import Path + +from api.core.writer_admission import admit_single_writer + +from api.utils.files import _atomic_write_text + +OWNER_FILE = ".winebot-committed-owner.json" +MAX_OWNER_BYTES = 8192 +MAX_GENERATION = (1 << 63) - 1 +_OPERATION_ID = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$") +_FIELDS = frozenset(("schema_version", "generation", "session_dir", "operation_id")) + + +class OwnerPointerError(RuntimeError): + """Persistent owner data is missing trust or schema requirements.""" + + +class OwnerGenerationConflict(OwnerPointerError): + """A stale generation or operation identity must not commit.""" + + +@dataclass(frozen=True) +class OwnerPointer: + schema_version: int + generation: int + session_dir: str + operation_id: str + + +def _root(root: str) -> Path: + path = Path(root) + if ( + not path.is_absolute() + or path.is_symlink() + or os.path.realpath(path) != str(path) + or not path.is_dir() + ): + raise OwnerPointerError("Persistent control root is not admitted") + return path + + +def _session(root: Path, session_dir: str) -> str: + candidate = Path(session_dir) + if ( + not candidate.is_absolute() + or candidate.is_symlink() + or candidate.parent != root + or os.path.realpath(candidate) != str(candidate) + or not candidate.is_dir() + ): + raise OwnerPointerError("Persistent owner is not a direct child session") + return str(candidate) + + +def _identity(operation_id: str) -> str: + if not isinstance(operation_id, str) or not _OPERATION_ID.fullmatch( + operation_id + ): + raise OwnerPointerError("Invalid owner operation identity") + return operation_id + + +def read_persistent_owner(root: str) -> OwnerPointer | None: + """Read only a validated root-local record. Corruption is never 'missing'.""" + directory = _root(root) + target = directory / OWNER_FILE + try: + fd = os.open(target, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + except FileNotFoundError: + return None + except OSError as exc: + raise OwnerPointerError("Persistent owner record inaccessible") from exc + try: + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_size > MAX_OWNER_BYTES + or metadata.st_size <= 0 + ): + raise OwnerPointerError("Persistent owner record identity rejected") + with os.fdopen(fd, "r", encoding="utf-8") as handle: + fd = -1 + content = handle.read(MAX_OWNER_BYTES + 1) + payload = json.loads(content) + except (OSError, ValueError, UnicodeError) as exc: + raise OwnerPointerError("Persistent owner record malformed") from exc + finally: + if fd >= 0: + os.close(fd) + if not isinstance(payload, dict) or set(payload) != _FIELDS: + raise OwnerPointerError("Unknown persistent owner schema") + if type(payload["schema_version"]) is not int or payload["schema_version"] != 1: + raise OwnerPointerError("Unsupported persistent owner schema version") + gen = payload["generation"] + if type(gen) is not int or not 0 < gen <= MAX_GENERATION: + raise OwnerPointerError("Invalid persistent owner generation") + session_dir = payload["session_dir"] + if not isinstance(session_dir, str): + raise OwnerPointerError("Invalid persistent owner session") + return OwnerPointer( + schema_version=1, + generation=gen, + session_dir=_session(directory, session_dir), + operation_id=_identity(payload["operation_id"]), + ) + + +def commit_persistent_owner( + root: str, session_dir: str, expected_generation: int, operation_id: str +) -> OwnerPointer: + """Idempotent generation CAS while holding the admitted root writer lock. + + This one-file CAS cannot by itself atomically switch the Wine profile, + broker state, multiple handover markers, or live guest effects. + """ + if type(expected_generation) is not int or not 0 <= expected_generation < MAX_GENERATION: + raise OwnerGenerationConflict("Invalid expected owner generation") + op = _identity(operation_id) + # This context shares the entrypoint's exact inherited OFD if present; + # otherwise it acquires an independent exclusive lock for a direct call. + with admit_single_writer(root): + directory = _root(root) + requested = _session(directory, session_dir) + current = read_persistent_owner(root) + if current is not None and current.operation_id == op: + if ( + current.session_dir == requested + and current.generation == expected_generation + 1 + ): + # A prior caller may have seen rename succeed but parent + # fsync fail. Never ACK its idempotent replay without a + # fresh successful durability barrier on the same directory. + directory_fd = os.open( + directory, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + ) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + return current + raise OwnerGenerationConflict("Owner operation identity reused") + actual = current.generation if current else 0 + if actual != expected_generation: + raise OwnerGenerationConflict("Stale persistent owner generation") + next_record = OwnerPointer( + schema_version=1, + generation=actual + 1, + session_dir=requested, + operation_id=op, + ) + payload = { + "schema_version": next_record.schema_version, + "generation": next_record.generation, + "session_dir": next_record.session_dir, + "operation_id": next_record.operation_id, + } + if (directory / OWNER_FILE).is_symlink(): + raise OwnerPointerError("Symlink persistent owner record rejected") + _atomic_write_text(str(directory / OWNER_FILE), json.dumps(payload, sort_keys=True)) + return next_record diff --git a/formal/PERSISTENT_SESSION_OWNER.md b/formal/PERSISTENT_SESSION_OWNER.md new file mode 100644 index 00000000..e2b8d628 --- /dev/null +++ b/formal/PERSISTENT_SESSION_OWNER.md @@ -0,0 +1,78 @@ +# Persistent active-owner pointer across disposable WineBot runtimes (RDTE) + +## Reproduced source distinction — 2026-11-22 +- `api/utils/files.py:47` binds `SESSION_FILE` to `/tmp/winebot_current_session`. + `read_session_dir()` reads that ephemeral file; `write_session_dir()` + commits **only** that path, although it fsyncs that particular directory. +- `scripts/init/10-setup-infra.sh` selects a new session when neither + `WINEBOT_SESSION_DIR` nor `WINEBOT_SESSION_ID` is supplied, and writes + the active pointer to the same `/tmp` location. +- `api/core/handover_recovery.py` replays only the **active** session's + durable intent marker. After a fresh container loses the `/tmp` pointer, + the persisted session tree may still contain old transaction markers + that the new default-session startup does not discover or reconcile. +- The source-safe TLA+ `SessionHandover` assumes an abstract authoritative + pointer survives crash. That property is **not refined to** the existing + /tmp-only code across disposable container replacement. + +This is an independently source-verified *risk*, not evidence of a specific +user production failure. It directly affects the required disposable +runtime/application/persistent data architecture. + +## Red/blue qualification +`PersistentSessionOwnerUnsafe.tla` demonstrates prepare durable intent, +lose the volatile pointer, and invent a new owner with a stranded journal. +The expected counterexample is `NoOrphanAtRest` violated; parsing errors +or other failure codes must not count as counterexamples. + +`PersistentSessionOwner.tla` models a **proposed** persistent committed +owner and a volatile cache that is rebuilt from it; only a reconciled +owner may report READY. Independent Python stdlib graph search covers +both cases with no local Wine, private code, or user content. + +## Required sequential production correction +1. Under the qualified **early entrypoint lease** (#184), choose a versioned + persistent control-root owner pointer (e.g., a dedicated file under the + admitted `WINEBOT_SESSION_ROOT`), with strict root, permissions, + symlink rejection and bounded schema/identity. Never infer active from + arbitrary directory mtime/lexical order. +2. Make `resume` changes generation-fenced/compare-and-swap, write a + durable owner record atomically (tempfile fsync, rename, dir fsync), + and preserve old `/tmp` pointer only as a derived compatibility cache. + Specify crash order of both marker files, stable committed owner, + profile relink, broker state and journal cleanup. +3. Before shell/guest/session mutation on new container startup, read the + committed owner under the same lease, match a valid root-local + session path, reconcile *all reachable corresponding* prepared intent + markers, or **quarantine** on orphan/conflicting markers. Do not silently + create a new session or trust a stale `/tmp` pointer. +4. Prove crash at each write/sync/rename/profile/broker stage using two + disposable instances sharing the same persistent volume, including + SIGKILL, stale generations, corrupted pointer and absent peer marker. + Qualify exact-source Wine11 real guest, native GUI and frozen contracts. +5. Review throughput/latency, storage mount semantics, reader/worker + authority and fail-closed error surfaces before promotion. The + formal abstraction alone is **NOT READY** for hardware or release. + +Independent from WinInspect-private native v0.5/cloud admission #468/#561. +No paid compute, private Actions minutes or source projection. +DLE = Durable (exact SHA+receipts), Legible (red/blue counterexamples), +Executable (gated source-to-runtime refinement plan). + +## Source-only storage primitive workcell (#186) +The isolated `api/core/persistent_owner.py` introduces a strict version-1 +one-file persistent owner record under the already admitted session root, +with monotonically advancing generation and explicit operation identity. +Its compare-and-swap acquires the same `writer_admission` lease, validates +root/session identity, refuses symlinks, unknown schema or corrupted data, +and writes through the established tempfile fsync → replace → parent fsync +primitive. Replay of the same operation/generation is idempotent; stale +generations and operation-ID reuse are denied. Synthetic tests include two +real competing Python processes and injected parent-directory fsync failure. + +**Not integrated:** none of `docker/entrypoint.sh`, `api/routers/lifecycle.py`, +`api/server.py` or the legacy `/tmp` pointer is changed by this workcell. +No immediate product behavior or recovered active owner is claimed. +Integration follows release-accepted early admission #184 and must cover +the source-to-model mapping, root mount/permission handling, paired +handover journals, replay/quarantine and actual guest behavior. diff --git a/formal/tests/test_persistent_session_owner.py b/formal/tests/test_persistent_session_owner.py new file mode 100644 index 00000000..dd549fea --- /dev/null +++ b/formal/tests/test_persistent_session_owner.py @@ -0,0 +1,100 @@ +"""Finite owner-pointer loss vs durable restart recovery (synthetic only).""" + +import unittest +from collections import deque +from dataclasses import dataclass, replace + + +@dataclass(frozen=True) +class Pointer: + phase: str = "ready" + durable: str = "A" + volatile: str = "A" + reported: str = "A" + intent: bool = False + + +def valid_actions(s: Pointer): + if s.phase == "ready": + yield "prepare", replace(s, phase="prepared", intent=True) + if s.phase == "prepared": + yield "commit", replace( + s, phase="committed", durable="B", volatile="B", + reported="B", intent=False, + ) + if s.phase in ("ready", "prepared", "committed"): + yield "crash", replace( + s, phase="down", volatile="none", reported="none", + ) + if s.phase == "down": + yield "reconcile", replace( + s, phase="ready", volatile=s.durable, + reported=s.durable, intent=False, + ) + + +def unsafe_actions(s: Pointer): + if s.phase == "ready": + yield "prepare", replace(s, phase="prepared", intent=True) + if s.phase == "prepared": + yield "crash", replace( + s, phase="down", volatile="none", reported="none" + ) + if s.phase == "down": + yield "unsafe_fresh_container", replace( + s, phase="ready", volatile="C", reported="C" + ) + + +def explore(actions, invariant): + start = Pointer() + seen = {start} + pending = deque([(start, ())]) + while pending: + s, history = pending.popleft() + if not invariant(s): + return history, seen + for label, next_state in actions(s): + if next_state not in seen: + seen.add(next_state) + pending.append((next_state, history + (label,))) + return None, seen + + +class PersistentPointerModelTests(unittest.TestCase): + def test_durable_protocol_restarts_to_one_resting_owner(self): + def good(s): + if s.phase in ("ready", "committed"): + return ( + not s.intent + and s.volatile == s.durable == s.reported + ) + return True + + trace, states = explore(valid_actions, good) + self.assertIsNone(trace) + self.assertGreater(len(states), 6) + self.assertTrue(any(s.phase == "ready" and s.durable == "B" for s in states)) + + def test_ephemeral_only_pointer_produces_orphaned_journal(self): + trace, states = explore( + unsafe_actions, + lambda s: s.phase != "ready" + or (s.volatile == s.durable and not s.intent), + ) + self.assertEqual(trace, ( + "prepare", "crash", "unsafe_fresh_container" + )) + self.assertGreater(len(states), 3) + + def test_crash_before_durable_commit_restores_previous_owner(self): + state = Pointer() + state = dict(valid_actions(state))["prepare"] + state = dict(valid_actions(state))["crash"] + state = dict(valid_actions(state))["reconcile"] + self.assertEqual((state.durable, state.volatile, state.reported), ("A", "A", "A")) + self.assertFalse(state.intent) + + +if __name__ == "__main__": + unittest.main() diff --git a/formal/tla/PersistentSessionOwner.cfg b/formal/tla/PersistentSessionOwner.cfg new file mode 100644 index 00000000..941c05dc --- /dev/null +++ b/formal/tla/PersistentSessionOwner.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANTS TypeOK NoFalseReady NoSplitVisibleOwner diff --git a/formal/tla/PersistentSessionOwner.tla b/formal/tla/PersistentSessionOwner.tla new file mode 100644 index 00000000..0601ef10 --- /dev/null +++ b/formal/tla/PersistentSessionOwner.tla @@ -0,0 +1,63 @@ +----------------------- MODULE PersistentSessionOwner ----------------------- +EXTENDS TLC + +\* Proposed persistent pointer protocol, NOT the current /tmp implementation. +\* A committed root owner remains discoverable across a fresh container's /tmp. +Owners == {"A", "B", "none"} +Phases == {"ready", "prepared", "committed", "down"} +VARIABLES phase, durable, volatile, reported, intent +vars == <> + +Init == + /\ phase = "ready" + /\ durable = "A" + /\ volatile = "A" + /\ reported = "A" + /\ intent = FALSE + +Prepare == + /\ phase = "ready" + /\ phase' = "prepared" + /\ intent' = TRUE + /\ UNCHANGED <> + +Commit == + /\ phase = "prepared" + /\ phase' = "committed" + /\ durable' = "B" + /\ volatile' = "B" + /\ reported' = "B" + /\ intent' = FALSE + +Crash == + /\ phase \in {"ready", "prepared", "committed"} + /\ phase' = "down" + /\ volatile' = "none" + /\ reported' = "none" + /\ UNCHANGED <> + +Recover == + /\ phase = "down" + /\ phase' = "ready" + /\ volatile' = durable + /\ reported' = durable + /\ intent' = FALSE + /\ UNCHANGED durable + +Next == Prepare \/ Commit \/ Crash \/ Recover +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ phase \in Phases + /\ durable \in Owners + /\ volatile \in Owners + /\ reported \in Owners + /\ intent \in BOOLEAN + +NoFalseReady == + (phase \in {"ready", "committed"}) => + (volatile = durable /\ reported = durable /\ ~intent) +NoSplitVisibleOwner == + (volatile # "none" /\ reported # "none") => + (volatile = reported) +============================================================================= \ No newline at end of file diff --git a/formal/tla/PersistentSessionOwnerUnsafe.cfg b/formal/tla/PersistentSessionOwnerUnsafe.cfg new file mode 100644 index 00000000..76c99f31 --- /dev/null +++ b/formal/tla/PersistentSessionOwnerUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT NoOrphanAtRest diff --git a/formal/tla/PersistentSessionOwnerUnsafe.tla b/formal/tla/PersistentSessionOwnerUnsafe.tla new file mode 100644 index 00000000..a9bae208 --- /dev/null +++ b/formal/tla/PersistentSessionOwnerUnsafe.tla @@ -0,0 +1,38 @@ +-------------------- MODULE PersistentSessionOwnerUnsafe -------------------- +EXTENDS TLC + +\* Deliberately broken real-world pattern: only /tmp stores active pointer. +\* A new container invents another session while durable handover intent lives. +Owners == {"A", "C", "none"} +VARIABLES phase, durable, volatile, intent +vars == <> + +Init == + /\ phase = "ready" + /\ durable = "A" + /\ volatile = "A" + /\ intent = FALSE + +Prepare == + /\ phase = "ready" + /\ phase' = "prepared" + /\ intent' = TRUE + /\ UNCHANGED <> + +Crash == + /\ phase = "prepared" + /\ phase' = "down" + /\ volatile' = "none" + /\ UNCHANGED <> + +UnsafeFallback == + /\ phase = "down" + /\ phase' = "ready" + /\ volatile' = "C" + /\ UNCHANGED <> + +Next == Prepare \/ Crash \/ UnsafeFallback +Spec == Init /\ [][Next]_vars +NoOrphanAtRest == + (phase = "ready") => (volatile = durable /\ ~intent) +============================================================================= \ No newline at end of file diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index 3f7d4056..da53eebb 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -10,6 +10,7 @@ pytest \ tests/test_conformance_runtime_policy.py \ tests/test_config_strict_validation.py \ tests/test_invariants.py \ + tests/test_persistent_owner.py \ tests/test_writer_admission.py \ tests/test_early_writer_admission.py \ tests/test_startup_checkpoint_redaction.py \ diff --git a/tests/test_persistent_owner.py b/tests/test_persistent_owner.py new file mode 100644 index 00000000..054933ed --- /dev/null +++ b/tests/test_persistent_owner.py @@ -0,0 +1,137 @@ +"""Safe synthetic persistent owner CAS and durability regression tests.""" + +import json +import os +import subprocess +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest + +from api.core.persistent_owner import ( + OWNER_FILE, + OwnerGenerationConflict, + OwnerPointerError, + commit_persistent_owner, + read_persistent_owner, +) + +pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="Linux root lock only") +REPO_ROOT = Path(__file__).resolve().parents[1] + +COMPETITOR = """ +import sys +from api.core.persistent_owner import commit_persistent_owner, OwnerGenerationConflict +from api.core.writer_admission import WriterAdmissionError +try: + commit_persistent_owner(sys.argv[1], sys.argv[2], 0, sys.argv[3]) +except (OwnerGenerationConflict, WriterAdmissionError): + raise SystemExit(43) +""" + + +def setup_root(tmp_path): + root = tmp_path / "sessions" + root.mkdir() + a, b = root / "A", root / "B" + a.mkdir() + b.mkdir() + return root, a, b + + +def test_initial_commit_replay_is_idempotent_and_advances_generation(tmp_path): + root, a, b = setup_root(tmp_path) + assert read_persistent_owner(str(root)) is None + first = commit_persistent_owner(str(root), str(a), 0, "operation-1") + assert first.generation == 1 + assert commit_persistent_owner(str(root), str(a), 0, "operation-1") == first + new_owner = commit_persistent_owner(str(root), str(b), 1, "operation-2") + assert new_owner.generation == 2 + assert read_persistent_owner(str(root)) == new_owner + assert json.loads((root / OWNER_FILE).read_text())["session_dir"] == str(b) + + +def test_stale_generation_and_reused_operation_fail_without_mutation(tmp_path): + root, a, b = setup_root(tmp_path) + commit_persistent_owner(str(root), str(a), 0, "operation-1") + source = (root / OWNER_FILE).read_bytes() + with pytest.raises(OwnerGenerationConflict, match="Stale"): + commit_persistent_owner(str(root), str(b), 0, "operation-2") + with pytest.raises(OwnerGenerationConflict, match="reused"): + commit_persistent_owner(str(root), str(b), 0, "operation-1") + assert (root / OWNER_FILE).read_bytes() == source + + +def test_external_or_symlink_owner_paths_and_invalid_ops_rejected(tmp_path): + root, a, _ = setup_root(tmp_path) + outside = tmp_path / "external" + outside.mkdir() + alias = root / "alias" + alias.symlink_to(a, target_is_directory=True) + for attempted in (str(outside), str(alias), str(a / ".." / "A")): + with pytest.raises(OwnerPointerError): + commit_persistent_owner(str(root), attempted, 0, "operation-1") + with pytest.raises(OwnerPointerError, match="identity"): + commit_persistent_owner(str(root), str(a), 0, "../unsafe-id") + assert read_persistent_owner(str(root)) is None + + +def test_symlink_or_malformed_persistent_record_fails_closed(tmp_path): + root, a, _ = setup_root(tmp_path) + target = root / OWNER_FILE + target.symlink_to(a) + with pytest.raises(OwnerPointerError): + read_persistent_owner(str(root)) + with pytest.raises(OwnerPointerError): + commit_persistent_owner(str(root), str(a), 0, "operation-1") + target.unlink() + target.write_text("{invalid json", encoding="utf-8") + with pytest.raises(OwnerPointerError, match="malformed"): + commit_persistent_owner(str(root), str(a), 0, "operation-1") + + +def test_directory_sync_failure_is_not_acknowledged_as_commit(tmp_path): + root, a, _ = setup_root(tmp_path) + real_sync = os.fsync + + def fail_directory_sync(fd): + if os.fstat(fd).st_mode & 0o170000 == 0o040000: + raise OSError("synthetic parent fsync denied") + return real_sync(fd) + + with patch("api.utils.files.os.fsync", side_effect=fail_directory_sync): + with pytest.raises(OSError, match="synthetic parent"): + commit_persistent_owner(str(root), str(a), 0, "operation-1") + # The rename may already have landed; no invented rollback/ACK. + assert read_persistent_owner(str(root)).generation == 1 + # A retry of that exact operation must repair the parent fsync before + # it may acknowledge the persisted idempotent owner record. + with patch("api.core.persistent_owner.os.fsync", wraps=real_sync) as sync: + replay = commit_persistent_owner(str(root), str(a), 0, "operation-1") + assert replay.generation == 1 + assert sync.call_count >= 1 + + +def test_two_real_processes_with_same_expected_epoch_only_one_commits(tmp_path): + root, a, b = setup_root(tmp_path) + commands = [ + [sys.executable, "-c", COMPETITOR, str(root), str(a), "operation-A"], + [sys.executable, "-c", COMPETITOR, str(root), str(b), "operation-B"], + ] + processes = [ + subprocess.Popen(cmd, cwd=REPO_ROOT, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + for cmd in commands + ] + try: + results = [p.wait(timeout=5) for p in processes] + assert sorted(results) == [0, 43] + record = read_persistent_owner(str(root)) + assert record.generation == 1 + assert record.session_dir in {str(a), str(b)} + finally: + for p in processes: + if p.poll() is None: + p.kill() + p.wait(timeout=3) From 71412921868f1f52cdf459c33ead40ca23d3e47b Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:01:09 +0100 Subject: [PATCH 2/3] fix(ci): sort integrated first-party imports when writer module exists On combined source #187, Ruff recognizes the actual api.core.writer_admission module as first-party and expects no blank separator before api.utils.files. Standalone #186 had opposite detection because that module was absent. Fix only import grouping; all CAS, barriers, models and tests unchanged. --- api/core/persistent_owner.py | 1 - 1 file changed, 1 deletion(-) diff --git a/api/core/persistent_owner.py b/api/core/persistent_owner.py index b6a2c950..ac148c10 100644 --- a/api/core/persistent_owner.py +++ b/api/core/persistent_owner.py @@ -12,7 +12,6 @@ from pathlib import Path from api.core.writer_admission import admit_single_writer - from api.utils.files import _atomic_write_text OWNER_FILE = ".winebot-committed-owner.json" From 158cf3d0e02990f0fb67acb3b1bcd43e6bc4dd09 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:05:01 +0100 Subject: [PATCH 3/3] ci(wine11): make real layered HIL mandatory for persistent-owner integration seams --- .github/workflows/wine11-disposable-layer-hil.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/wine11-disposable-layer-hil.yml b/.github/workflows/wine11-disposable-layer-hil.yml index 6f9955c3..28a833f3 100644 --- a/.github/workflows/wine11-disposable-layer-hil.yml +++ b/.github/workflows/wine11-disposable-layer-hil.yml @@ -11,6 +11,15 @@ on: # Real startup and read-only HIL must requalify actual early-admission # and infrastructure changes, not only the entrypoint wrapper. - 'api/core/writer_admission.py' + # Owner-pointer semantics may change startup/recovery in a combined + # candidate; source-only formal green cannot replace real Wine11 HIL. + - 'api/core/persistent_owner.py' + - 'tests/test_persistent_owner.py' + - 'formal/PERSISTENT_SESSION_OWNER.md' + - 'formal/tla/PersistentSessionOwner*.tla' + - 'formal/tla/PersistentSessionOwner*.cfg' + - 'formal/tests/test_persistent_session_owner.py' + - 'scripts/ci/test.sh' - 'api/server.py' - 'api/core/handover_recovery.py' - 'scripts/init/00-setup-user.sh'