From 1ab002da96733b1e1ade37403898330425b13c5e Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:11:52 +0100 Subject: [PATCH 1/3] formal(mvp): model competing session writers and expose stale-owner race Add bounded two-actor blue epoch fencing and mandatory stale-commit negative control, offline deterministic search, and a source-bound admission/refinement plan. This is a modeled design gap; no production lock, CAS, Wine process or hardware gate is claimed as implemented. --- .github/workflows/formal-cross-layer-tlc.yml | 20 +++- formal/SESSION_WRITER_FENCING.md | 72 ++++++++++++ formal/tests/test_session_writer_fence.py | 116 +++++++++++++++++++ formal/tla/SessionWriterFence.cfg | 3 + formal/tla/SessionWriterFence.tla | 66 +++++++++++ formal/tla/SessionWriterFenceUnsafe.cfg | 2 + formal/tla/SessionWriterFenceUnsafe.tla | 36 ++++++ 7 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 formal/SESSION_WRITER_FENCING.md create mode 100644 formal/tests/test_session_writer_fence.py create mode 100644 formal/tla/SessionWriterFence.cfg create mode 100644 formal/tla/SessionWriterFence.tla create mode 100644 formal/tla/SessionWriterFenceUnsafe.cfg create mode 100644 formal/tla/SessionWriterFenceUnsafe.tla diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index c6706066..2a9d82d0 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -51,7 +51,7 @@ jobs: run: | set -euo pipefail cd formal/tla - for model in ControlLease SessionHandover ReleaseAdmission; do + for model in ControlLease SessionHandover ReleaseAdmission SessionWriterFence; do echo "TLC_MODEL=$model" timeout 90s java -Xmx768m -XX:+UseParallelGC \ -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ @@ -95,6 +95,24 @@ jobs: exit 1 fi echo "FORMAL_HANDOVER_NEGATIVE=SPLIT_OWNER_COUNTEREXAMPLE_CONFIRMED" + - name: Prove that two unfenced writers can commit a stale epoch + 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 SessionWriterFenceUnsafe.cfg \ + SessionWriterFenceUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-two-writer.log" 2>&1; then + echo "FORMAL_TWO_WRITER_NEGATIVE=FAILED_TO_DETECT_STALE_COMMIT" + exit 1 + fi + if ! grep -Fq 'Invariant NoStaleWrite is violated' \ + "$RUNNER_TEMP/formal/unsafe-two-writer.log"; then + echo "FORMAL_TWO_WRITER_NEGATIVE=NO_EXPECTED_COUNTEREXAMPLE" + exit 1 + fi + echo "FORMAL_TWO_WRITER_NEGATIVE=STALE_COMMIT_COUNTEREXAMPLE_CONFIRMED" - name: Run dependency-free model contract tests shell: bash run: | diff --git a/formal/SESSION_WRITER_FENCING.md b/formal/SESSION_WRITER_FENCING.md new file mode 100644 index 00000000..db8b9324 --- /dev/null +++ b/formal/SESSION_WRITER_FENCING.md @@ -0,0 +1,72 @@ +# Two-writer session ownership and generation fencing (RDTE, unimplemented) + +## Current source seam and release significance +The MVP integration `api/routers/lifecycle.py` uses a module-local +`session_transition_lock = asyncio.Lock()` while `resume_session()` reads and +writes the durable active session pointer, user profile link, broker state +and paired transition journals. `api/server.py::lifespan` similarly relinks +the profile and replays an interrupted operation during startup. An async +lock cannot coordinate independent Python processes sharing a session root. +This is a source-rooted risk, **not** an observed production multi-worker +failure or proof that two workers are deployed today. + +`formal/tla/SessionHandover.tla` models one writer and crash recovery; it +does not prove cross-process linearizability. Metadata parent-directory +`fsync` in qualified #176 proves more durable individual renames, **not** +atomic commits across several files or processes. + +## Proposed nonnegotiable invariants +1. Exactly zero or one mutating process owns one shared persistent WineBot + session/control root at a time. Read-only clients connect to that owner. +2. An unavailable, contended or unsupported lock fails closed **before** any + startup, profile-link, instance metadata, Wine or broker mutations. +3. Every ownership change requires a persisted generation token read under + the exclusive lease; a stale observed epoch cannot commit or roll it back. +4. After crash the next admitted owner either reconciles paired intent, + active pointer, profile and broker, or quarantines. Never silently + acknowledges two ACTIVE owners. +5. POSIX `flock` alone is not a distributed lock or storage-fencing system. + Each deployment's file-lock semantics, mount sharing and process + namespaces require explicit qualification. Do not admit unsupported + network/shared volumes or multiple hosts. +6. STOP_NOW remains an unconditional human veto; already-delivered X11, + Wine/AHK events and independent process groups remain separate obligations. + +## Blue/red model contract +`SessionWriterFence.tla` models **proposed** single-holder acquisition and +epoch-checked owner updates; an interrupted holder releases without logical +commit. `SessionWriterFenceUnsafe.tla` models two independent workers +reading A@1 and committing different targets without a CAS. TLC must find +the `NoStaleWrite` counterexample, not merely fail to parse the model. +`formal/tests/test_session_writer_fence.py` enumerates the same bounded +interleavings independently with only the Python standard library. + +These tests prove properties of the **abstract protocols only**. They do +not show that current runtime code enforces an OS lock or generation CAS. + +## Sequential implementation / acceptance plan +1. Qualify a source-bound secure process-lifetime admission lock in a + disposable public Linux worker using two genuine competing processes, + SIGKILL/restart, no symlink following, restrictive permissions, fixed + safe lock path on the shared persistent control root and negative tests. +2. Bind that admission at the start of API lifespan, *before* any persistent + mutations. Keep FD custody through shutdown; guard other mutator paths + and reject multiple workers until safely partitioned. +3. Add explicit persisted monotonically advancing generation/operation-id + CAS and revalidate while holding the lease. Extend restart/intent + reconciliation under the same admission, including unmatched orphans. +4. Run crash-point and two-worker interleaving tests with a reproducible + synthetic session tree, then source-exact public Wine 11 GUI workloads. +5. Require all exact-head CI/TLC/negative controls, frozen API contracts, + source review, root/mount custody, safe redacted receipts, and explicit + owner promotion before hardware/production release. + +No production guard is implemented by this RDTE workcell. No private +WinInspect source, secrets, user files or paid/private runners are needed. +The release is NOT_READY_FOR_HARDWARE_TEST; WinInspect-private #468 native +qualification and WineBot #166 actual read-only HWND acceptance remain +independent blocked gates. + +DLE: Durable = source and CI receipts tied to exact commits; Legible = this +model/refinement gap and negative counterexample; Executable = concrete +implement/qualify/admit sequence, no hidden manual waiver. diff --git a/formal/tests/test_session_writer_fence.py b/formal/tests/test_session_writer_fence.py new file mode 100644 index 00000000..a456f88e --- /dev/null +++ b/formal/tests/test_session_writer_fence.py @@ -0,0 +1,116 @@ +"""Deterministic two-process session-fencing blue/red model tests. + +Source-level RDTE only: no production WineBot lock, process or guest effects. +""" + +import unittest +from collections import deque +from dataclasses import dataclass, replace + +TARGETS = ("B", "C") + + +@dataclass(frozen=True) +class State: + epoch: int = 1 + owner: str = "A" + holder: int = -1 + phase: tuple[int, int] = (0, 0) # 0 ready, 1 observed, 2 completed + seen: tuple[int, int] = (0, 0) + stale_commit: bool = False + + +def changed(values: tuple[int, int], index: int, value: int) -> tuple[int, int]: + result = list(values) + result[index] = value + return (result[0], result[1]) + + +def blue_actions(s: State): + for i in range(2): + if s.holder == -1 and s.phase[i] == 0 and s.epoch < 3: + yield f"acquire_{i}", replace( + s, holder=i, phase=changed(s.phase, i, 1), + seen=changed(s.seen, i, s.epoch), + ) + if s.holder == i and s.phase[i] == 1: + if s.seen[i] == s.epoch: + yield f"commit_{i}", replace( + s, holder=-1, owner=TARGETS[i], epoch=s.epoch + 1, + phase=changed(s.phase, i, 2), + ) + yield f"crash_{i}", replace( + s, holder=-1, phase=changed(s.phase, i, 2), + ) + + +def unsafe_actions(s: State): + for i in range(2): + if s.phase[i] == 0: + yield f"read_{i}", replace( + s, phase=changed(s.phase, i, 1), + seen=changed(s.seen, i, s.epoch), + ) + if s.phase[i] == 1: + yield f"write_{i}", replace( + s, owner=TARGETS[i], epoch=s.seen[i] + 1, + phase=changed(s.phase, i, 2), + stale_commit=s.stale_commit or s.seen[i] != s.epoch, + ) + + +def explore(next_actions, invariant): + initial = State() + q = deque([(initial, ())]) + visited = {initial} + while q: + state, actions = q.popleft() + if not invariant(state): + return actions, visited + for action, next_state in next_actions(state): + if next_state not in visited: + visited.add(next_state) + q.append((next_state, actions + (action,))) + return None, visited + + +class SessionWriterFenceTests(unittest.TestCase): + def test_fenced_two_processes_cannot_stale_commit_or_overlap(self): + def invariant(s: State): + held = [i for i, phase in enumerate(s.phase) if phase == 1] + return ( + not s.stale_commit + and len(held) <= 1 + and (not held or held[0] == s.holder) + and (s.epoch > 1 or s.owner == "A") + ) + + counterexample, states = explore(blue_actions, invariant) + self.assertIsNone(counterexample) + self.assertGreater(len(states), 5) + self.assertTrue(any(s.epoch == 3 for s in states)) + + def test_unfenced_read_then_write_has_real_stale_epoch_counterexample(self): + counterexample, states = explore(unsafe_actions, lambda s: not s.stale_commit) + self.assertIsNotNone(counterexample) + self.assertIn("read_0", counterexample) + self.assertIn("read_1", counterexample) + self.assertIn("write_0", counterexample) + self.assertIn("write_1", counterexample) + self.assertGreater(len(states), 5) + + def test_explicit_old_writer_cannot_commit_after_new_owner(self): + # Unsafe interleaving: two workers first accept owner A generation 1. + s = State() + s = dict(unsafe_actions(s))["read_0"] + s = dict(unsafe_actions(s))["read_1"] + s = dict(unsafe_actions(s))["write_0"] + self.assertEqual((s.owner, s.epoch), ("B", 2)) + s = dict(unsafe_actions(s))["write_1"] + self.assertTrue(s.stale_commit) + self.assertEqual((s.owner, s.epoch), ("C", 2)) + # A missing CAS permits replay of generation 2 without increment. + + +if __name__ == "__main__": + unittest.main() diff --git a/formal/tla/SessionWriterFence.cfg b/formal/tla/SessionWriterFence.cfg new file mode 100644 index 00000000..e78748cc --- /dev/null +++ b/formal/tla/SessionWriterFence.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT MaxEpoch = 3 +INVARIANTS TypeOK NoStaleWrite NoConcurrentPrepared NoFalseInitialOwner diff --git a/formal/tla/SessionWriterFence.tla b/formal/tla/SessionWriterFence.tla new file mode 100644 index 00000000..8e49aeb2 --- /dev/null +++ b/formal/tla/SessionWriterFence.tla @@ -0,0 +1,66 @@ +------------------------ MODULE SessionWriterFence ------------------------ +EXTENDS Naturals, TLC + +\* Two independently scheduled workers use one durable logical owner. +\* This model describes a proposed fencing protocol, NOT existing WineBot. +CONSTANT MaxEpoch +ASSUME MaxEpoch \in Nat \ {0} +Writers == {"one", "two"} +Sessions == {"A", "B", "C"} +Phases == {"idle", "seen", "done"} +Target(w) == IF w = "one" THEN "B" ELSE "C" + +VARIABLES epoch, owner, holder, phase, observed, staleCommit +vars == <> + +Init == + /\ epoch = 1 + /\ owner = "A" + /\ holder = "none" + /\ phase = [w \in Writers |-> "idle"] + /\ observed = [w \in Writers |-> 0] + /\ staleCommit = FALSE + +Acquire(w) == + /\ holder = "none" + /\ phase[w] = "idle" + /\ epoch < MaxEpoch + /\ holder' = w + /\ phase' = [phase EXCEPT ![w] = "seen"] + /\ observed' = [observed EXCEPT ![w] = epoch] + /\ UNCHANGED <> + +Commit(w) == + /\ holder = w + /\ phase[w] = "seen" + /\ observed[w] = epoch + /\ epoch < MaxEpoch + /\ owner' = Target(w) + /\ epoch' = epoch + 1 + /\ holder' = "none" + /\ phase' = [phase EXCEPT ![w] = "done"] + /\ UNCHANGED <> + +Crash(w) == + /\ holder = w + /\ phase[w] = "seen" + /\ holder' = "none" + /\ phase' = [phase EXCEPT ![w] = "done"] + /\ UNCHANGED <> + +Next == \E w \in Writers : (Acquire(w) \/ Commit(w) \/ Crash(w)) +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ epoch \in 1..MaxEpoch + /\ owner \in Sessions + /\ holder \in Writers \cup {"none"} + /\ phase \in [Writers -> Phases] + /\ observed \in [Writers -> 0..MaxEpoch] + /\ staleCommit \in BOOLEAN + +NoStaleWrite == ~staleCommit +NoConcurrentPrepared == + \A w \in Writers : (phase[w] = "seen" => holder = w) +NoFalseInitialOwner == epoch = 1 => owner = "A" +============================================================================= \ No newline at end of file diff --git a/formal/tla/SessionWriterFenceUnsafe.cfg b/formal/tla/SessionWriterFenceUnsafe.cfg new file mode 100644 index 00000000..84b284a3 --- /dev/null +++ b/formal/tla/SessionWriterFenceUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT NoStaleWrite diff --git a/formal/tla/SessionWriterFenceUnsafe.tla b/formal/tla/SessionWriterFenceUnsafe.tla new file mode 100644 index 00000000..4a09aeca --- /dev/null +++ b/formal/tla/SessionWriterFenceUnsafe.tla @@ -0,0 +1,36 @@ +--------------------- MODULE SessionWriterFenceUnsafe --------------------- +EXTENDS Naturals, TLC + +\* Deliberately BROKEN: two workers read the same epoch, then each writes. +\* Stale last-writer-wins commit must be rejected by mandatory TLC negative. +Writers == {"one", "two"} +Target(w) == IF w = "one" THEN "B" ELSE "C" +VARIABLES epoch, owner, phase, observed, staleCommit +vars == <> + +Init == + /\ epoch = 1 + /\ owner = "A" + /\ phase = [w \in Writers |-> "idle"] + /\ observed = [w \in Writers |-> 0] + /\ staleCommit = FALSE + +Observe(w) == + /\ phase[w] = "idle" + /\ phase' = [phase EXCEPT ![w] = "seen"] + /\ observed' = [observed EXCEPT ![w] = epoch] + /\ UNCHANGED <> + +UnsafeCommit(w) == + /\ phase[w] = "seen" + /\ owner' = Target(w) + /\ epoch' = observed[w] + 1 + /\ staleCommit' = staleCommit \/ (observed[w] # epoch) + /\ phase' = [phase EXCEPT ![w] = "done"] + /\ UNCHANGED observed + +Next == \E w \in Writers : (Observe(w) \/ UnsafeCommit(w)) +Spec == Init /\ [][Next]_vars + +NoStaleWrite == ~staleCommit +============================================================================= \ No newline at end of file From 9cdf1e9a826efc2d2e50722eb693fef5706df739 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:13:31 +0100 Subject: [PATCH 2/3] ci(formal): expose bounded unexpected unsafe-model diagnostic The blue two-writer TLC run passed but the mandatory expected red counterexample was not observed in CI. Print only filtered public-model TLC errors to identify the exact first cause. Keep the negative gate fail-closed; no waiver, bypass or log artifact upload. --- .github/workflows/formal-cross-layer-tlc.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index 2a9d82d0..3d8ee26a 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -110,6 +110,10 @@ jobs: if ! grep -Fq 'Invariant NoStaleWrite is violated' \ "$RUNNER_TEMP/formal/unsafe-two-writer.log"; then echo "FORMAL_TWO_WRITER_NEGATIVE=NO_EXPECTED_COUNTEREXAMPLE" + # All input is versioned public synthetic model source; print + # only bounded diagnostic lines, never runner environment dumps. + grep -E '^(Error:|Invariant |Semantic errors|.*Error.*|.*SessionWriterFenceUnsafe.*)' \ + "$RUNNER_TEMP/formal/unsafe-two-writer.log" | head -n 20 || true exit 1 fi echo "FORMAL_TWO_WRITER_NEGATIVE=STALE_COMMIT_COUNTEREXAMPLE_CONFIRMED" From 638f3cacd0451009fa39371af4d4451e2cdd5a02 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:14:44 +0100 Subject: [PATCH 3/3] fix(formal): parenthesize stale-commit boolean disjunction in TLC red control Exact-head TLC #44912828275 identified an underdetermined successor: without grouping the expression, an OR branch failed to assign the primed staleCommit variable. Correct only operator grouping; retain mandatory expected NoStaleWrite counterexample and green-model checks. --- formal/tla/SessionWriterFenceUnsafe.tla | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formal/tla/SessionWriterFenceUnsafe.tla b/formal/tla/SessionWriterFenceUnsafe.tla index 4a09aeca..4628f0f8 100644 --- a/formal/tla/SessionWriterFenceUnsafe.tla +++ b/formal/tla/SessionWriterFenceUnsafe.tla @@ -25,7 +25,7 @@ UnsafeCommit(w) == /\ phase[w] = "seen" /\ owner' = Target(w) /\ epoch' = observed[w] + 1 - /\ staleCommit' = staleCommit \/ (observed[w] # epoch) + /\ staleCommit' = (staleCommit \/ (observed[w] # epoch)) /\ phase' = [phase EXCEPT ![w] = "done"] /\ UNCHANGED observed