Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion .github/workflows/formal-cross-layer-tlc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down Expand Up @@ -95,6 +95,28 @@ 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"
# 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"
- name: Run dependency-free model contract tests
shell: bash
run: |
Expand Down
72 changes: 72 additions & 0 deletions formal/SESSION_WRITER_FENCING.md
Original file line number Diff line number Diff line change
@@ -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.
116 changes: 116 additions & 0 deletions formal/tests/test_session_writer_fence.py
Original file line number Diff line number Diff line change
@@ -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()
3 changes: 3 additions & 0 deletions formal/tla/SessionWriterFence.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SPECIFICATION Spec
CONSTANT MaxEpoch = 3
INVARIANTS TypeOK NoStaleWrite NoConcurrentPrepared NoFalseInitialOwner
66 changes: 66 additions & 0 deletions formal/tla/SessionWriterFence.tla
Original file line number Diff line number Diff line change
@@ -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 == <<epoch, owner, holder, phase, observed, staleCommit>>

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 <<epoch, owner, staleCommit>>

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 <<observed, staleCommit>>

Crash(w) ==
/\ holder = w
/\ phase[w] = "seen"
/\ holder' = "none"
/\ phase' = [phase EXCEPT ![w] = "done"]
/\ UNCHANGED <<epoch, owner, observed, staleCommit>>

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"
=============================================================================
2 changes: 2 additions & 0 deletions formal/tla/SessionWriterFenceUnsafe.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SPECIFICATION Spec
INVARIANT NoStaleWrite
36 changes: 36 additions & 0 deletions formal/tla/SessionWriterFenceUnsafe.tla
Original file line number Diff line number Diff line change
@@ -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 == <<epoch, owner, phase, observed, staleCommit>>

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 <<epoch, owner, staleCommit>>

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
=============================================================================