Skip to content
Closed
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
8 changes: 8 additions & 0 deletions .github/workflows/formal-cross-layer-tlc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ on:
pull_request:
paths:
- "formal/**"
- "api/core/broker.py"
- "api/core/handover_recovery.py"
- "api/routers/input.py"
- "api/routers/lifecycle.py"
- "api/server.py"
- "tests/test_mvp_control_safety.py"
- "tests/test_handover_restart_recovery.py"
- "scripts/ci/test.sh"
- ".github/workflows/formal-cross-layer-tlc.yml"
workflow_dispatch:

Expand Down
135 changes: 135 additions & 0 deletions api/core/handover_recovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""Conservative restart reconciliation for an interrupted session handover.

Only the current active-session pointer is authoritative on restart. We never
guess another session from loose markers or accept paths outside the current
session's parent directory. No Wine process is started by this reconciler.
"""
import json
import os
from pathlib import Path

from api.core.constants import (
SESSION_STATE_ACTIVE,
SESSION_STATE_COMPLETED,
SESSION_STATE_SUSPENDED,
)
from api.utils.files import read_session_state, write_session_state

MARKER_NAME = "session.transition.json"
_MAX_MARKER_BYTES = 16384


def _safe_peer(raw: object, active: Path) -> Path | None:
if raw is None:
return None
if not isinstance(raw, str) or not raw:
raise RuntimeError("Invalid handover peer")
path = Path(raw)
if not path.is_absolute() or path.is_symlink():
raise RuntimeError("Invalid handover peer")
resolved = path.resolve(strict=True)
if resolved.parent != active.parent or not resolved.is_dir():
raise RuntimeError("Handover peer is outside current session root")
return resolved


def _marker(session: Path) -> dict | None:
path = session / MARKER_NAME
if path.is_symlink():
raise RuntimeError("Refusing symlink handover marker")
if not path.exists():
return None
if path.stat().st_size > _MAX_MARKER_BYTES:
raise RuntimeError("Oversized handover marker")
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise RuntimeError("Invalid handover marker") from exc
if not isinstance(data, dict) or not isinstance(data.get("extra"), dict):
raise RuntimeError("Invalid handover marker envelope")
if not isinstance(data["extra"].get("operation_id"), str):
raise RuntimeError("Missing handover operation identity")
return data


def _remove_durable(session: Path) -> None:
path = session / MARKER_NAME
if path.is_symlink():
raise RuntimeError("Refusing symlink handover marker")
if path.exists():
path.unlink()
directory_fd = os.open(str(session), os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)


def reconcile_active_handover(session_dir: str, profile_link: str) -> str:
"""Converge interrupted ownership to the active pointer, fail closed.

Call only after the runtime has relinked the user profile and updated its
in-process broker for the active session. Reconcile no other session unless
its marker matches the exact same operation and points back to active.
"""
active = Path(session_dir).resolve(strict=True)
marker = _marker(active)
if marker is None:
return "no_marker"
if not active.is_dir() or not (active / "user").is_dir():
raise RuntimeError("Active session profile unavailable")
link = Path(profile_link)
if not link.is_symlink() or link.resolve(strict=True) != (active / "user").resolve():
raise RuntimeError("Active Wine profile link disagrees with session pointer")

phase = marker.get("phase")
extra = marker["extra"]
operation_id = extra["operation_id"]
if phase == "resume_target_prepare":
peer = _safe_peer(extra.get("previous_session"), active)
if peer is not None and peer != active:
other = _marker(peer)
# The original transaction writes BOTH markers before changing
# the active pointer. A missing peer marker at this phase is not
# an admissible crash outcome, and must remain quarantined.
if other is None:
# Crash after deleting a peer marker is replayable only if
# both persisted owners already reached the safe end state.
if (read_session_state(str(active)) != SESSION_STATE_ACTIVE or
read_session_state(str(peer)) not in
(SESSION_STATE_SUSPENDED, SESSION_STATE_COMPLETED)):
raise RuntimeError("Absent handover peer marker before commit")
elif (other.get("phase") != "resume_handover_out" or
other["extra"].get("operation_id") != operation_id or
_safe_peer(other["extra"].get("target_session"), peer) != active):
raise RuntimeError("Conflicting handover peer marker")
if peer is not None and peer != active:
if read_session_state(str(peer)) in (None, SESSION_STATE_ACTIVE):
write_session_state(str(peer), SESSION_STATE_SUSPENDED)
write_session_state(str(active), SESSION_STATE_ACTIVE)
if peer is not None and peer != active:
_remove_durable(peer)
elif phase == "resume_handover_out":
peer = _safe_peer(extra.get("target_session"), active)
if peer is not None and peer != active:
other = _marker(peer)
if other is None:
if (read_session_state(str(active)) != SESSION_STATE_ACTIVE or
read_session_state(str(peer)) not in
(SESSION_STATE_SUSPENDED, SESSION_STATE_COMPLETED)):
raise RuntimeError("Absent handover peer marker before commit")
elif (other.get("phase") != "resume_target_prepare" or
other["extra"].get("operation_id") != operation_id or
_safe_peer(other["extra"].get("previous_session"), peer) != active):
raise RuntimeError("Conflicting handover peer marker")
# Even a stray target ACTIVE must not leave dual active state.
if read_session_state(str(peer)) in (None, SESSION_STATE_ACTIVE):
write_session_state(str(peer), SESSION_STATE_SUSPENDED)
write_session_state(str(active), SESSION_STATE_ACTIVE)
if peer is not None and peer != active:
_remove_durable(peer)
else:
raise RuntimeError("Unknown handover phase")

_remove_durable(active)
return "reconciled"
53 changes: 46 additions & 7 deletions api/routers/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,17 @@ def _restore_resume_state(
os.environ["WINEBOT_SESSION_ID"] = os.path.basename(previous_session_dir)
if previous_current_state:
write_session_state(previous_session_dir, previous_current_state)
# Restore and verify the Wine profile link after a failed activation.
_link_profile_checked(os.path.join(previous_session_dir, "user"))


def _link_profile_checked(user_dir: str) -> None:
link_wine_user_dir(user_dir)
profile_link = os.path.join(
os.getenv("WINEPREFIX", "/wineprefix"), "drive_c", "users", "winebot"
)
if not os.path.islink(profile_link) or os.path.realpath(profile_link) != os.path.realpath(user_dir):
raise RuntimeError("Session profile link verification failed")


def _transition_marker_path(session_dir: str) -> str:
Expand All @@ -443,17 +454,27 @@ def _write_transition_marker(session_dir: str, phase: str, extra: dict[str, Any]
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, _transition_marker_path(session_dir))
# fsync directory so the intent rename survives a process crash/reboot.
directory_fd = os.open(session_dir, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)


def _clear_transition_marker(session_dir: str | None) -> None:
if not session_dir:
return
path = _transition_marker_path(session_dir)
try:
if os.path.exists(path):
os.unlink(path)
except Exception:
pass
if os.path.islink(path):
raise RuntimeError("Refusing symlink transition marker")
if os.path.exists(path):
os.unlink(path)
directory_fd = os.open(session_dir, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)


@router.get("/operations/{operation_id}")
Expand Down Expand Up @@ -991,7 +1012,7 @@ async def resume_session(data: SessionResumeModel | None = Body(default=None)):
os.environ["WINEBOT_SESSION_DIR"] = target_dir
os.environ["WINEBOT_SESSION_ID"] = os.path.basename(target_dir)
os.environ["WINEBOT_USER_DIR"] = user_dir
link_wine_user_dir(user_dir)
_link_profile_checked(user_dir)
write_session_state(target_dir, SESSION_STATE_ACTIVE)
append_lifecycle_event(
target_dir, "session_resumed", "Session resumed via API", source="api"
Expand All @@ -1013,16 +1034,34 @@ async def resume_session(data: SessionResumeModel | None = Body(default=None)):
interactive,
session_control_mode=session_control_mode,
)
_clear_transition_marker(target_dir)
# Commit the prior owner out of ACTIVE before removing the durable
# intent. If this write is interrupted, startup replay can finish.
if current_session and current_session != target_dir:
if previous_current_state in (None, SESSION_STATE_ACTIVE):
write_session_state(current_session, SESSION_STATE_SUSPENDED)
# Keep the active-side intent until last: if we die after
# removing the peer marker, startup can verify converged state
# and finish active-side cleanup idempotently.
if current_session and current_session != target_dir:
_clear_transition_marker(current_session)
_clear_transition_marker(target_dir)
except Exception as exc:
_restore_resume_state(
previous_session_dir=current_session,
target_dir=target_dir,
previous_target_state=previous_target_state,
previous_current_state=previous_current_state,
)
# A first activation has no older owner to compensate to.
# Retain transaction intent for startup reconciliation rather
# than silently acknowledging an incomplete operation.
if not current_session and read_session_dir() == target_dir:
await fail_operation(
operation_id, error="handover requires restart reconciliation"
)
raise RuntimeError(
"Interrupted session activation requires restart reconciliation"
) from exc
_clear_transition_marker(target_dir)
if current_session and current_session != target_dir:
_clear_transition_marker(current_session)
Expand Down
6 changes: 6 additions & 0 deletions api/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from api.core.broker import broker
from api.core.config_guard import validate_current_environment
from api.core.discovery import discovery_manager
from api.core.handover_recovery import reconcile_active_handover
from api.core.models import ControlPolicyMode
from api.core.monitor import inactivity_monitor_task
from api.core.session_context import reset_current_session_dir, set_current_session_dir
Expand Down Expand Up @@ -115,6 +116,11 @@ async def lifespan(_app: FastAPI):
interactive,
session_control_mode=session_control_mode,
)
# Reconcile a pending handover before readiness or new input grants.
profile_link = os.path.join(
os.getenv("WINEPREFIX", "/wineprefix"), "drive_c", "users", "winebot"
)
reconcile_active_handover(session_dir, profile_link)

# Start Discovery
try:
Expand Down
3 changes: 2 additions & 1 deletion scripts/ci/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,5 @@ pytest \
tests/test_mvp_control_safety.py \
tests/test_mvp_control_api.py \
tests/test_mvp_mouse_lease.py \
tests/test_mvp_inflight_cancel.py
tests/test_mvp_inflight_cancel.py \
tests/test_handover_restart_recovery.py
2 changes: 1 addition & 1 deletion tests/test_api_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ def test_resume_session_rolls_back_state_on_broker_failure(tmp_path):
with patch("api.routers.lifecycle.read_session_dir", return_value=str(current_dir)):
with patch("api.routers.lifecycle.resolve_session_dir", return_value=str(target_dir)):
with patch("api.routers.lifecycle.append_lifecycle_event"):
with patch("api.routers.lifecycle.link_wine_user_dir"):
with patch("api.routers.lifecycle._link_profile_checked"):
with patch("api.routers.lifecycle.ensure_user_profile"):
with patch(
"api.routers.lifecycle.atomic_shutdown",
Expand Down
Loading