"""Manage one cooperating training chain and its save-and-stop request.""" import fcntl import hashlib import os import subprocess import sys import tempfile import time from pathlib import Path from tk import paths def root(): project = hashlib.sha256(os.fsencode(paths.ROOT)).hexdigest()[:12] base = Path(os.environ.get("TK_RECOVERY_DIR", Path.home() / "Library/Application Support/Turbo-Kev")) return base / project def session(): value = os.environ.get("TK_RUN_SESSION") return Path(value) if value else None def requested(): directory = session() return directory is not None and (directory / "stop").exists() def finish_pause(message): print(message, flush=True) directory = session() if directory is not None: (directory / "saved.tmp").write_text(message) (directory / "saved.tmp").replace(directory / "saved") raise SystemExit(75) def unlocked(lock): try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return False fcntl.flock(lock, fcntl.LOCK_UN) return True def stop(base, lock): with (base / "registration").open("a") as registration: fcntl.flock(registration, fcntl.LOCK_EX) if unlocked(lock): return report(base, active=False) directory = Path((base / "current").read_text()) (directory / "stop").touch() print("Stop requested. Waiting for a saved training step or a completed stage...", flush=True) while not (directory / "exit").exists(): changed = (base / "current").read_text() != str(directory) if (changed or unlocked(lock)) and not (directory / "exit").exists(): print("The run exited before confirming a safe stop.", file=sys.stderr) return 1 time.sleep(0.25) code = int((directory / "exit").read_text()) if code == 75 and (directory / "saved").exists(): print((directory / "saved").read_text()) return 0 if code == 0: print("The run completed.") return 0 print(f"The run exited with status {code} before confirming a safe stop.", file=sys.stderr) return 1 def report(base, active): current = base / "current" if not current.exists(): print("No managed training run recorded.") return 0 directory = Path(current.read_text()) result = 0 if active: print("Stop requested." if (directory / "stop").exists() else "Training run active.") elif (directory / "exit").exists(): code = int((directory / "exit").read_text()) if code == 75 and (directory / "saved").exists(): print((directory / "saved").read_text()) else: print("Run completed." if code == 0 else f"Run exited with status {code}.") result = int(code != 0) else: print("Run ended without confirming a safe stop.") result = 1 if (directory / "log").exists(): print(f'Log: {(directory / "log").read_text()}') return result def supervise(command, directory, lock_fd): try: returncode = subprocess.call(command, env={**os.environ, "TK_RUN_SESSION": str(directory)}, pass_fds=(lock_fd,)) except OSError as exc: print(exc, file=sys.stderr) returncode = 1 (directory / "exit.tmp").write_text(str(returncode)) (directory / "exit.tmp").replace(directory / "exit") return returncode def background(name, command, directory, lock): # The foreground launcher holds the run lock before creating a log or PID. paths.RUNS.mkdir(exist_ok=True) log = paths.RUNS / f"{name}-{time.strftime('%Y%m%d-%H%M%S')}.log" if log.exists(): log = log.with_name(f"{log.stem}-{time.time_ns()}.log") with log.open("x") as output: (directory / "log").write_text(str(log)) worker = [sys.executable, "-m", "tk.control", "worker", str(directory), str(lock.fileno()), "/usr/bin/caffeinate", "-i", *command] child = subprocess.Popen(worker, pass_fds=(lock.fileno(),), start_new_session=True, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT) try: pending = paths.RUNS / f"{name}.pid.tmp" pending.write_text(f"{child.pid}\n") pending.replace(paths.RUNS / f"{name}.pid") except OSError as exc: print(f"Could not record PID: {exc}", file=sys.stderr) print(f"Started {name} pid {child.pid} -> {log}") return 0 def main(): if sys.argv[1] == "worker": code = supervise(sys.argv[4:], Path(sys.argv[2]), int(sys.argv[3])) print(f"EXIT={code}", flush=True) return code if sys.argv[1] == "boundary": if requested(): finish_pause("Stopped between stages. Resume with the chain command.") return 0 base = root() base.mkdir(parents=True, exist_ok=True) with (base / "lock").open("a") as lock: if sys.argv[1] == "stop": return stop(base, lock) with (base / "registration").open("a") as registration: fcntl.flock(registration, fcntl.LOCK_EX) if sys.argv[1] == "status": report(base, active=not unlocked(lock)) return 0 try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: print("A training run is already active.", file=sys.stderr) return 1 directory = Path(tempfile.mkdtemp(prefix="run-", dir=base)) (base / "current.tmp").write_text(str(directory)) (base / "current.tmp").replace(base / "current") if sys.argv[1] == "background": return background(sys.argv[2], sys.argv[3:], directory, lock) return supervise(sys.argv[2:], directory, lock.fileno()) if __name__ == "__main__": sys.exit(main())