"""Durable, atomic campaign state storage and the per-campaign run lock. Extracted from campaign.py (Session 1 of the refactor-handoffs plan, docs/refactor-handoffs/01-file-splits.md, Task 3). """ from __future__ import annotations import os import sys from datetime import datetime, timezone from pathlib import Path from afk_developer import fsutil from afk_developer.campaign_models import CampaignState class CampaignBusyError(RuntimeError): """Raised when another process owns the durable campaign lease.""" def _pid_is_alive(pid: int) -> bool: """Check a process without using ``os.kill(pid, 0)`` on Windows. On Windows, Python maps signal ``0`` through the console-control signal path. Checking a lock held by the current pytest process can consequently raise ``KeyboardInterrupt``. Query the process handle instead. """ if pid <= 0: return False if sys.platform != "win32": try: os.kill(pid, 0) except OSError: return False return True import ctypes process_query_limited_information = 0x1000 handle = ctypes.windll.kernel32.OpenProcess( process_query_limited_information, False, pid, ) if not handle: return False ctypes.windll.kernel32.CloseHandle(handle) return True def _process_start_token(pid: int) -> str: """Return a stable per-launch token for ``pid``, or ``""`` if unavailable. A bare PID is not a durable identity: the OS recycles it, so a lock whose owner died can be adopted by an unrelated process and never self-release. Pairing the PID with its process start time distinguishes the two. """ if pid <= 0: return "" if sys.platform != "win32": try: fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(") ", 1)[-1] except OSError: return "" parts = fields.split() # Field 22 of /proc/pid/stat, offset by the two fields before it here. return parts[19] if len(parts) > 19 else "" import ctypes from ctypes import wintypes process_query_limited_information = 0x1000 handle = ctypes.windll.kernel32.OpenProcess( process_query_limited_information, False, pid, ) if not handle: return "" try: creation = wintypes.FILETIME() unused = (wintypes.FILETIME(), wintypes.FILETIME(), wintypes.FILETIME()) ok = ctypes.windll.kernel32.GetProcessTimes( handle, ctypes.byref(creation), ctypes.byref(unused[0]), ctypes.byref(unused[1]), ctypes.byref(unused[2]), ) if not ok: return "" return f"{creation.dwHighDateTime}:{creation.dwLowDateTime}" finally: ctypes.windll.kernel32.CloseHandle(handle) def _owner_still_running(owner_pid: int, owner_token: str) -> bool: """Decide whether a lock's recorded owner is genuinely still alive.""" if not _pid_is_alive(owner_pid): return False if not owner_token: # Legacy lock file, or a platform that withheld the start time. return True current_token = _process_start_token(owner_pid) return not current_token or current_token == owner_token class CampaignStore: """Atomic state storage outside the target repository.""" def __init__(self, projects_dir: Path) -> None: self.root = projects_dir / "campaigns" def path_for(self, name: str) -> Path: return self.root / f"{name}.json" def load(self, name: str) -> CampaignState | None: path = self.path_for(name) if not path.is_file(): return None return CampaignState.model_validate_json(path.read_text(encoding="utf-8")) def find_by_plan_name(self, plan_name: str) -> CampaignState | None: """Return the campaign owning a phase/batch plan, if any. A manual single-task retry only knows the plan name (e.g. a phase plan like ``my-campaign-phase-003``), not which campaign wraps it. Scanning every persisted campaign lets a retry that resolves the task also clear a stale campaign-level escalation left over from before the retry, without the caller needing to know the campaign name up front. """ if not self.root.is_dir(): return None for candidate in self.root.glob("*.json"): try: campaign = CampaignState.model_validate_json(candidate.read_text(encoding="utf-8")) except (OSError, ValueError): continue if any(phase.plan_name == plan_name for phase in campaign.phases): return campaign if any(batch.plan_name == plan_name for batch in campaign.batches): return campaign return None def save(self, campaign: CampaignState) -> Path: self.root.mkdir(parents=True, exist_ok=True) campaign.updated_at = datetime.now(timezone.utc) path = self.path_for(campaign.name) fsutil.atomic_write_text(path, campaign.model_dump_json(indent=2)) return path def acquire_run_lock(self, name: str) -> Path: """Acquire an exclusive per-campaign lock and recover a dead-owner lock.""" self.root.mkdir(parents=True, exist_ok=True) path = self.root / f"{name}.lock" for _ in range(2): try: descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) except FileExistsError: try: recorded = path.read_text(encoding="utf-8").strip().split("\n") owner_pid = int(recorded[0].strip()) except (OSError, ValueError, IndexError): path.unlink(missing_ok=True) continue owner_token = recorded[1].strip() if len(recorded) > 1 else "" if not _owner_still_running(owner_pid, owner_token): path.unlink(missing_ok=True) continue raise CampaignBusyError(f"Campaign '{name}' is already running (PID {owner_pid}).") else: with os.fdopen(descriptor, "w", encoding="utf-8") as handle: pid = os.getpid() handle.write(f"{pid}\n{_process_start_token(pid)}") return path raise CampaignBusyError(f"Could not acquire campaign lock for '{name}'.") @staticmethod def release_run_lock(path: Path) -> None: path.unlink(missing_ok=True)