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
26 changes: 25 additions & 1 deletion .github/workflows/formal-cross-layer-tlc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 \
Expand Down Expand Up @@ -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: |
Expand Down
9 changes: 9 additions & 0 deletions .github/workflows/wine11-disposable-layer-hil.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
172 changes: 172 additions & 0 deletions api/core/persistent_owner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""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
78 changes: 78 additions & 0 deletions formal/PERSISTENT_SESSION_OWNER.md
Original file line number Diff line number Diff line change
@@ -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.
Loading