diff --git a/pkgs/laptop-agent/package.nix b/pkgs/laptop-agent/package.nix new file mode 100644 index 0000000000..abded492b1 --- /dev/null +++ b/pkgs/laptop-agent/package.nix @@ -0,0 +1,47 @@ +# laptop-agent daemon — the reconciled single source (code#10131). +# +# Union of the live daemon lineage (timeout semantics, trip logging, +# /exec cancel, disconnect reap, /file) and the darwin-nix vendored +# lineage this package shape comes from (persisted job index, +# fail-closed startup validation, request-framing 400s, job +# summaries, spool reaping, bytes-space auth). Vendored here as the +# canonical source; the nix module that deploys the daemon consumes +# this package. See src/laptop_agent.py's header for the full +# reconciliation notes. +{ + lib, + stdenv, + python3, + bash, + makeWrapper, +}: + +stdenv.mkDerivation { + pname = "laptop-agent"; + version = "0.1.0"; + + # The resident fleet execution agent (code#5343): a single + # stdlib-only Python daemon. The sandbox session proxy routes + # laptop-agent, secrets broker, and queue broker traffic to it and + # its sibling brokers. + src = ./src; + + nativeBuildInputs = [ makeWrapper ]; + + dontBuild = true; + + installPhase = '' + runHook preInstall + install -Dm755 laptop_agent.py $out/libexec/laptop_agent.py + makeWrapper ${python3}/bin/python3 $out/bin/laptop-agent \ + --add-flags "$out/libexec/laptop_agent.py" \ + --set LAPTOP_AGENT_BASH ${bash}/bin/bash + runHook postInstall + ''; + + meta = { + description = "laptop-agent — resident fleet execution agent daemon (reconciled source, code#10131)"; + mainProgram = "laptop-agent"; + platforms = lib.platforms.unix; + }; +} diff --git a/pkgs/laptop-agent/src/laptop_agent.py b/pkgs/laptop-agent/src/laptop_agent.py new file mode 100644 index 0000000000..4318bda458 --- /dev/null +++ b/pkgs/laptop-agent/src/laptop_agent.py @@ -0,0 +1,1159 @@ +#!/usr/bin/env python3 +"""laptop-agent daemon — resident execution agent on Drew's laptop. + +Design: developing-today/code#5343. Single file, Python stdlib only. +Binds the tailnet interface only; every request needs the X-Agent-Token +header (token in ~/.config/laptop-agent/token, mode 600). Startup fails +closed when that token is missing, empty, or whitespace-only. + +API (JSON): + GET /health -> {ok, uptime_s, jobs, load1} + POST /exec {cmds:[{cwd, argv|shell}], timeout_s?} + -> {results:[{exit, stdout, stderr, + duration_ms, truncated}]} + POST /jobs {cwd, argv|shell, env?} -> {job_id} + GET /jobs -> {jobs:[{job_id, state, exit, ...}]} + GET /jobs/?out_off&err_off -> {state, exit, stdout, stderr, + out_next, err_next, duration_ms} + POST /jobs//kill -> {ok, state} + POST /exec//cancel -> {ok, cancelled} (POST /cancel + {trip} is the legacy spelling) + GET /file?path=&off=&len= -> raw bytes (code#5757): the byte + range [off, off+len) of the file, + len capped at 1 MiB; response + headers X-File-Size (total size) + and X-File-Off echo the range. + Auth is the token header only, + exactly like every other route. + +Job stdout/stderr spool to ~/.local/state/laptop-agent/jobs// so a +daemon restart does not lose results: job metadata is persisted next to +the output and the index is rebuilt on startup. Finished jobs reaped +after 24h, spool directory included. + +Timeout semantics (2026-11-10, live lineage): every /exec command runs +in its OWN process group (start_new_session) and the whole group is +killed on timeout, on an explicit /cancel for its trip, or when the +client connection dies mid-exec — a caller-side timeout therefore +never leaves orphan processes behind on the laptop, grandchildren +included. Trip logging v2 (code#5702) appends one record per exec/job +to trips.jsonl in the state directory. + +Reconciliation (code#10131): this file is the union of the two daemon +lineages — the live daemon (timeout semantics, trip logging, /exec +cancel, disconnect reap, /file) and the vendored darwin-nix package +lineage (persisted job index, fail-closed token + startup-int +validation, request-framing errors as 400s, job summaries, spool +reaping, bytes-space auth). It is vendored into developing-today/code +at pkgs/laptop-agent/src/ as the single daemon source; the fleet +round-trip parity for both lineages' surfaces is the acceptance +evidence on #10131. +""" +import hashlib +import hmac +import json +import math +import os +import secrets +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlparse, parse_qs + + +def _parse_startup_int(name, raw, requirement, minimum, maximum=None): + """Validate an integer startup env var, or exit 3 naming it (#1510). + + A bare int() at import crashed with a raw ValueError traceback for + typos, and out-of-range values either tracebacked later at bind + (PORT=99999), silently bound an ephemeral port (PORT=0), or started + a healthy-looking daemon that could never run work (SLOTS=0). + Fail at startup instead, in the read_token house style. + """ + try: + value = int(raw) + except (TypeError, ValueError): + value = None + if (value is None or value < minimum + or (maximum is not None and value > maximum)): + print(f"laptop-agent: invalid {name}={raw!r}: {requirement}", + file=sys.stderr, flush=True) + sys.exit(3) + return value + + +BIND_HOST = os.environ.get("LAPTOP_AGENT_HOST", "100.99.113.103") +BIND_PORT = _parse_startup_int( + "LAPTOP_AGENT_PORT", os.environ.get("LAPTOP_AGENT_PORT", "4799"), + "must be an integer 1-65535", 1, 65535) +# Absolute interpreter for `shell` requests: NixOS has no /bin/bash, and +# the package wrapper sets this to the store path. The live lineage's +# resolution chain is the fallback when the wrapper did not set it +# (the 2026-11-04 laptop-ssh retirement verification caught shell mode +# failing with ENOENT for a hardcoded /bin/bash). +BASH = os.environ.get("LAPTOP_AGENT_BASH") or next( + (p for p in (shutil.which("bash"), + "/etc/profiles/per-user/user/bin/bash", + "/run/current-system/sw/bin/bash", + "/bin/bash") + if p and os.path.exists(p)), "/bin/bash") +TOKEN_FILE = Path(os.environ.get( + "LAPTOP_AGENT_TOKEN_FILE", Path.home() / ".config/laptop-agent/token")) +STATE_DIR = Path(os.environ.get( + "LAPTOP_AGENT_STATE", Path.home() / ".local/state/laptop-agent")) +MAX_OUT = 1 << 20 # per-stream capture cap for /exec (tail kept) +MAX_BODY = 1 << 20 # request body cap for /exec and /jobs +FILE_CHUNK_MAX = 1 << 20 # max bytes served per GET /file request +EXEC_TIMEOUT_DEFAULT = 120 +EXEC_TIMEOUT_MAX = 600 +JOB_TTL_S = 24 * 3600 +REAP_INTERVAL_S = 3600 # background reaper cadence (#1504) +KILL_GRACE_S = 5 +# Slot semantics (#1545): LAPTOP_AGENT_SLOTS is ONE shared pool for all +# work the daemon runs, not a per-route cap. POST /exec acquires a slot +# for the duration of the call; POST /jobs acquires a slot before +# spawning and holds it for the job's whole lifetime (the watch thread +# releases it when the process exits, including after a kill). Both +# routes wait up to 5s for a slot and then return 503 {"error": "busy"}: +# submissions are never queued indefinitely and never spawn past the cap. +SEMA = threading.Semaphore(_parse_startup_int( + "LAPTOP_AGENT_SLOTS", os.environ.get("LAPTOP_AGENT_SLOTS", "32"), + "must be an integer >= 1", 1)) +STARTED = time.time() + +JOBS = {} # job_id -> dict +JOBS_LOCK = threading.Lock() +TRIPS_FILE = STATE_DIR / "trips.jsonl" +EXEC_PROCS = {} # trip -> set[Popen] currently running for /exec +EXEC_PROCS_LOCK = threading.Lock() + + +def read_token(path: Path) -> str: + """Return the agent token, or exit non-zero before binding a listener. + + An empty file previously left TOKEN == "" so a request without the + header (also "") authenticated successfully (codex P1 on PR #1459). + """ + try: + token = path.read_text().strip() + except OSError as e: + print(f"laptop-agent: cannot read token file {path}: {e}", + file=sys.stderr, flush=True) + sys.exit(3) + if not token: + print(f"laptop-agent: token file {path} is empty; refusing to start", + file=sys.stderr, flush=True) + sys.exit(3) + return token + + +TOKEN = read_token(TOKEN_FILE) + + +def tail_bytes(data: bytes, cap: int): + if len(data) <= cap: + return data, False + return data[-cap:], True + + +def tail_file(path: Path, cap: int = MAX_OUT): + """Return the last `cap` bytes of a spool file and whether it was cut. + + Never reads the whole file into memory, so a noisy command cannot + exhaust the daemon. + """ + try: + with open(path, "rb") as f: + f.seek(0, os.SEEK_END) + size = f.tell() + start = max(0, size - cap) + f.seek(start) + data = f.read(cap) + return data, start > 0 + except OSError: + return b"", False + + +def _kill_group(pid: int, sig: int): + try: + os.killpg(pid, sig) + except OSError: + pass + + +def _group_alive(pid: int) -> bool: + try: + os.killpg(pid, 0) + return True + except OSError: + return False + + +def log_trip(trip, kind, cmd_str, duration_ms, exit_code, out_bytes, + err_bytes, t_received=None): + """Append one trip record (single O_APPEND write) to trips.jsonl. + + Safety: only the command's first token and the sha256 of the full + command string are recorded — never raw command text, environment, + headers, or token values. Perf/safety: logging must never fail or + visibly delay the request, so every error is swallowed. + + Trip logging v2 (code#5702): t_received is the millisecond epoch + stamped at request entry in do_POST; with the client's t_sent / + t_returned it splits the trip into outbound / daemon / return + legs. v1 fields are kept verbatim for v1 readers.""" + try: + parts = (cmd_str or "").split() + rec = {"v": 2, + "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "trip": trip, "kind": kind, + "cmd0": parts[0] if parts else "", + "cmd_sha256": hashlib.sha256( + (cmd_str or "").encode("utf-8", "replace")).hexdigest(), + "duration_ms": duration_ms, "exit": exit_code, + "out_bytes": out_bytes, "err_bytes": err_bytes} + if t_received is not None: + rec["t_received"] = t_received + fd = os.open(TRIPS_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, + 0o644) + try: + os.write(fd, (json.dumps(rec) + "\n").encode()) + finally: + os.close(fd) + except Exception: + pass + + +def kill_group(proc, grace_s=2.0): + """TERM a process group, escalate to KILL after grace_s. The exec + children run with start_new_session=True, so proc.pid is the pgid + and this reaches grandchildren that a plain proc.kill() misses.""" + try: + os.killpg(proc.pid, signal.SIGTERM) + except OSError: + pass + deadline = time.time() + grace_s + while time.time() < deadline: + if proc.poll() is not None: + break + time.sleep(0.05) + if proc.poll() is None: + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=5) + except Exception: + pass + + +def _drain(stream, buf): + try: + while True: + chunk = stream.read(65536) + if not chunk: + break + buf.append(chunk) + except (OSError, ValueError): + pass + + +def run_one(spec, timeout_s, trip=None, cancel_event=None): + """Run one command in its own process group, capturing output. + + The group dies when ANY of these fires: timeout_s expires, the + cancel_event is set (explicit /cancel or the client connection + died — see Handler._client_gone), or the watchdog notices. + Bytes are drained incrementally so a killed grandchild holding + the pipes open can never wedge the reader (the classic + subprocess.run+timeout hang).""" + cwd = spec.get("cwd") or str(Path.home()) + env = dict(os.environ) + env.update(spec.get("env") or {}) + if spec.get("shell") is not None: + argv = [BASH, "-lc", spec["shell"]] + cmd_str = spec["shell"] + else: + argv = list(spec["argv"]) + cmd_str = " ".join(argv) + t0 = time.time() + try: + proc = subprocess.Popen(argv, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True) + except Exception as e: # cwd missing, argv[0] missing, ... + return {"exit": None, "error": f"{type(e).__name__}: {e}", + "stdout": "", "stderr": "", + "duration_ms": int((time.time() - t0) * 1000), + "truncated": False, + "_cmd": cmd_str, "_out_bytes": 0, "_err_bytes": 0} + if trip: + with EXEC_PROCS_LOCK: + EXEC_PROCS.setdefault(trip, set()).add(proc) + out_parts, err_parts = [], [] + t_out = threading.Thread(target=_drain, + args=(proc.stdout, out_parts), daemon=True) + t_err = threading.Thread(target=_drain, + args=(proc.stderr, err_parts), daemon=True) + t_out.start() + t_err.start() + timed_out = False + cancelled = False + deadline = time.time() + timeout_s + try: + while True: + if proc.poll() is not None: + break + if cancel_event is not None and cancel_event.is_set(): + cancelled = True + kill_group(proc) + break + if time.time() >= deadline: + timed_out = True + kill_group(proc) + break + time.sleep(0.05) + finally: + if trip: + with EXEC_PROCS_LOCK: + s = EXEC_PROCS.get(trip) + if s is not None: + s.discard(proc) + if not s: + EXEC_PROCS.pop(trip, None) + # Collect whatever the pipes still hold, but never wait forever: + # a detached grandchild can keep a pipe fd open after the group + # leader dies; the capture cap makes a short grace sufficient. + t_out.join(timeout=2) + t_err.join(timeout=2) + out = b"".join(out_parts) + err = b"".join(err_parts) + out_t, out_tr = tail_bytes(out, MAX_OUT) + err_t, err_tr = tail_bytes(err, MAX_OUT) + result = {"exit": proc.returncode, + "stdout": out_t.decode("utf-8", "replace"), + "stderr": err_t.decode("utf-8", "replace"), + "duration_ms": int((time.time() - t0) * 1000), + "truncated": out_tr or err_tr, + "_cmd": cmd_str, "_out_bytes": len(out), + "_err_bytes": len(err)} + if timed_out: + result["exit"] = None + result["timeout"] = True + if cancelled: + result["exit"] = None + result["timeout"] = True + result["cancelled"] = True + return result + + +def _jobs_root(): + state_root = STATE_DIR.resolve() + jobs_root = (STATE_DIR / "jobs").resolve() + if jobs_root.parent != state_root: + raise ValueError("laptop-agent jobs directory escapes state directory") + return jobs_root + + +def job_dir(job_id): + if (not isinstance(job_id, str) or not job_id or job_id in (".", "..") + or "/" in job_id or "\\" in job_id): + raise ValueError("invalid laptop-agent job id") + base = _jobs_root() + d = base / job_id + if d.is_symlink(): + raise ValueError("laptop-agent job directory is a symlink") + try: + resolved = d.resolve() + except (OSError, RuntimeError) as e: + raise ValueError( + "cannot safely resolve laptop-agent job directory") from e + if resolved.parent != base: + raise ValueError("laptop-agent job directory escapes jobs directory") + return resolved + + +def _write_meta(job): + meta = {"id": job["id"], "cwd": job["cwd"], "cmd": job["cmd_repr"], + "started_at": job["started_at"], "ended_at": job["ended_at"], + "exit": job["exit"], "state": job["state"], + "interrupted": job.get("interrupted", False)} + try: + d = job_dir(job["id"]) + except (RuntimeError, ValueError) as e: + # A spool swapped for a symlink after load (#1575): job_dir() + # raises ValueError, which must stay contained here exactly as + # an OSError is -- job_state() calls this from both serializers, + # so a leak would poison every read of the job. One stderr line + # naming the job, as in the loader/reaper skip contract. + print(f"laptop-agent: cannot write meta for job " + f"{job['id']}: {e}", file=sys.stderr, flush=True) + return + try: + d.mkdir(parents=True, exist_ok=True) + tmp = d / "meta.json.tmp" + tmp.write_text(json.dumps(meta)) + os.replace(tmp, d / "meta.json") + except OSError: + pass + + +# Restore contract (design #1578, phase 1 -- issue #1579): the +# writer is the schema. _write_meta() writes exactly the eight +# fields in RESTORE_FIELD_TABLE; load_persisted_jobs() restores a +# persisted entry only through _restore_persisted_job(), driven by +# this table: for each field -- the shape the writer produces, the +# default when the field is missing/null, and the disposition when +# a present value violates the shape. Missing/null takes the named +# default; a present-but-malformed value is never laundered through +# a default -- the whole entry is skipped, one stderr line naming +# the directory and the field/reason, the spool left on disk +# untouched, and healthy siblings still restore (the fleet's +# established skip contract, stated once here instead of being +# restated in every per-field guard block). +# +# The exit/cwd/cmd rows originally recorded the writer shapes +# only, with enforcement owned by issue #1568; #1568 has since +# folded its checks into _restore_persisted_job() as table-driven +# rows below -- not as per-field guard blocks in the load loop -- +# exactly as the fold-in rule first stated here required. +RESTORE_FIELD_TABLE = ( + # (field, writer shape, missing/null default, malformed disposition) + ("id", "str job id (secrets.token_hex(6))", + "the spool directory name (also for an empty string)", + "skip: non-string, or a string that is not the directory " + "name or carries '.'/'..'/a path separator (#1548/#1554)"), + ("cwd", "str working directory", + "str(Path.home()) (via the restore tail's `or` default)", + "skip: any non-string present value (#1568, folded in as " + "a table row per #1579)"), + ("cmd", "str command representation", + "'' (via the restore tail's `or` default)", + "skip: any non-string present value (#1568, folded in as " + "a table row per #1579)"), + ("started_at", "float seconds since the epoch", + "0.0", + "skip: non-numeric, bool, non-finite, or oversized int " + "(#1513/#1523, PR #1534)"), + ("ended_at", "float seconds since the epoch, or None", + "stamped with time.time() at load (the transitions below)", + "skip: non-numeric, bool, non-finite, or oversized int " + "(#1513/#1523, PR #1534)"), + ("exit", "int process returncode, or None while running", + "None", + "skip: non-integer or bool present value (#1568, folded " + "in as a table row per #1579)"), + ("state", "'running' or 'done'", + "'done'", + "skip: any other present value (#1556)"), + ("interrupted", "bool", + "False", + "skip: any non-boolean present value (#1556)"), +) + +# The only coercions restore may perform (the table's transitions): +# persisted "running" -> "done" + interrupted=True + exit=None + +# ended_at stamped (nobody can poll a dead process), and "done" +# with a null/missing ended_at -> ended_at stamped at load (#1532), +# so the reaper's TTL and duration_ms behave. Both persist via +# _write_meta (as does a faithfully restored interrupted=True). +# No other value is ever rewritten. + + +def _bad_persisted_timestamp(value): + """True when a present timestamp violates its table row. + + Missing/None is valid (the table default applies). A bool is + malformed (bool is an int subclass, so float(True) == 1.0 + would otherwise slip through -- #1513), as are non-numeric + values, non-finite floats (json.loads parses the NaN/Infinity + literals -- #1523), and oversized ints, whose isfinite() + conversion raises OverflowError instead of returning False + (Codex review on PR #1534). + """ + if value is None: + return False + if isinstance(value, bool) or not isinstance(value, (int, float)): + return True + try: + return not math.isfinite(value) + except OverflowError: + return True + + +def _restore_persisted_job(meta, dir_name): + """Validate one parsed meta.json against RESTORE_FIELD_TABLE. + + Returns (job, persist, reason): on success the restored job + dict, whether the restore must be re-persisted via _write_meta + (a transition fired, or interrupted=True was restored), and + None; on a malformed entry, (None, False, the skip reason) -- + the caller prints exactly one stderr line naming the spool + directory and this reason, and leaves the spool untouched. + Behaviour-identical to the per-field guard blocks this + replaces: #1522 (container), #1513/#1523 (timestamps), + #1548/#1554 (id), #1556 (state/interrupted), #1532 (the + ended_at transitions), #1568 (exit/cwd/cmd, folded in as + table rows). + """ + if not isinstance(meta, dict): + return None, False, "meta.json is not a JSON object" + _bad_fields = [name for name in ("started_at", "ended_at") + if _bad_persisted_timestamp(meta.get(name))] + if _bad_fields: + return None, False, f"bad {'/'.join(_bad_fields)} in meta.json" + _raw_id = meta.get("id") + if _raw_id is not None and not isinstance(_raw_id, str): + return None, False, "non-string id in meta.json" + job_id = _raw_id or dir_name + if (job_id != dir_name or job_id in (".", "..") + or "/" in job_id or "\\" in job_id): + return None, False, "invalid id in meta.json" + try: + job_dir(job_id) + except (OSError, RuntimeError, ValueError): + return None, False, "unsafe spool directory" + _raw_state = meta.get("state") + if _raw_state is not None and _raw_state not in ("running", "done"): + return None, False, "invalid state in meta.json" + _raw_interrupted = meta.get("interrupted") + if (_raw_interrupted is not None + and not isinstance(_raw_interrupted, bool)): + return None, False, "non-boolean interrupted in meta.json" + # Issue #1568, folded in as table rows per the fold-in rule at + # the table above: _write_meta only ever writes exit as an int + # returncode (negative for signal deaths) or None, and cwd/cmd + # as strings. Present values of any other shape were restored + # and served verbatim -- exit="0"/[0], cwd=123 and cmd={"x": 1} + # all reached job_public/job_summary and were re-persisted by + # _write_meta. Same skip contract as every other guarded + # field. bool is rejected for exit explicitly: it is an int + # subclass, but the writer never produces one. Missing/None + # keeps the established defaults (None / home / ""). + _raw_exit = meta.get("exit") + if (_raw_exit is not None + and (isinstance(_raw_exit, bool) + or not isinstance(_raw_exit, int))): + return None, False, "non-integer exit in meta.json" + if (meta.get("cwd") is not None + and not isinstance(meta.get("cwd"), str)): + return None, False, "non-string cwd in meta.json" + if (meta.get("cmd") is not None + and not isinstance(meta.get("cmd"), str)): + return None, False, "non-string cmd in meta.json" + state = _raw_state or "done" + exit_code = meta.get("exit") + ended_at = meta.get("ended_at") + interrupted = bool(_raw_interrupted) + stamped = False + if state == "running": + # The process did not survive the restart: nobody can poll + # it. A finite end time is what lets the reaper apply TTL + # to the restored job's spool; leaving it null retains it + # forever. + state = "done" + exit_code = None + interrupted = True + ended_at = time.time() + elif ended_at is None: + # A restored done job with a null/missing end time (#1532): + # the reaper reads null as "now", so its spool would be + # retained forever, and duration_ms would grow with + # wall-clock time on every poll. Stamp a finite end time + # at load and persist it, so the TTL runs from the stamp + # and duration is stable. + ended_at = time.time() + stamped = True + job = {"id": job_id, "proc": None, + "cwd": meta.get("cwd") or str(Path.home()), + "cmd_repr": meta.get("cmd") or "", + "started_at": float(meta.get("started_at") or 0.0), + "ended_at": ended_at, + "exit": exit_code, "state": state, + "interrupted": interrupted, "_files": ()} + return job, (interrupted or stamped), None + + +def load_persisted_jobs(): + """Rebuild JOBS from the spool directory so job IDs survive restarts. + + The loop does no field logic of its own (design #1578 rule 2): + iterate, skip symlink/non-directory entries as before, parse + JSON, validate through _restore_persisted_job(), then admit + the job or print the one-line skip reason and continue. + """ + try: + base = _jobs_root() + entries = list(base.iterdir()) + except (OSError, RuntimeError, ValueError): + return + for d in entries: + if d.is_symlink(): + print(f"laptop-agent: skipping persisted job {d}: " + "spool directory is a symlink", + file=sys.stderr, flush=True) + continue + if not d.is_dir(): + continue + try: + meta = json.loads((d / "meta.json").read_text()) + except (OSError, ValueError): + continue + job, persist, reason = _restore_persisted_job(meta, d.name) + if job is None: + print(f"laptop-agent: skipping persisted job {d}: " + f"{reason}", + file=sys.stderr, flush=True) + continue + JOBS[job["id"]] = job + if persist: + _write_meta(job) + +def job_state(job): + if job["state"] == "running": + proc = job["proc"] + if proc is not None and proc.poll() is None: + return "running" + job["state"] = "done" + if proc is not None: + job["exit"] = proc.returncode + if job["ended_at"] is None: + job["ended_at"] = time.time() + _write_meta(job) + return job["state"] + + +def job_public(job, out_off=0, err_off=0): + state = job_state(job) + try: + d = job_dir(job["id"]) + except (RuntimeError, ValueError) as e: + # Post-load spool swap (#1575): serve the job's in-memory + # record with empty output instead of raising ValueError, + # which do_GET would turn into a 400 blaming the request. + print(f"laptop-agent: cannot read spool for job " + f"{job['id']}: {e}", file=sys.stderr, flush=True) + d = None + out = b"" + err = b"" + if d is not None: + try: + with open(d / "stdout", "rb") as f: + f.seek(out_off) + out = f.read(MAX_OUT) + except OSError: + pass + try: + with open(d / "stderr", "rb") as f: + f.seek(err_off) + err = f.read(MAX_OUT) + except OSError: + pass + return {"job_id": job["id"], "state": state, + "exit": job["exit"] if state == "done" else None, + "cwd": job["cwd"], "cmd": job["cmd_repr"], + "started_at": job["started_at"], + "interrupted": job.get("interrupted", False), + "duration_ms": int(((job["ended_at"] or time.time()) + - job["started_at"]) * 1000), + "stdout": out.decode("utf-8", "replace"), + "stderr": err.decode("utf-8", "replace"), + "out_next": out_off + len(out), "err_next": err_off + len(err)} + + +def job_summary(job): + """Summary serializer for the GET /jobs list route. + + Returns the documented list shape (docstring above): identity, + state, and spool sizes/cursors only. Unlike job_public it never + reads or embeds stdout/stderr payloads, so polling the list costs + O(jobs), not O(jobs x 2 x MAX_OUT). out_next/err_next are the + spool sizes, i.e. the offsets a client would page from in the + single-job route. + """ + state = job_state(job) + try: + d = job_dir(job["id"]) + except (RuntimeError, ValueError) as e: + # Post-load spool swap (#1575): one poisoned spool must not + # fail the whole GET /jobs list -- report zero sizes for this + # job (same shape as a missing spool file) and serve the rest. + print(f"laptop-agent: cannot read spool for job " + f"{job['id']}: {e}", file=sys.stderr, flush=True) + d = None + try: + out_size = (d / "stdout").stat().st_size if d else 0 + except OSError: + out_size = 0 + try: + err_size = (d / "stderr").stat().st_size if d else 0 + except OSError: + err_size = 0 + return {"job_id": job["id"], "state": state, + "exit": job["exit"] if state == "done" else None, + "cwd": job["cwd"], "cmd": job["cmd_repr"], + "started_at": job["started_at"], + "interrupted": job.get("interrupted", False), + "duration_ms": int(((job["ended_at"] or time.time()) + - job["started_at"]) * 1000), + "out_bytes": out_size, "err_bytes": err_size, + "out_next": out_size, "err_next": err_size} + + +def reap_old_jobs(): + now = time.time() + with JOBS_LOCK: + dead = [] + for j in list(JOBS.values()): + if job_state(j) == "done" and (j["ended_at"] or now) < now - JOB_TTL_S: + dead.append(j) + for j in dead: + JOBS.pop(j["id"], None) + for j in dead: + # Output is uncapped, so retention must remove the spool too. + # job_dir() raises ValueError for an unsafe spool (#1555) and + # ignore_errors covers only rmtree's own errors, so guard each + # job: one unsafe spool must not abort the whole reap (#1560). + # The dead jobs are already popped from JOBS, so a spool that + # cannot be removed is log-and-drop -- one stderr line naming + # the job -- and the reap continues with the remaining jobs; + # without the line the leak would be silent and permanent, + # because no later reap pass still knows these jobs. + try: + shutil.rmtree(job_dir(j["id"]), ignore_errors=True) + except (OSError, RuntimeError, ValueError) as e: + print(f"laptop-agent: reap: cannot remove spool for job " + f"{j['id']}: {e}", file=sys.stderr, flush=True) + + +class FramingError(ValueError): + """Invalid request framing: the next request boundary is unknown, + so the connection must be closed after the 400 response.""" + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # quiet; journal gets tracebacks only + pass + + def _send(self, code, obj, close=False): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + if close: + self.send_header("Connection", "close") + self.close_connection = True + self.end_headers() + self.wfile.write(body) + + def _send_bytes(self, code, data, extra_headers=None): + self.send_response(code) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(len(data))) + for k, v in (extra_headers or {}).items(): + self.send_header(k, str(v)) + self.end_headers() + self.wfile.write(data) + + def _authed(self): + given = self.headers.get("X-Agent-Token") or "" + if not given: + return False + # Compare in bytes space (#1741): hmac.compare_digest on str + # raises TypeError for non-ASCII operands, which the request + # handlers turned into a 400 leaking the exception message -- + # and a non-ASCII token file produced a daemon that could + # never authenticate. http.server decodes header bytes as + # latin-1, so try both the utf-8 encoding of the decoded + # string (a latin-1 sender of the token's characters) and the + # raw wire bytes it recovers (a utf-8 sender). + expected = TOKEN.encode("utf-8") + candidates = {given.encode("utf-8")} + try: + candidates.add(given.encode("latin-1")) + except UnicodeEncodeError: + pass + return any(hmac.compare_digest(c, expected) for c in candidates) + + def _client_gone(self): + """True once the client connection has died (EOF/error). + + ThreadingHTTPServer handlers never poll the socket while a + /exec runs, so a client killed by an outer `timeout` used to + leave its command running to the daemon-side cap — or longer, + for grandchildren. Closing the write side makes the peer see + FIN at once; the handler thread then re-checks between drain + slices. Used as run_one's disconnect watchdog trigger.""" + try: + self.connection.setblocking(False) + try: + data = self.connection.recv(1, socket.MSG_PEEK) + return data == b"" + except BlockingIOError: + return False + except OSError: + return True + finally: + self.connection.setblocking(True) + except OSError: + return True + + def _body(self): + try: + n = int(self.headers.get("Content-Length") or 0) + except (TypeError, ValueError): + raise FramingError("invalid Content-Length header") + if n < 0: + raise FramingError("invalid Content-Length header") + if n > MAX_BODY: + raise FramingError("request body too large") + raw = self.rfile.read(n) if n else b"{}" + try: + body = json.loads(raw or b"{}") + except ValueError: + raise ValueError("request body is not valid JSON") + if not isinstance(body, dict): + raise ValueError("request body must be a JSON object") + return body + + def _send_bad_request(self, e): + try: + self._send(400, {"error": str(e) or "bad request"}, + close=isinstance(e, FramingError)) + except Exception: + pass + + def do_GET(self): + try: + self._do_GET() + except (ValueError, KeyError, TypeError, AttributeError, + IndexError) as e: + self._send_bad_request(e) + except (BrokenPipeError, ConnectionResetError): + pass + + def _do_GET(self): + if not self._authed(): + return self._send(401, {"error": "bad token"}) + path = urlparse(self.path) + if path.path == "/health": + with JOBS_LOCK: + n = len(JOBS) + return self._send(200, {"ok": True, + "uptime_s": int(time.time() - STARTED), + "jobs": n, "load1": os.getloadavg()[0]}) + if path.path == "/file": + q = parse_qs(path.query) + fpath = (q.get("path") or [""])[0] + if not fpath: + return self._send(400, {"error": "path required"}) + try: + off = int((q.get("off") or ["0"])[0]) + length = int((q.get("len") or [str(FILE_CHUNK_MAX)])[0]) + except ValueError: + return self._send(400, {"error": "off/len must be ints"}) + if off < 0 or length <= 0: + return self._send(400, {"error": "off>=0, len>=1 required"}) + length = min(length, FILE_CHUNK_MAX) + try: + size = os.path.getsize(fpath) + if not os.path.isfile(fpath): + raise OSError("not a regular file") + except OSError as e: + return self._send(404, {"error": f"no such file: {e}"}) + if off > size: + return self._send(416, {"error": "off beyond end of file", + "size": size}) + with open(fpath, "rb") as fh: + fh.seek(off) + data = fh.read(length) + return self._send_bytes(200, data, {"X-File-Size": size, + "X-File-Off": off}) + if path.path == "/jobs": + with JOBS_LOCK: + items = [job_summary(j) for j in JOBS.values()] + return self._send(200, {"jobs": items}) + if path.path.startswith("/jobs/"): + job_id = path.path.split("/")[2] + q = parse_qs(path.query) + with JOBS_LOCK: + job = JOBS.get(job_id) + if job is None: + return self._send(404, {"error": "no such job"}) + try: + out_off = int(q.get("out_off", [0])[0]) + err_off = int(q.get("err_off", [0])[0]) + except (TypeError, ValueError): + raise ValueError("out_off/err_off must be integers") + if out_off < 0 or err_off < 0: + raise ValueError("out_off/err_off must be >= 0") + return self._send(200, job_public(job, out_off, err_off)) + return self._send(404, {"error": "no such route"}) + + def do_POST(self): + try: + self._do_POST() + except (ValueError, KeyError, TypeError, AttributeError, + IndexError) as e: + self._send_bad_request(e) + except (BrokenPipeError, ConnectionResetError): + pass + + def _do_POST(self): + # Trip v2 (code#5702): stamp reception at request entry; the + # value is echoed to the client as the internal _t_received + # response field (stripped client-side) and logged daemon-side. + t_received_ms = int(time.time() * 1000) + if not self._authed(): + return self._send(401, {"error": "bad token"}) + path = urlparse(self.path).path + if path == "/exec": + body = self._body() + trip = self.headers.get("X-Trip-Id") or body.get("trip") + if not isinstance(trip, str) or not trip: + trip = secrets.token_hex(6) + try: + timeout = int(body.get("timeout_s", EXEC_TIMEOUT_DEFAULT)) + except (TypeError, ValueError, OverflowError): + return self._send(400, + {"error": "timeout_s must be an integer"}) + timeout = max(1, min(timeout, EXEC_TIMEOUT_MAX)) + cmds = body.get("cmds") or [] + if not isinstance(cmds, list) or not cmds: + return self._send(400, {"error": "cmds required"}) + for c in cmds: + if not isinstance(c, dict) or ( + c.get("shell") is None and not ( + isinstance(c.get("argv"), (list, tuple)) + and c["argv"])): + return self._send( + 400, {"error": "each cmd requires 'argv' or 'shell'"}) + if (c.get("env") is not None + and not isinstance(c.get("env"), dict)): + return self._send( + 400, {"error": "cmd env must be an object"}) + if not SEMA.acquire(timeout=5): + return self._send(503, {"error": "busy"}) + cancel_event = threading.Event() + + def watch_disconnect(ev=cancel_event): + # Poll the socket at 4 Hz while the exec runs; a dead + # client connection kills the trip's process groups + # so no orphan work survives a caller-side timeout. + while not ev.is_set(): + if self._client_gone(): + ev.set() + with EXEC_PROCS_LOCK: + procs = list(EXEC_PROCS.get(trip, ())) + for p in procs: + if p.poll() is None: + kill_group(p) + return + ev.wait(0.25) + + watcher = threading.Thread(target=watch_disconnect, + daemon=True) + watcher.start() + try: + results = [run_one(c, timeout, trip=trip, + cancel_event=cancel_event) + for c in cmds] + finally: + cancel_event.set() + watcher.join(timeout=1) + SEMA.release() + for r in results: + cmd_str = r.pop("_cmd", "") + out_b = r.pop("_out_bytes", 0) + err_b = r.pop("_err_bytes", 0) + log_trip(trip, "exec", cmd_str, r.get("duration_ms"), + r.get("exit"), out_b, err_b, + t_received=t_received_ms) + try: + return self._send(200, {"results": results, + "_t_received": t_received_ms}) + except (BrokenPipeError, ConnectionResetError): + pass # client already gone; the work is done/killed + return + if path == "/cancel" or (path.startswith("/exec/") + and path.endswith("/cancel")): + body = self._body() + trip = (body.get("trip") or self.headers.get("X-Trip-Id") + or (path.split("/")[2] + if path.startswith("/exec/") else None)) + if not isinstance(trip, str) or not trip: + return self._send(400, {"error": "trip required"}) + with EXEC_PROCS_LOCK: + procs = list(EXEC_PROCS.get(trip, ())) + killed = 0 + for p in procs: + if p.poll() is None: + kill_group(p) + killed += 1 + return self._send(200, {"ok": True, "cancelled": killed}) + if path == "/jobs": + body = self._body() + trip = self.headers.get("X-Trip-Id") or body.get("trip") + if not isinstance(trip, str) or not trip: + trip = secrets.token_hex(6) + cwd = body.get("cwd") or str(Path.home()) + if body.get("env") is not None and not isinstance( + body.get("env"), dict): + return self._send(400, {"error": "env must be an object"}) + if body.get("shell") is not None: + argv = [BASH, "-lc", body["shell"]] + cmd_repr = body["shell"] + elif isinstance(body.get("argv"), (list, tuple)) and body["argv"]: + argv = list(body["argv"]) + cmd_repr = " ".join(str(a) for a in argv) + else: + return self._send(400, {"error": "argv or shell required"}) + if not SEMA.acquire(timeout=5): + return self._send(503, {"error": "busy"}) + job_id = d = None + out_f = err_f = proc = None + watch_thread = None + watch_started = False + try: + job_id = secrets.token_hex(6) + d = job_dir(job_id) + d.mkdir(parents=True, exist_ok=True) + env = dict(os.environ) + env.update(body.get("env") or {}) + out_f = open(d / "stdout", "wb") + err_f = open(d / "stderr", "wb") + proc = subprocess.Popen(argv, cwd=cwd, env=env, + stdout=out_f, stderr=err_f, + start_new_session=True) + job = {"id": job_id, "proc": proc, "cwd": cwd, + "cmd_repr": cmd_repr, "started_at": time.time(), + "ended_at": None, "exit": None, "state": "running", + "interrupted": False, "_files": (out_f, err_f), + "trip": trip, "t_received": t_received_ms} + _write_meta(job) + with JOBS_LOCK: + JOBS[job_id] = job + + def watch(j=job): + try: + j["proc"].wait() + finally: + SEMA.release() + j["ended_at"] = time.time() + for f in j["_files"]: + try: + f.close() + except OSError: + pass + job_state(j) + try: + d = job_dir(j["id"]) + out_b = (d / "stdout").stat().st_size + err_b = (d / "stderr").stat().st_size + except (OSError, RuntimeError, ValueError): + out_b = err_b = 0 + log_trip(j["trip"], "job", j["cmd_repr"], + int((j["ended_at"] - j["started_at"]) * 1000), + j["proc"].returncode, out_b, err_b, + t_received=j.get("t_received")) + + watch_thread = threading.Thread(target=watch, daemon=True) + watch_thread.start() + watch_started = True + except Exception as e: + # Thread.start() can raise after the new thread has begun. + # In that case its finally block owns the acquired slot. + if watch_thread is not None and watch_thread.ident is not None: + watch_started = True + if not watch_started: + try: + if proc is not None: + try: + proc.kill() + proc.wait(timeout=5) + except (OSError, subprocess.TimeoutExpired): + pass + with JOBS_LOCK: + JOBS.pop(job_id, None) + for f in (out_f, err_f): + if f is not None: + try: + f.close() + except OSError: + pass + if d is not None: + shutil.rmtree(d, ignore_errors=True) + except Exception: + pass + finally: + SEMA.release() + return self._send(400, {"error": f"{type(e).__name__}: {e}"}) + reap_old_jobs() + return self._send(200, {"job_id": job_id, + "_t_received": t_received_ms}) + if path.startswith("/jobs/") and path.endswith("/kill"): + job_id = path.split("/")[2] + with JOBS_LOCK: + job = JOBS.get(job_id) + if job is None: + return self._send(404, {"error": "no such job"}) + if job_state(job) == "running" and job["proc"] is not None: + pid = job["proc"].pid + _kill_group(pid, signal.SIGTERM) + + def hard_kill(p=pid): + deadline = time.time() + KILL_GRACE_S + while time.time() < deadline: + if not _group_alive(p): + return + time.sleep(0.1) + if _group_alive(p): + _kill_group(p, signal.SIGKILL) + threading.Thread(target=hard_kill, daemon=True).start() + return self._send(200, {"ok": True, "job_id": job_id}) + return self._send(404, {"error": "no such route"}) + + +def _reaper_loop(): + """Reap on a timer so the TTL fires without a new job (#1504). + + reap_old_jobs() used to run only from the POST /jobs path, so a + daemon serving only /exec + /health + job polls never reaped and + finished jobs' uncapped spool dirs accumulated forever. + """ + while True: + time.sleep(REAP_INTERVAL_S) + try: + reap_old_jobs() + except Exception as e: # a reaper fault must not kill the daemon + print(f"laptop-agent: background reap failed: {e}", + file=sys.stderr, flush=True) + + +def main(): + (STATE_DIR / "jobs").mkdir(parents=True, exist_ok=True) + (STATE_DIR / "exec").mkdir(parents=True, exist_ok=True) + load_persisted_jobs() + reap_old_jobs() + threading.Thread(target=_reaper_loop, daemon=True).start() + srv = ThreadingHTTPServer((BIND_HOST, BIND_PORT), Handler) + print(f"laptop-agent listening on {BIND_HOST}:{BIND_PORT}", flush=True) + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/pkgs/laptop-agent/tests/parity_roundtrip.py b/pkgs/laptop-agent/tests/parity_roundtrip.py new file mode 100644 index 0000000000..0467966696 --- /dev/null +++ b/pkgs/laptop-agent/tests/parity_roundtrip.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Client-protocol parity round-trip for the reconciled daemon (#10131). +Drives the union daemon on a scratch port/state dir with the exact wire +shapes the real client (~/tools/laptop-agent.py) uses.""" +import json +import os +import subprocess +import sys +import threading +import time +import urllib.request +import urllib.error +from pathlib import Path + +DAEMON = Path(__file__).resolve().parents[1] / "src" / "laptop_agent.py" + +BASE = "http://127.0.0.1:4798" +TOKEN = "parity-token-123" +STATE = "/tmp/parity-state" +FAILS = [] +# The laptop shell exports proxy vars; loopback must not go through them. +OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + +def call(method, path, body=None, headers=None, raw=None, timeout=30): + data = raw + if body is not None: + data = json.dumps(body).encode() + req = urllib.request.Request(BASE + path, data=data, method=method) + req.add_header("X-Agent-Token", TOKEN) + if body is not None: + req.add_header("Content-Type", "application/json") + for k, v in (headers or {}).items(): + req.add_header(k, v) + try: + with OPENER.open(req, timeout=timeout) as r: + return r.status, dict(r.headers), r.read() + except urllib.error.HTTPError as e: + return e.code, dict(e.headers), e.read() + +def jcall(method, path, body=None, **kw): + st, hd, raw = call(method, path, body=body, **kw) + return st, json.loads(raw) if raw else {} + +def check(name, cond, extra=""): + print(("PASS " if cond else "FAIL ") + name + (f" [{extra}]" if extra else "")) + if not cond: + FAILS.append(name) + +def start_daemon(): + env = dict(os.environ, + LAPTOP_AGENT_STATE=STATE, + LAPTOP_AGENT_TOKEN_FILE="/tmp/parity-token", + LAPTOP_AGENT_PORT="4798", + LAPTOP_AGENT_HOST="127.0.0.1") + logf = open("/tmp/parity-daemon.log", "ab") + p = subprocess.Popen( + [sys.executable, str(DAEMON)], + env=env, stdout=logf, stderr=subprocess.STDOUT) + for _ in range(75): + if p.poll() is not None: + raise RuntimeError(f"daemon exited early rc={p.returncode}; " + "see /tmp/parity-daemon.log") + try: + st, _h, _r = call("GET", "/health", timeout=2) + if st == 200: + return p + except Exception: + pass + time.sleep(0.2) + raise RuntimeError("daemon did not come up; see /tmp/parity-daemon.log") + +def main(): + subprocess.run(["rm", "-rf", STATE], check=True) + with open("/tmp/parity-token", "w") as f: + f.write(TOKEN + "\n") + with open("/tmp/parity-file.txt", "wb") as f: + f.write(bytes(range(100))) + d = start_daemon() + try: + st, b = jcall("GET", "/health") + check("health", st == 200 and b.get("ok") is True) + st, _ = jcall("GET", "/health", headers={}) + # (auth header always added by call(); do a raw unauth check) + req = urllib.request.Request(BASE + "/health", method="GET") + try: + OPENER.open(req, timeout=5) + check("unauth 401", False) + except urllib.error.HTTPError as e: + check("unauth 401", e.code == 401) + + st, b = jcall("POST", "/exec", + {"cmds": [{"argv": ["echo", "hello-union"]}, + {"shell": "echo shell-$((6*7))"}], + "timeout_s": 10}) + rs = b.get("results", []) + check("exec argv+shell", + st == 200 and len(rs) == 2 + and rs[0]["stdout"].strip() == "hello-union" + and rs[1]["stdout"].strip() == "shell-42" + and "_t_received" in b) + + st, b = jcall("POST", "/exec", + {"cmds": [{"argv": ["sleep", "311"]}], + "timeout_s": 1}) + r = b["results"][0] + check("exec timeout kills", r.get("timeout") is True, + f"dur={r.get('duration_ms')}") + time.sleep(0.5) + ps = subprocess.run(["pgrep", "-f", "sleep 311"], + capture_output=True, text=True).stdout.strip() + check("no orphan after timeout", ps == "", f"pgrep={ps!r}") + + holder = {} + def long_exec(): + holder["r"] = jcall("POST", "/exec", + {"cmds": [{"argv": ["sleep", "312"]}], + "timeout_s": 60}, + headers={"X-Trip-Id": "parity-trip-1"}, + timeout=70) + t = threading.Thread(target=long_exec) + t.start() + time.sleep(1.0) + st, b = jcall("POST", "/exec/parity-trip-1/cancel", {}) + check("cancel accepted", st == 200 and b.get("cancelled", 0) >= 1, + str(b)) + t.join(timeout=15) + r = holder["r"][1]["results"][0] + # Live contract: /cancel kills via the trip's proc registry, so + # the exec returns promptly, killed — the cancelled flag is set + # only on the disconnect-watchdog path. + check("exec cancelled result", + r.get("duration_ms", 999999) < 15000 + and r.get("exit") in (None, -15, -9), + f"dur={r.get('duration_ms')} exit={r.get('exit')}") + + st, b = jcall("POST", "/exec", {"cmds": [{"nope": 1}]}) + check("bad cmd 400", st == 400, str(st)) + st, b = jcall("POST", "/exec", + {"cmds": [{"argv": ["true"]}], "timeout_s": "x"}) + check("bad timeout 400", st == 400, str(st)) + st, hd, raw = call("POST", "/exec", raw=b"{not json") + check("malformed json 400", st == 400 + and json.loads(raw).get("error"), str(st)) + + st, b = jcall("POST", "/jobs", + {"shell": "echo job-out; sleep 2"}) + jid = b.get("job_id") + check("job created", st == 200 and bool(jid) + and "_t_received" in b) + done = None + for _ in range(40): + st, jb = jcall("GET", f"/jobs/{jid}") + if jb.get("state") == "done": + done = jb + break + time.sleep(0.5) + check("job completes with output", + done is not None and done.get("exit") == 0 + and "job-out" in done.get("stdout", ""), str(done)[:120]) + + st, b = jcall("POST", "/jobs", {"argv": ["sleep", "313"]}) + jid2 = b["job_id"] + st, b = jcall("GET", "/jobs") + summ = [x for x in b.get("jobs", []) if x["job_id"] == jid2] + check("jobs list summary shape", + bool(summ) and "stdout" not in summ[0] + and summ[0]["state"] == "running") + st, b = jcall("POST", f"/jobs/{jid2}/kill", {}) + check("job kill", st == 200 and b.get("ok") is True) + for _ in range(20): + st, jb = jcall("GET", f"/jobs/{jid2}") + if jb.get("state") == "done": + break + time.sleep(0.5) + check("killed job done", jb.get("state") == "done") + + st, hd, raw = call("GET", "/file?path=/tmp/parity-file.txt&off=10&len=5") + check("file range", + st == 200 and raw == bytes(range(10, 15)) + and hd.get("X-File-Size") == "100", f"{st} {raw!r}") + + # Restart persistence: running job becomes done+interrupted; + # finished job stays pollable. + st, b = jcall("POST", "/jobs", {"argv": ["sleep", "314"]}) + jid3 = b["job_id"] + time.sleep(0.5) + finally: + d.terminate() + d.wait(timeout=10) + d2 = start_daemon() + try: + st, jb = jcall("GET", f"/jobs/{jid3}") + check("restart: running job interrupted", + jb.get("state") == "done" and jb.get("interrupted") is True, + str({k: jb.get(k) for k in ("state", "interrupted")})) + st, jb = jcall("GET", f"/jobs/{jid}") + check("restart: finished job pollable", + jb.get("state") == "done" and jb.get("exit") == 0 + and "job-out" in jb.get("stdout", ""), str(jb)[:120]) + trips = open(os.path.join(STATE, "trips.jsonl")).read() + kinds = [json.loads(ln)["kind"] for ln in trips.splitlines() + if ln.strip()] + check("trips.jsonl has exec+job records", + "exec" in kinds and "job" in kinds, str(kinds)) + # Cleanup: the interrupted job's sleep outlived the first + # daemon (daemon SIGTERM does not reap job groups); kill any + # straggler sleeps from this test's unique durations. + for dur in ("311", "312", "313", "314"): + subprocess.run(["pkill", "-f", f"sleep {dur}"], + capture_output=True) + finally: + d2.terminate() + d2.wait(timeout=10) + print("RESULT:", "ALL PASS" if not FAILS else f"FAILURES: {FAILS}") + return 1 if FAILS else 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pkgs/laptop-agent/tests/test_laptop_agent.py b/pkgs/laptop-agent/tests/test_laptop_agent.py new file mode 100644 index 0000000000..24d32db36c --- /dev/null +++ b/pkgs/laptop-agent/tests/test_laptop_agent.py @@ -0,0 +1,1965 @@ +#!/usr/bin/env python3 +"""Tests for laptop-agent startup auth and bounded output capture. + +Run with: python3 -m unittest discover -s pkgs/laptop-agent/tests +Wired as the flake check `laptop-agent-tests` (Linux). +""" +import contextlib +import http.client +import io +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest.mock import patch + +AGENT = Path(__file__).resolve().parents[1] / "src" / "laptop_agent.py" + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class EmptyTokenTest(unittest.TestCase): + """PR #1459 codex P1: an empty/whitespace token must fail closed.""" + + def _run_with_token(self, text): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write(text) + token = f.name + try: + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(free_port()), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + return subprocess.run([sys.executable, str(AGENT)], env=env, + capture_output=True, text=True, timeout=20) + finally: + os.unlink(token) + + def test_empty_token_refuses_to_start(self): + p = self._run_with_token("") + self.assertEqual(p.returncode, 3, p.stderr) + self.assertIn("refusing to start", p.stderr) + + def test_whitespace_token_refuses_to_start(self): + p = self._run_with_token(" \n\t\n") + self.assertEqual(p.returncode, 3, p.stderr) + + def test_missing_token_file_refuses_to_start(self): + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE="/nonexistent/token", + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(free_port()), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + p = subprocess.run([sys.executable, str(AGENT)], env=env, + capture_output=True, text=True, timeout=20) + self.assertEqual(p.returncode, 3, p.stderr) + + +class StartupEnvValidationTest(unittest.TestCase): + """#1510: invalid PORT/SLOTS must exit 3 naming var+value, no traceback.""" + + def _run_with_env(self, extra): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("test-token\n") + token = f.name + try: + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(free_port()), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + env.update(extra) + return subprocess.run([sys.executable, str(AGENT)], env=env, + capture_output=True, text=True, timeout=20) + finally: + os.unlink(token) + + def test_invalid_port_refuses_to_start(self): + for value in ("abc", "0", "99999", "-1"): + with self.subTest(LAPTOP_AGENT_PORT=value): + p = self._run_with_env({"LAPTOP_AGENT_PORT": value}) + self.assertEqual(p.returncode, 3, p.stderr) + self.assertIn("invalid LAPTOP_AGENT_PORT=", p.stderr) + self.assertIn(repr(value), p.stderr) + self.assertNotIn("Traceback", p.stderr) + + def test_invalid_slots_refuses_to_start(self): + for value in ("abc", "0", "-1"): + with self.subTest(LAPTOP_AGENT_SLOTS=value): + p = self._run_with_env({"LAPTOP_AGENT_SLOTS": value}) + self.assertEqual(p.returncode, 3, p.stderr) + self.assertIn("invalid LAPTOP_AGENT_SLOTS=", p.stderr) + self.assertIn(repr(value), p.stderr) + self.assertNotIn("Traceback", p.stderr) + + +class AuthHeaderTest(unittest.TestCase): + """A request without the header must be rejected, not treated as "".""" + + def test_missing_header_rejected(self): + token = "s" * 32 + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(token + "\n") + token_path = f.name + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.time() + 10 + while time.time() < deadline: + try: + urllib.request.urlopen( + f"http://127.0.0.1:{port}/health", timeout=1) + except urllib.error.HTTPError as e: + self.assertEqual(e.code, 401) + break + except (urllib.error.URLError, ConnectionError): + time.sleep(0.1) + else: + self.fail("agent did not start") + req = urllib.request.Request( + f"http://127.0.0.1:{port}/health", + headers={"X-Agent-Token": token}) + with urllib.request.urlopen(req, timeout=5) as r: + self.assertEqual(r.status, 200) + self.assertTrue(json.loads(r.read())["ok"]) + finally: + proc.terminate() + proc.wait(timeout=10) + os.unlink(token_path) + + +class AuthNonAsciiTest(unittest.TestCase): + """#1741: non-ASCII tokens must not crash the auth comparison. + + hmac.compare_digest on str raises TypeError for non-ASCII + operands, which used to surface as a 400 leaking the exception + message, and a non-ASCII token file produced a daemon that could + never authenticate. The comparison is done on bytes: a presented + non-ASCII token gets the uniform 401, and the correct non-ASCII + token authenticates end to end. + """ + + def _start_agent(self, token_text): + f = tempfile.NamedTemporaryFile("w", encoding="utf-8", + delete=False) + f.write(token_text + "\n") + f.close() + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=f.name, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.addCleanup(os.unlink, f.name) + self.addCleanup(proc.kill) + deadline = time.time() + 10 + while time.time() < deadline: + if proc.poll() is not None: + self.fail(f"agent exited early: {proc.stderr.read()}") + try: + self._raw_health(port, None) + return proc, port + except (ConnectionError, OSError): + time.sleep(0.1) + self.fail("agent did not start") + + def _raw_health(self, port, token_bytes): + with socket.create_connection(("127.0.0.1", port), + timeout=5) as sock: + lines = [b"GET /health HTTP/1.1", b"Host: 127.0.0.1", + b"Connection: close"] + if token_bytes is not None: + lines.append(b"X-Agent-Token: " + token_bytes) + sock.sendall(b"\r\n".join(lines) + b"\r\n\r\n") + chunks = [] + while True: + data = sock.recv(4096) + if not data: + break + chunks.append(data) + head, _, body = b"".join(chunks).partition(b"\r\n\r\n") + return int(head.split(b" ")[1]), body + + def test_non_ascii_header_gets_uniform_401(self): + _, port = self._start_agent("s" * 32) + wrong_status, wrong_body = self._raw_health(port, b"wrong-token") + self.assertEqual(wrong_status, 401) + self.assertEqual(json.loads(wrong_body), {"error": "bad token"}) + for enc in ("utf-8", "latin-1"): + status, body = self._raw_health( + port, "caf\u00e9-token".encode(enc)) + self.assertEqual(status, 401, enc) + self.assertEqual(json.loads(body), {"error": "bad token"}, enc) + self.assertNotIn(b"TypeError", body) + + def test_non_ascii_token_file_authenticates(self): + token = "t\u00f6k\u00e9n-token-0123456789" + _, port = self._start_agent(token) + for enc in ("utf-8", "latin-1"): + status, body = self._raw_health(port, token.encode(enc)) + self.assertEqual(status, 200, enc) + self.assertTrue(json.loads(body)["ok"], enc) + status, body = self._raw_health(port, b"ascii-wrong-token") + self.assertEqual(status, 401) + self.assertEqual(json.loads(body), {"error": "bad token"}) + + +class TailFileTest(unittest.TestCase): + def test_job_public_samples_state_before_reading_spools(self): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("tail-test-token\n") + token_path = f.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + + with tempfile.TemporaryDirectory() as state_dir: + with patch.object(la, "STATE_DIR", Path(state_dir)): + job_id = "job-public-race" + spool = la.job_dir(job_id) + spool.mkdir(parents=True) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + job = {"id": job_id, "state": "running", "proc": None, + "exit": None, "cwd": "/", "cmd_repr": "test", + "started_at": time.time(), "ended_at": None, + "interrupted": False} + + def finish_job(current): + (spool / "stdout").write_bytes(b"final output") + current["state"] = "done" + current["exit"] = 0 + current["ended_at"] = time.time() + return "done" + + with patch.object(la, "job_state", side_effect=finish_job) as state: + result = la.job_public(job) + + state.assert_called_once_with(job) + self.assertEqual(result["state"], "done") + self.assertEqual(result["stdout"], "final output") + + def test_tail_caps_and_flags(self): + with tempfile.NamedTemporaryFile("w", delete=False) as t: + t.write("tail-test-token\n") + token_path = t.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + with tempfile.NamedTemporaryFile(delete=False) as f: + f.write(b"x" * 100 + b"END") + path = Path(f.name) + try: + data, cut = la.tail_file(path, 10) + self.assertEqual(data, b"xxxxxxxEND") + self.assertTrue(cut) + data, cut = la.tail_file(path, 1000) + self.assertEqual(len(data), 103) + self.assertFalse(cut) + finally: + os.unlink(path) + + + +class JobsListShapeTest(unittest.TestCase): + """Issue #1503: GET /jobs is a summary; output lives on /jobs/. + + Oracle: the module docstring's documented shapes -- the list route + documents {job_id, state, exit, ...} with no output fields, while + the single-job route documents stdout/stderr plus paging cursors. + """ + + def _import_agent(self): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("jobs-list-test-token\n") + token_path = f.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + return la + + def test_summary_has_no_output_but_single_job_shape_does(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + with patch.object(la, "STATE_DIR", Path(state_dir)): + job_id = "job-list-shape" + spool = la.job_dir(job_id) + spool.mkdir(parents=True) + (spool / "stdout").write_bytes(b"known stdout payload") + (spool / "stderr").write_bytes(b"known stderr payload") + job = {"id": job_id, "state": "done", "proc": None, + "exit": 0, "cwd": "/", "cmd_repr": "test", + "started_at": time.time(), "ended_at": time.time(), + "interrupted": False} + summary = la.job_summary(job) + full = la.job_public(job) + for key in ("job_id", "state", "exit", "cwd", "cmd", + "started_at", "duration_ms", "interrupted", + "out_next", "err_next"): + self.assertIn(key, summary) + self.assertNotIn("stdout", summary) + self.assertNotIn("stderr", summary) + self.assertNotIn("known stdout payload", json.dumps(summary)) + self.assertNotIn("known stderr payload", json.dumps(summary)) + self.assertEqual(summary["out_next"], len(b"known stdout payload")) + self.assertEqual(summary["err_next"], len(b"known stderr payload")) + self.assertEqual(full["stdout"], "known stdout payload") + self.assertEqual(full["stderr"], "known stderr payload") + + def test_list_route_returns_summary_single_route_returns_output(self): + token = "jobs-list-http-token" + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(token + "\n") + token_path = f.name + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + headers = {"X-Agent-Token": token, + "Content-Type": "application/json"} + + def call(method, path, body=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", data=data, + headers=headers, method=method) + with urllib.request.urlopen(req, timeout=5) as r: + return json.loads(r.read()) + + try: + deadline = time.time() + 10 + while True: + try: + if call("GET", "/health")["ok"]: + break + except Exception: + if time.time() > deadline: + raise + time.sleep(0.1) + job_id = call("POST", "/jobs", { + "cwd": "/", + "argv": [sys.executable, "-c", + "import sys; sys.stdout.write('k' * 64); " + "sys.stderr.write('e' * 64)"]})["job_id"] + deadline = time.time() + 10 + single = None + while time.time() < deadline: + single = call("GET", f"/jobs/{job_id}") + if single["state"] == "done": + break + time.sleep(0.1) + self.assertEqual(single["state"], "done") + self.assertEqual(single["stdout"], "k" * 64) + self.assertEqual(single["stderr"], "e" * 64) + listing = call("GET", "/jobs") + entry = [j for j in listing["jobs"] if j["job_id"] == job_id] + self.assertEqual(len(entry), 1) + self.assertNotIn("stdout", entry[0]) + self.assertNotIn("stderr", entry[0]) + self.assertNotIn("k" * 64, json.dumps(entry[0])) + self.assertNotIn("e" * 64, json.dumps(entry[0])) + self.assertEqual(entry[0]["out_next"], 64) + self.assertEqual(entry[0]["err_next"], 64) + finally: + proc.terminate() + proc.wait(timeout=10) + os.unlink(token_path) + + + +class JobSlotsTest(unittest.TestCase): + """Issue #1545: POST /jobs shares the LAPTOP_AGENT_SLOTS pool. + + Oracle: with SLOTS=1 and one long-running job held, a second + POST /jobs gets 503 busy (after the bounded 5s wait, like /exec) + instead of running concurrently, /exec is likewise busy (shared + pool), and once the held job ends its slot is released so a new + job is accepted again. + """ + + def test_second_job_rejected_while_slot_held_then_accepted(self): + token = "jobs-slots-test-token" + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(token + "\n") + token_path = f.name + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_SLOTS="1", + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + headers = {"X-Agent-Token": token, + "Content-Type": "application/json"} + + def call(method, path, body=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", data=data, + headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=20) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read()) + + try: + deadline = time.time() + 10 + while True: + try: + status, body = call("GET", "/health") + if status == 200 and body["ok"]: + break + except Exception: + if time.time() > deadline: + raise + time.sleep(0.1) + status, body = call("POST", "/jobs", { + "cwd": "/", + "argv": [sys.executable, "-c", + "import time; time.sleep(30)"]}) + self.assertEqual(status, 200, body) + job_id = body["job_id"] + # The single slot is held for the job's lifetime: a second + # job must not run concurrently. + status, body = call("POST", "/jobs", { + "cwd": "/", "argv": [sys.executable, "-c", "pass"]}) + self.assertEqual(status, 503, body) + self.assertEqual(body.get("error"), "busy") + listing_status, listing = call("GET", "/jobs") + self.assertEqual(listing_status, 200, listing) + running = [j for j in listing["jobs"] + if j["state"] == "running"] + self.assertEqual([j["job_id"] for j in running], [job_id]) + # Shared pool: /exec is busy too while the job holds the slot. + status, body = call("POST", "/exec", { + "cmds": [{"argv": [sys.executable, "-c", "pass"]}]}) + self.assertEqual(status, 503, body) + # Killing the held job releases the slot for new work. + status, body = call("POST", f"/jobs/{job_id}/kill") + self.assertEqual(status, 200, body) + deadline = time.time() + 15 + while time.time() < deadline: + status, body = call("POST", "/jobs", { + "cwd": "/", "argv": [sys.executable, "-c", "pass"]}) + if status == 200: + break + time.sleep(0.2) + self.assertEqual(status, 200, body) + finally: + proc.terminate() + proc.wait(timeout=10) + os.unlink(token_path) + + def test_spool_creation_failure_returns_400_and_releases_slot(self): + token = "jobs-spool-failure-test-token" + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(token + "\n") + token_path = f.name + state_dir = tempfile.mkdtemp() + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_SLOTS="1", + LAPTOP_AGENT_STATE=state_dir) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + headers = {"X-Agent-Token": token, + "Content-Type": "application/json"} + + def call(method, path, body=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", data=data, + headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=20) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + try: + deadline = time.time() + 10 + while True: + try: + status, body = call("GET", "/health") + if status == 200 and body["ok"]: + break + except Exception: + if time.time() > deadline: + raise + time.sleep(0.1) + + # Replace the initialized spool parent after startup. mkdir for + # the job's directory now fails with ENOTDIR, after slot acquire. + jobs_dir = Path(state_dir) / "jobs" + jobs_dir.rmdir() + jobs_dir.write_text("not a directory") + status, body = call("POST", "/jobs", { + "cwd": "/", "argv": [sys.executable, "-c", "pass"]}) + self.assertEqual(status, 400, body) + self.assertIn("error", body) + + jobs_dir.unlink() + jobs_dir.mkdir() + status, body = call("POST", "/jobs", { + "cwd": "/", "argv": [sys.executable, "-c", "pass"]}) + self.assertEqual(status, 200, body) + job_id = body["job_id"] + deadline = time.time() + 10 + while time.time() < deadline: + status, job = call("GET", f"/jobs/{job_id}") + if status == 200 and job.get("state") == "done": + break + time.sleep(0.05) + self.assertEqual(status, 200, job) + self.assertEqual(job.get("state"), "done", job) + + status, body = call("POST", "/exec", { + "cmds": [{"argv": [sys.executable, "-c", "pass"]}]}) + self.assertEqual(status, 200, body) + finally: + proc.terminate() + proc.wait(timeout=10) + proc.stdout.close() + proc.stderr.close() + os.unlink(token_path) + shutil.rmtree(state_dir, ignore_errors=True) + + +class MalformedRequestTest(unittest.TestCase): + """Issue #1502: malformed input returns 400 JSON, never a drop. + + Oracle: for every malformed shape, the response is a well-formed + JSON body carrying an "error" key with status 400, AND a + subsequent authed GET /health on the same daemon returns 200 -- + the invariant is that arbitrary body/query bytes can never kill + the handler or wedge the connection. + """ + + def setUp(self): + self.token = "" + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(self.token + "\n") + self.token_path = f.name + self.port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=self.token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(self.port), + LAPTOP_AGENT_STATE=tempfile.mkdtemp()) + self.proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + deadline = time.time() + 10 + while time.time() < deadline: + try: + status, body = self._call("GET", "/health") + if status == 200 and body.get("ok"): + return + except Exception: + time.sleep(0.1) + self.tearDown() + self.fail("agent did not start") + + def tearDown(self): + self.proc.terminate() + self.proc.wait(timeout=10) + os.unlink(self.token_path) + + def _conn(self): + return http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) + + def _call(self, method, path, body=None, raw=None, conn=None): + c = conn or self._conn() + headers = {"X-Agent-Token": self.token, + "Content-Type": "application/json"} + data = raw if raw is not None else ( + json.dumps(body).encode() if body is not None else None) + c.request(method, path, body=data, headers=headers) + r = c.getresponse() + payload = r.read() + if conn is None: + c.close() + try: + parsed = json.loads(payload) if payload else {} + except ValueError: + parsed = {} + return r.status, parsed + + def _assert_400_then_health(self, method, path, **kw): + status, body = self._call(method, path, **kw) + self.assertEqual(status, 400, body) + self.assertIn("error", body) + status, body = self._call("GET", "/health") + self.assertEqual(status, 200) + self.assertTrue(body["ok"]) + + def test_invalid_json_body(self): + self._assert_400_then_health("POST", "/exec", raw=b"{not json") + + def test_non_object_json_body(self): + self._assert_400_then_health("POST", "/exec", raw=b"[1, 2]") + + def test_bad_content_length_header(self): + conn = self._conn() + conn.putrequest("POST", "/exec") + conn.putheader("X-Agent-Token", self.token) + conn.putheader("Content-Type", "application/json") + conn.putheader("Content-Length", "abc") + conn.endheaders() + r = conn.getresponse() + body = json.loads(r.read()) + self.assertEqual(r.status, 400, body) + self.assertIn("error", body) + status, body = self._call("GET", "/health") + self.assertEqual(status, 200) + self.assertTrue(body["ok"]) + + def test_bad_content_length_with_body_closes_connection(self): + # Codex P2 on PR #1508: unread body bytes after a framing 400 + # would otherwise be parsed as the next request. Oracle: the + # 400 carries Connection: close, and a fresh connection's + # authed /health still returns 200. + conn = self._conn() + conn.putrequest("POST", "/exec") + conn.putheader("X-Agent-Token", self.token) + conn.putheader("Content-Type", "application/json") + conn.putheader("Content-Length", "abc") + conn.endheaders(b"{}") + r = conn.getresponse() + body = json.loads(r.read()) + self.assertEqual(r.status, 400, body) + self.assertIn("error", body) + self.assertEqual(r.getheader("Connection"), "close") + conn.close() + status, body = self._call("GET", "/health") + self.assertEqual(status, 200) + self.assertTrue(body["ok"]) + + def test_oversized_content_length_rejected_before_reading_body(self): + conn = self._conn() + conn.putrequest("POST", "/exec") + conn.putheader("X-Agent-Token", self.token) + conn.putheader("Content-Type", "application/json") + conn.putheader("Content-Length", str((1 << 20) + 1)) + # A partial body must not make the handler wait for the declared size. + conn.endheaders(b"{}") + r = conn.getresponse() + body = json.loads(r.read()) + self.assertEqual(r.status, 400, body) + self.assertEqual(body["error"], "request body too large") + self.assertEqual(r.getheader("Connection"), "close") + conn.close() + status, body = self._call("GET", "/health") + self.assertEqual(status, 200) + self.assertTrue(body["ok"]) + + def test_content_length_at_max_body_is_accepted(self): + body = {"cmds": [{"cwd": os.getcwd(), + "argv": [sys.executable, "-c", "pass"]}]} + raw = json.dumps(body).encode() + raw += b" " * ((1 << 20) - len(raw)) + status, result = self._call("POST", "/exec", raw=raw) + self.assertEqual(status, 200, result) + self.assertEqual(result["results"][0]["exit"], 0) + + def test_exec_timeout_not_an_integer(self): + self._assert_400_then_health( + "POST", "/exec", + body={"cmds": [{"argv": [sys.executable, "-c", "pass"]}], + "timeout_s": "abc"}) + + def test_exec_non_finite_timeout_is_rejected(self): + conn = self._conn() + try: + for timeout in (float("nan"), float("inf"), float("-inf")): + with self.subTest(timeout=timeout): + status, body = self._call( + "POST", "/exec", + body={"cmds": [{"argv": [sys.executable, "-c", + "pass"]}], + "timeout_s": timeout}, + conn=conn) + self.assertEqual(status, 400, body) + self.assertEqual( + body.get("error"), "timeout_s must be an integer") + status, body = self._call( + "GET", "/health", conn=conn) + self.assertEqual(status, 200, body) + self.assertTrue(body["ok"]) + finally: + conn.close() + + def test_exec_negative_timeout_is_clamped(self): + status, body = self._call( + "POST", "/exec", + body={"cmds": [{"cwd": os.getcwd(), + "argv": [sys.executable, "-c", "pass"]}], + "timeout_s": -5}) + self.assertEqual(status, 200, body) + self.assertEqual(body["results"][0]["exit"], 0) + self.assertNotIn("timeout", body["results"][0]) + + def test_exec_cmd_without_argv_or_shell(self): + self._assert_400_then_health( + "POST", "/exec", body={"cmds": [{"cwd": "/"}]}) + + def test_jobs_without_argv_or_shell(self): + self._assert_400_then_health("POST", "/jobs", body={}) + + def test_jobs_argv_not_a_list(self): + self._assert_400_then_health( + "POST", "/jobs", body={"argv": "echo hi"}) + + def test_job_query_offsets_malformed(self): + status, body = self._call( + "POST", "/jobs", + body={"cwd": os.getcwd(), + "argv": [sys.executable, "-c", "pass"]}) + self.assertEqual(status, 200, body) + job_id = body["job_id"] + self._assert_400_then_health( + "GET", f"/jobs/{job_id}?out_off=abc") + self._assert_400_then_health( + "GET", f"/jobs/{job_id}?err_off=-1") + + +class PersistedJobTimestampTest(unittest.TestCase): + """Issue #1513: non-numeric persisted timestamps must not crash + startup or poison /jobs reads. + + Oracle: a spool dir whose meta.json timestamps are malformed + (string incl. numeric string, bool, list, object) is skipped + whole -- exactly one stderr line naming its dir, nothing added + to JOBS, spool left on disk -- while missing/None keep today's + defaults and well-formed jobs restore exactly as before, + including the running->interrupted conversion. + """ + + def _import_agent(self): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("persisted-ts-test-token\n") + token_path = f.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + return la + + def _write_job(self, state_dir, job_id, **meta): + spool = Path(state_dir) / "jobs" / job_id + spool.mkdir(parents=True) + meta.setdefault("id", job_id) + meta.setdefault("cwd", "/") + meta.setdefault("cmd", "test") + meta.setdefault("exit", 0) + meta.setdefault("state", "done") + (spool / "meta.json").write_text(json.dumps(meta)) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + return spool + + def _load(self, la, state_dir): + la.JOBS.clear() + err = io.StringIO() + with patch.object(la, "STATE_DIR", Path(state_dir)): + with contextlib.redirect_stderr(err): + la.load_persisted_jobs() + return err.getvalue() + + def tearDown(self): + la_mod = sys.modules.get("laptop_agent") + if la_mod is not None: + la_mod.JOBS.clear() + + def test_started_at_string_skipped_healthy_kept_stderr_names_dir(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, "bad-started", + started_at="not-a-number", + ended_at=200.0) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn("bad-started", la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + self.assertIn("started_at", lines[0]) + + def test_ended_at_string_skipped_summary_and_reaper_succeed(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, "bad-ended", + started_at=100.0, ended_at="never") + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn("bad-ended", la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + with patch.object(la, "STATE_DIR", Path(state_dir)): + summaries = [la.job_summary(j) + for j in list(la.JOBS.values())] + la.reap_old_jobs() + self.assertEqual([s["job_id"] for s in summaries], + ["healthy"]) + + def test_done_null_ended_at_stamped_and_reapable(self): + # Issue #1532: a restored done job with ended_at=null kept the + # null, so the reaper read it as "now" (spool retained forever) + # and duration_ms grew with wall-clock time. Oracle: at load it + # gets a finite stamp, duration is stable across reads, and + # the reaper removes it (index + spool) once past TTL. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + now = time.time() + spool = self._write_job(state_dir, "done-null-ended", + started_at=now - 48 * 3600, + ended_at=None) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + job = la.JOBS["done-null-ended"] + self.assertIsInstance(job["ended_at"], float) + with patch.object(la, "STATE_DIR", Path(state_dir)): + first = la.job_summary(job)["duration_ms"] + second = la.job_summary(job)["duration_ms"] + self.assertEqual(first, second) + with patch.object(la, "JOB_TTL_S", -1): + la.reap_old_jobs() + self.assertNotIn("done-null-ended", la.JOBS) + self.assertFalse(spool.exists()) + def test_non_object_meta_skipped_healthy_kept(self): + # Issue #1522: meta.json that is valid JSON but not an object + # gets the same skip contract as malformed timestamps. + la = self._import_agent() + shapes = [("[1, 2, 3]", "list-meta"), ('"hello"', "string-meta"), + ("42", "number-meta"), ("true", "bool-meta"), + ("null", "null-meta")] + for raw, job_id in shapes: + with self.subTest(shape=raw): + with tempfile.TemporaryDirectory() as state_dir: + spool = Path(state_dir) / "jobs" / job_id + spool.mkdir(parents=True) + (spool / "meta.json").write_text(raw) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(spool.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(spool), lines[0]) + + def test_other_malformed_shapes_are_skipped(self): + la = self._import_agent() + cases = [ + ("bool-started", {"started_at": True, "ended_at": 150.0}), + ("list-ended", {"started_at": 100.0, "ended_at": [150.0]}), + ("numeric-string", {"started_at": "123", "ended_at": 150.0}), + ("object-started", {"started_at": {"t": 1}, + "ended_at": 150.0}), + ] + for job_id, stamps in cases: + with self.subTest(job_id=job_id): + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, job_id, **stamps) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertIn("healthy", la.JOBS) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(job_id, lines[0]) + + def test_nonfinite_timestamps_are_skipped(self): + la = self._import_agent() + cases = [ + ("nan-started", {"started_at": float("nan"), + "ended_at": 150.0}), + ("nan-ended", {"started_at": 100.0, + "ended_at": float("nan")}), + ("inf-started", {"started_at": float("inf"), + "ended_at": 150.0}), + ("neg-inf-started", {"started_at": float("-inf"), + "ended_at": 150.0}), + ("inf-ended", {"started_at": 100.0, + "ended_at": float("inf")}), + ("neg-inf-ended", {"started_at": 100.0, + "ended_at": float("-inf")}), + ] + for job_id, stamps in cases: + with self.subTest(job_id=job_id): + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, job_id, **stamps) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + + def test_oversized_int_timestamps_are_skipped(self): + # Codex review on PR #1534: math.isfinite(10**400) raises + # OverflowError (int too large to convert to float) instead + # of returning False, so an oversized integer timestamp must + # be skipped whole like the other malformed shapes, not + # escape load_persisted_jobs() and abort startup. + la = self._import_agent() + cases = [ + ("huge-started", {"started_at": 10**400, "ended_at": 150.0}), + ("huge-ended", {"started_at": 100.0, "ended_at": 10**400}), + ] + for job_id, stamps in cases: + with self.subTest(job_id=job_id): + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, job_id, **stamps) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + + def test_nonfinite_skipped_summary_and_public_succeed(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, "nan-started", + started_at=float("nan"), ended_at=150.0) + self._write_job(state_dir, "inf-ended", + started_at=100.0, ended_at=float("inf")) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 2, stderr) + with patch.object(la, "STATE_DIR", Path(state_dir)): + summaries = [la.job_summary(j) + for j in list(la.JOBS.values())] + publics = [la.job_public(j) + for j in list(la.JOBS.values())] + la.reap_old_jobs() + self.assertEqual([s["job_id"] for s in summaries], + ["healthy"]) + self.assertEqual(summaries[0]["duration_ms"], 50000) + self.assertEqual([p["job_id"] for p in publics], + ["healthy"]) + self.assertEqual(publics[0]["duration_ms"], 50000) + + def test_well_formed_restore_unchanged_and_running_interrupted(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, "done-job", + started_at=100.0, ended_at=150.5) + self._write_job(state_dir, "running-job", state="running", + exit=None, started_at=100.0, ended_at=None) + self._write_job(state_dir, "no-stamps") + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + done = la.JOBS["done-job"] + self.assertEqual(done["started_at"], 100.0) + self.assertEqual(done["ended_at"], 150.5) + self.assertEqual(done["state"], "done") + self.assertFalse(done["interrupted"]) + running = la.JOBS["running-job"] + self.assertEqual(running["state"], "done") + self.assertTrue(running["interrupted"]) + self.assertIsInstance(running["ended_at"], float) + self.assertEqual(running["started_at"], 100.0) + bare = la.JOBS["no-stamps"] + self.assertEqual(bare["started_at"], 0.0) + # #1532 supersedes the #1513 default for a done job: a + # null/missing ended_at gets a finite load-time stamp. + self.assertIsInstance(bare["ended_at"], float) + + def test_non_string_id_skipped_healthy_kept(self): + # Issue #1548: a persisted meta id that is not a string must + # not crash startup (list/object: unhashable at the JOBS + # assignment) or poison /jobs and the reaper (number/bool: + # TypeError at job_dir). Oracle: same skip contract as + # #1513/#1522 -- skipped whole, exactly one stderr line naming + # its dir, spool left on disk, healthy siblings unchanged. + la = self._import_agent() + cases = [ + ("numeric-id", 42), + ("zero-id", 0), + ("bool-id", True), + ("false-id", False), + ("list-id", ["a", "b"]), + ("object-id", {"a": 1}), + ] + for job_id, bad_id in cases: + with self.subTest(job_id=job_id, bad_id=repr(bad_id)): + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, job_id, id=bad_id, + started_at=100.0, + ended_at=150.0) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + self.assertIn("id", lines[0]) + + def test_non_string_id_running_entry_skipped_no_meta_write(self): + # A running entry is the _write_meta crash vector: restore + # converts it to interrupted and _write_meta calls + # job_dir(job["id"]) before its try block. A non-string id + # must be skipped before any of that, spool untouched. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, "running-bad-id", id=42, + state="running", exit=None, + started_at=100.0, ended_at=None) + before = (bad / "meta.json").read_text() + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + self.assertEqual((bad / "meta.json").read_text(), before) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + + def test_non_string_id_summary_public_and_reaper_succeed(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, "list-id-job", id=[1, 2], + started_at=100.0, ended_at=150.0) + self._write_job(state_dir, "numeric-id-job", id=7, + started_at=100.0, ended_at=150.0) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 2, stderr) + with patch.object(la, "STATE_DIR", Path(state_dir)): + summaries = [la.job_summary(j) + for j in list(la.JOBS.values())] + publics = [la.job_public(j) + for j in list(la.JOBS.values())] + la.reap_old_jobs() + self.assertEqual([s["job_id"] for s in summaries], + ["healthy"]) + self.assertEqual([p["job_id"] for p in publics], + ["healthy"]) + + def test_missing_null_empty_id_falls_back_to_dir_name(self): + # Acceptance #1548: missing/null/empty-string id keeps the + # current fallback to the spool directory name. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, "null-id", id=None, + started_at=100.0, ended_at=150.0) + self._write_job(state_dir, "empty-id", id="", + started_at=100.0, ended_at=150.0) + missing = self._write_job(state_dir, "missing-id", + started_at=100.0, ended_at=150.0) + meta = json.loads((missing / "meta.json").read_text()) + del meta["id"] + (missing / "meta.json").write_text(json.dumps(meta)) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + self.assertEqual(sorted(la.JOBS), + ["empty-id", "missing-id", "null-id"]) + + def test_parent_string_id_is_skipped_without_reaping_outside_jobs(self): + # Issue #1554: a persisted traversal id must not escape the jobs + # directory through the public serializers or startup reaper. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + state = Path(state_dir) + bad = self._write_job( + state_dir, "bad-parent-id", id="..", + started_at=100.0, ended_at=time.time() - 2 * la.JOB_TTL_S) + healthy = self._write_job( + state_dir, "healthy", started_at=100.0, ended_at=time.time()) + sentinel = state / "keep-me" + sentinel.write_text("outside the jobs directory") + + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + self.assertIn("id", lines[0]) + + with patch.object(la, "STATE_DIR", state): + summaries = [la.job_summary(j) + for j in list(la.JOBS.values())] + publics = [la.job_public(j) + for j in list(la.JOBS.values())] + la.reap_old_jobs() + + self.assertEqual([s["job_id"] for s in summaries], ["healthy"]) + self.assertEqual([p["job_id"] for p in publics], ["healthy"]) + self.assertTrue(sentinel.exists()) + self.assertTrue(healthy.exists()) + self.assertTrue(bad.exists()) + + def test_separator_and_cross_job_ids_are_skipped(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + bad_separator = self._write_job( + state_dir, "bad-separator", id="../escape", state="running", + exit=None, started_at=100.0, ended_at=None) + bad_separator_meta = (bad_separator / "meta.json").read_text() + cross_job = self._write_job( + state_dir, "cross-job", id="healthy", + started_at=100.0, ended_at=time.time() - 2 * la.JOB_TTL_S) + healthy = self._write_job( + state_dir, "healthy", started_at=100.0, ended_at=time.time()) + + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + self.assertEqual(la.JOBS["healthy"]["cmd_repr"], "test") + self.assertTrue(bad_separator.exists()) + self.assertEqual((bad_separator / "meta.json").read_text(), + bad_separator_meta) + self.assertFalse((Path(state_dir) / "escape").exists()) + self.assertTrue(cross_job.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 2, stderr) + self.assertTrue(all(any(str(spool) in line for line in lines) + for spool in (bad_separator, cross_job)), + stderr) + + with patch.object(la, "STATE_DIR", Path(state_dir)): + la.reap_old_jobs() + self.assertTrue(bad_separator.exists()) + self.assertTrue(cross_job.exists()) + self.assertTrue(healthy.exists()) + + def test_job_dir_rejects_non_child_and_symlink_paths(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + state = Path(state_dir) + jobs = state / "jobs" + jobs.mkdir() + outside = state / "outside" + outside.mkdir() + (jobs / "linked").symlink_to(outside, target_is_directory=True) + with patch.object(la, "STATE_DIR", state): + for job_id in ("..", ".", "../outside", "nested/job", + "nested\\job", "linked"): + with self.subTest(job_id=job_id): + with self.assertRaises(ValueError): + la.job_dir(job_id) + + def test_persisted_interrupted_true_round_trips_two_loads(self): + # Issue #1556: _write_meta persists interrupted:true for a + # restart-interrupted done job, but the restore hardcoded + # interrupted=False, so a second restart dropped the marker. + # Oracle: the flag restores faithfully and round-trips + # unchanged through _write_meta across repeated loads. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_job(state_dir, "interrupted-job", + interrupted=True, exit=None, + started_at=100.0, ended_at=150.0) + self._write_job(state_dir, "plain-job", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + job = la.JOBS["interrupted-job"] + self.assertTrue(job["interrupted"]) + self.assertEqual(job["state"], "done") + with patch.object(la, "STATE_DIR", Path(state_dir)): + self.assertTrue(la.job_public(job)["interrupted"]) + la._write_meta(job) + meta = json.loads((Path(state_dir) / "jobs" + / "interrupted-job" + / "meta.json").read_text()) + self.assertIs(meta["interrupted"], True) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + self.assertTrue(la.JOBS["interrupted-job"]["interrupted"]) + self.assertFalse(la.JOBS["plain-job"]["interrupted"]) + + def test_invalid_state_skipped_healthy_kept(self): + # Issue #1556: a persisted state outside {running, done} was + # restored verbatim, so /jobs served a nonexistent state and + # the recorded exit code was suppressed. Oracle: same skip + # contract as #1513/#1522/#1548 -- skipped whole, exactly one + # stderr line naming its dir, spool left on disk, healthy + # siblings unchanged. + la = self._import_agent() + cases = [ + ("bogus-state", "bogus-state"), + ("numeric-state", 7), + ("list-state", ["done"]), + ("bool-state", True), + ] + for job_id, bad_state in cases: + with self.subTest(job_id=job_id, bad_state=repr(bad_state)): + with tempfile.TemporaryDirectory() as state_dir: + bad = self._write_job(state_dir, job_id, + state=bad_state, + started_at=100.0, + ended_at=150.0) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertNotIn(job_id, la.JOBS) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + self.assertIn("state", lines[0]) + + def test_missing_null_state_defaults_done_and_non_bool_interrupted_skipped(self): + # Issue #1556 acceptance: missing/null state keeps the + # established "done" default, while a non-boolean interrupted + # follows the loader's malformed-field handling (skip whole). + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + missing = self._write_job(state_dir, "missing-state", + started_at=100.0, ended_at=150.0) + meta = json.loads((missing / "meta.json").read_text()) + del meta["state"] + (missing / "meta.json").write_text(json.dumps(meta)) + self._write_job(state_dir, "null-state", state=None, + started_at=100.0, ended_at=150.0) + bad = self._write_job(state_dir, "string-interrupted", + interrupted="yes", + started_at=100.0, ended_at=150.0) + self._write_job(state_dir, "healthy", + started_at=100.0, ended_at=150.0) + stderr = self._load(la, state_dir) + self.assertEqual(la.JOBS["missing-state"]["state"], "done") + self.assertEqual(la.JOBS["null-state"]["state"], "done") + self.assertNotIn("string-interrupted", la.JOBS) + self.assertTrue(bad.exists()) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(bad), lines[0]) + self.assertIn("interrupted", lines[0]) + def test_reap_guards_unsafe_spool_and_removes_healthy(self): + # Issue #1560: PR #1555 made job_dir() raise ValueError, but + # reap_old_jobs() called it unguarded after popping every dead + # job from JOBS -- one spool replaced by a symlink aborted the + # whole reap and the already-popped healthy spools leaked. + # Oracle: reap returns normally, the healthy past-TTL spool is + # removed, the unsafe spool is left in place, and exactly one + # stderr line names the unsafe job (log-and-drop: the job is + # already popped, so without the line the leak is silent). + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + state = Path(state_dir) + jobs_root = state / "jobs" + jobs_root.mkdir(parents=True) + outside = state / "outside" + outside.mkdir() + (jobs_root / "badjob").symlink_to(outside, + target_is_directory=True) + healthy = jobs_root / "goodjob" + healthy.mkdir() + (healthy / "stdout").write_bytes(b"hi") + now = time.time() + for job_id in ("badjob", "goodjob"): + la.JOBS[job_id] = { + "id": job_id, "proc": None, "cwd": "/", + "cmd_repr": "test", "started_at": now - 90000, + "ended_at": now - 90000, "exit": 0, "state": "done", + "interrupted": False, "_files": ()} + err = io.StringIO() + with patch.object(la, "STATE_DIR", state): + with contextlib.redirect_stderr(err): + la.reap_old_jobs() + self.assertEqual(la.JOBS, {}) + self.assertFalse(healthy.exists()) + self.assertTrue((jobs_root / "badjob").is_symlink()) + self.assertTrue(outside.exists()) + lines = [ln for ln in err.getvalue().splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, err.getvalue()) + self.assertIn("badjob", lines[0]) + + def test_read_paths_degrade_per_job_on_unsafe_spool(self): + # Issue #1575: job_public()/job_summary() called job_dir() + # unguarded and _write_meta() called it outside its OSError + # guard -- one spool replaced by a symlink after load made + # GET /jobs answer 400 for every job. Oracle: the serializers + # degrade per-job (poisoned job serves its in-memory record + # with empty output/zero sizes, one stderr line naming it), + # the healthy job reads normally, and _write_meta via + # job_state() cannot leak ValueError. + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + state = Path(state_dir) + jobs_root = state / "jobs" + jobs_root.mkdir(parents=True) + outside = state / "outside" + outside.mkdir() + (jobs_root / "badjob").symlink_to(outside, + target_is_directory=True) + (jobs_root / "runbad").symlink_to(outside, + target_is_directory=True) + healthy = jobs_root / "goodjob" + healthy.mkdir() + (healthy / "stdout").write_bytes(b"hi") + (healthy / "stderr").write_bytes(b"") + now = time.time() + for job_id, st in (("badjob", "done"), ("goodjob", "done"), + ("runbad", "running")): + la.JOBS[job_id] = { + "id": job_id, "proc": None, "cwd": "/", + "cmd_repr": "test", "started_at": now - 10, + "ended_at": now if st == "done" else None, + "exit": 0 if st == "done" else None, "state": st, + "interrupted": False, "_files": ()} + err = io.StringIO() + with patch.object(la, "STATE_DIR", state): + with contextlib.redirect_stderr(err): + summaries = [la.job_summary(j) + for j in la.JOBS.values() + if j["state"] == "done"] + public_bad = la.job_public(la.JOBS["badjob"]) + public_good = la.job_public(la.JOBS["goodjob"]) + # job_state on a running job calls _write_meta. + self.assertEqual(la.job_state(la.JOBS["runbad"]), + "done") + by_id = {x["job_id"]: x for x in summaries} + self.assertEqual(by_id["goodjob"]["out_bytes"], 2) + self.assertEqual(by_id["badjob"]["out_bytes"], 0) + self.assertEqual(by_id["badjob"]["err_bytes"], 0) + self.assertEqual(public_bad["stdout"], "") + self.assertEqual(public_bad["state"], "done") + self.assertEqual(public_good["stdout"], "hi") + lines = [ln for ln in err.getvalue().splitlines() + if ln.strip()] + self.assertTrue(any("badjob" in ln for ln in lines), + err.getvalue()) + +class PersistedJobRestoreContractTest(unittest.TestCase): + """Issue #1579 (design #1578 phase 1): the contract probe matrix + for the one restore validator, generated from the field table. + + Oracle: the writer (_write_meta). Every guarded field x {wrong + type, non-finite where numeric, bool-as-number, shape attack + where applicable, missing, null, the writer's own well-formed + value}: a present-but-malformed value skips the whole entry -- + exactly one stderr line naming the directory and the field, + the spool byte-identical, a healthy sibling restored -- while + missing/null takes the table's named default and a well-formed + value restores verbatim. Plus both transition rows and one + _write_meta -> reload round-trip asserting the served job is + identical. The per-incident tests in PersistedJobTimestampTest + above are the regression oracle; their assertions are + unmodified -- this class only adds coverage. + """ + + def _import_agent(self): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("restore-contract-test-token\n") + token_path = f.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + return la + + def _base_meta(self, job_id): + return {"id": job_id, "cwd": "/", "cmd": "test", + "started_at": 100.0, "ended_at": 150.0, "exit": 0, + "state": "done", "interrupted": False} + + def _write_raw(self, state_dir, job_id, meta): + spool = Path(state_dir) / "jobs" / job_id + spool.mkdir(parents=True) + raw = json.dumps(meta) + (spool / "meta.json").write_text(raw) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + return spool, raw + + def _load(self, la, state_dir): + la.JOBS.clear() + err = io.StringIO() + with patch.object(la, "STATE_DIR", Path(state_dir)): + with contextlib.redirect_stderr(err): + la.load_persisted_jobs() + return err.getvalue() + + def tearDown(self): + la_mod = sys.modules.get("laptop_agent") + if la_mod is not None: + la_mod.JOBS.clear() + + def test_field_table_covers_exactly_the_writer_fields(self): + la = self._import_agent() + self.assertEqual( + [row[0] for row in la.RESTORE_FIELD_TABLE], + ["id", "cwd", "cmd", "started_at", "ended_at", + "exit", "state", "interrupted"]) + for row in la.RESTORE_FIELD_TABLE: + self.assertEqual(len(row), 4, row) + by_field = {row[0]: row for row in la.RESTORE_FIELD_TABLE} + for field in ("exit", "cwd", "cmd"): + self.assertIn("#1568", by_field[field][3]) + + def test_malformed_matrix_rows_are_skipped(self): + la = self._import_agent() + ts_bad = ["123", True, False, [150.0], {"t": 1}, + float("nan"), float("inf"), float("-inf"), 10**400] + cases = [] + for value in ts_bad: + cases.append(("started_at", value)) + cases.append(("ended_at", value)) + for value in [42, True, ["a"], {"a": 1}, + "..", ".", "a/b", "a\\b", "other-job"]: + cases.append(("id", value)) + for value in ["bogus", 7, True, ["done"], {"s": 1}]: + cases.append(("state", value)) + for value in ["yes", 1, 0, ["true"], {"i": 1}]: + cases.append(("interrupted", value)) + for field, value in cases: + with self.subTest(field=field, value=repr(value)): + with tempfile.TemporaryDirectory() as state_dir: + meta = self._base_meta("bad-job") + meta[field] = value + spool, raw = self._write_raw(state_dir, "bad-job", + meta) + self._write_raw(state_dir, "healthy", + self._base_meta("healthy")) + stderr = self._load(la, state_dir) + self.assertNotIn("bad-job", la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(spool.exists()) + self.assertEqual((spool / "meta.json").read_text(), + raw) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(spool), lines[0]) + self.assertIn(field, lines[0]) + + def test_non_object_container_matrix_rows_are_skipped(self): + la = self._import_agent() + for raw in ["[1, 2, 3]", '"hello"', "42", "true", "null"]: + with self.subTest(raw=raw): + with tempfile.TemporaryDirectory() as state_dir: + spool = Path(state_dir) / "jobs" / "bad-job" + spool.mkdir(parents=True) + (spool / "meta.json").write_text(raw) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + self._write_raw(state_dir, "healthy", + self._base_meta("healthy")) + stderr = self._load(la, state_dir) + self.assertNotIn("bad-job", la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertEqual((spool / "meta.json").read_text(), + raw) + lines = [ln for ln in stderr.splitlines() + if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(spool), lines[0]) + + def test_missing_and_null_rows_take_table_defaults(self): + la = self._import_agent() + for field in ["started_at", "ended_at", "id", "state", + "interrupted"]: + for mode in ["missing", "null"]: + with self.subTest(field=field, mode=mode): + with tempfile.TemporaryDirectory() as state_dir: + meta = self._base_meta("case-job") + if mode == "missing": + del meta[field] + else: + meta[field] = None + self._write_raw(state_dir, "case-job", meta) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + job = la.JOBS["case-job"] + if field == "started_at": + self.assertEqual(job["started_at"], 0.0) + elif field == "ended_at": + # #1532 transition: stamped at load. + self.assertIsInstance(job["ended_at"], + float) + elif field == "state": + self.assertEqual(job["state"], "done") + elif field == "interrupted": + self.assertFalse(job["interrupted"]) + with tempfile.TemporaryDirectory() as state_dir: + meta = self._base_meta("empty-id") + meta["id"] = "" + self._write_raw(state_dir, "empty-id", meta) + self.assertEqual(self._load(la, state_dir), "") + self.assertIn("empty-id", la.JOBS) + + def test_well_formed_writer_values_restore_verbatim(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + self._write_raw(state_dir, "writer-job", + self._base_meta("writer-job")) + meta = self._base_meta("int-stamps") + meta["started_at"] = 100 + meta["ended_at"] = 150 + meta["interrupted"] = True + self._write_raw(state_dir, "int-stamps", meta) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + job = la.JOBS["writer-job"] + self.assertEqual(job["started_at"], 100.0) + self.assertEqual(job["ended_at"], 150.0) + self.assertEqual(job["exit"], 0) + self.assertEqual(job["state"], "done") + self.assertFalse(job["interrupted"]) + self.assertEqual(job["cwd"], "/") + self.assertEqual(job["cmd_repr"], "test") + stamps = la.JOBS["int-stamps"] + self.assertEqual(stamps["started_at"], 100.0) + self.assertEqual(stamps["ended_at"], 150.0) + self.assertTrue(stamps["interrupted"]) + + def test_both_transitions_and_their_persistence(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + running = self._base_meta("was-running") + running.update(state="running", exit=5, ended_at=None) + spool_r, _ = self._write_raw(state_dir, "was-running", + running) + done = self._base_meta("done-no-end") + done["ended_at"] = None + spool_d, _ = self._write_raw(state_dir, "done-no-end", + done) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + job = la.JOBS["was-running"] + self.assertEqual(job["state"], "done") + self.assertTrue(job["interrupted"]) + self.assertIsNone(job["exit"]) + self.assertIsInstance(job["ended_at"], float) + meta_r = json.loads((spool_r / "meta.json").read_text()) + self.assertEqual(meta_r["state"], "done") + self.assertIs(meta_r["interrupted"], True) + self.assertIsNone(meta_r["exit"]) + self.assertEqual(meta_r["ended_at"], job["ended_at"]) + job_d = la.JOBS["done-no-end"] + self.assertIsInstance(job_d["ended_at"], float) + meta_d = json.loads((spool_d / "meta.json").read_text()) + self.assertEqual(meta_d["ended_at"], job_d["ended_at"]) + + def test_validator_returns_a_single_reason_naming_the_field(self): + la = self._import_agent() + cases = [("started_at", "123"), ("ended_at", float("nan")), + ("id", 42), ("id", ".."), ("state", "bogus"), + ("interrupted", "yes")] + with tempfile.TemporaryDirectory() as state_dir: + with patch.object(la, "STATE_DIR", Path(state_dir)): + for field, value in cases: + with self.subTest(field=field, value=repr(value)): + meta = self._base_meta("case-job") + meta[field] = value + job, persist, reason = \ + la._restore_persisted_job(meta, "case-job") + self.assertIsNone(job) + self.assertFalse(persist) + self.assertIn(field, reason) + job, persist, reason = la._restore_persisted_job( + self._base_meta("case-job"), "case-job") + self.assertIsNotNone(job) + self.assertIsNone(reason) + + def test_write_meta_reload_round_trip_serves_identical_job(self): + la = self._import_agent() + job = {"id": "round-trip", "proc": None, "cwd": "/", + "cmd_repr": "echo hi", "started_at": 100.0, + "ended_at": 150.0, "exit": 3, "state": "done", + "interrupted": False, "_files": ()} + with tempfile.TemporaryDirectory() as state_dir: + with patch.object(la, "STATE_DIR", Path(state_dir)): + la._write_meta(job) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + restored = la.JOBS["round-trip"] + for key in ("id", "cwd", "cmd_repr", "started_at", + "ended_at", "exit", "state", "interrupted"): + self.assertEqual(restored[key], job[key], key) + with patch.object(la, "STATE_DIR", Path(state_dir)): + public = la.job_public(restored) + self.assertEqual(public, { + "job_id": "round-trip", "state": "done", "exit": 3, + "cwd": "/", "cmd": "echo hi", "started_at": 100.0, + "interrupted": False, "duration_ms": 50000, + "stdout": "", "stderr": "", "out_next": 0, + "err_next": 0}) + + +class PersistedJobExitCwdCmdTest(unittest.TestCase): + """Issue #1568: load_persisted_jobs restored exit/cwd/cmd + verbatim -- a malformed meta.json exit was served verbatim as + the job's exit code, and _write_meta re-persisted the junk. + + Oracle: the writer (_write_meta) only ever writes exit as an + int returncode (negative for signal deaths) or None, and + cwd/cmd as strings. A present value of any other shape follows + the established skip contract -- skipped whole, exactly one + stderr line naming its dir and the field, spool left on disk, + healthy siblings unchanged -- while missing/None keep the + established defaults (None / home dir / ""). The checks live + in the one restore validator as RESTORE_FIELD_TABLE rows, per + the #1579 fold-in rule (design #1578 phase 1). + """ + + def _import_agent(self): + with tempfile.NamedTemporaryFile("w", suffix="-token", + delete=False) as f: + f.write("persisted-exit-cwd-cmd-test-token\n") + token_path = f.name + os.environ.setdefault("LAPTOP_AGENT_TOKEN_FILE", token_path) + sys.path.insert(0, str(AGENT.parent)) + import laptop_agent as la + return la + + def _base_meta(self, job_id): + return {"id": job_id, "cwd": "/", "cmd": "test", + "started_at": 100.0, "ended_at": 150.0, "exit": 0, + "state": "done", "interrupted": False} + + def _write_raw(self, state_dir, job_id, meta): + spool = Path(state_dir) / "jobs" / job_id + spool.mkdir(parents=True) + raw = json.dumps(meta) + (spool / "meta.json").write_text(raw) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + return spool, raw + + def _load(self, la, state_dir): + la.JOBS.clear() + err = io.StringIO() + with patch.object(la, "STATE_DIR", Path(state_dir)): + with contextlib.redirect_stderr(err): + la.load_persisted_jobs() + return err.getvalue() + + def tearDown(self): + la_mod = sys.modules.get("laptop_agent") + if la_mod is not None: + la_mod.JOBS.clear() + + def _assert_skipped(self, la, field, value): + with tempfile.TemporaryDirectory() as state_dir: + meta = self._base_meta("bad-job") + meta[field] = value + spool, raw = self._write_raw(state_dir, "bad-job", meta) + self._write_raw(state_dir, "healthy", + self._base_meta("healthy")) + stderr = self._load(la, state_dir) + self.assertNotIn("bad-job", la.JOBS) + self.assertIn("healthy", la.JOBS) + self.assertTrue(spool.exists()) + self.assertEqual((spool / "meta.json").read_text(), raw) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + self.assertIn(str(spool), lines[0]) + self.assertIn(field, lines[0]) + + def test_non_integer_exit_skipped_healthy_kept(self): + la = self._import_agent() + for value in ["0", [0], {"x": 1}, 0.5, True, False]: + with self.subTest(value=repr(value)): + self._assert_skipped(la, "exit", value) + + def test_exit_controls_restore_verbatim(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + for job_id, value in [("zero-exit", 0), + ("negative-exit", -9), + ("null-exit", None)]: + meta = self._base_meta(job_id) + meta["exit"] = value + self._write_raw(state_dir, job_id, meta) + meta = self._base_meta("missing-exit") + del meta["exit"] + self._write_raw(state_dir, "missing-exit", meta) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + self.assertEqual(la.JOBS["zero-exit"]["exit"], 0) + self.assertEqual(la.JOBS["negative-exit"]["exit"], -9) + self.assertIsNone(la.JOBS["null-exit"]["exit"]) + self.assertIsNone(la.JOBS["missing-exit"]["exit"]) + + def test_non_string_cwd_skipped_healthy_kept(self): + la = self._import_agent() + for value in [123, ["x"], {"x": 1}, True]: + with self.subTest(value=repr(value)): + self._assert_skipped(la, "cwd", value) + + def test_cwd_defaults_and_verbatim_restore(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + for job_id, mode in [("missing-cwd", "missing"), + ("null-cwd", "null"), + ("empty-cwd", "empty")]: + meta = self._base_meta(job_id) + if mode == "missing": + del meta["cwd"] + elif mode == "null": + meta["cwd"] = None + else: + meta["cwd"] = "" + self._write_raw(state_dir, job_id, meta) + meta = self._base_meta("real-cwd") + meta["cwd"] = "/work/tree" + self._write_raw(state_dir, "real-cwd", meta) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + for job_id in ("missing-cwd", "null-cwd", "empty-cwd"): + self.assertEqual(la.JOBS[job_id]["cwd"], + str(Path.home())) + self.assertEqual(la.JOBS["real-cwd"]["cwd"], "/work/tree") + + def test_non_string_cmd_skipped_healthy_kept(self): + la = self._import_agent() + for value in [{"x": 1}, 42, ["ls"], True]: + with self.subTest(value=repr(value)): + self._assert_skipped(la, "cmd", value) + + def test_cmd_defaults_and_verbatim_restore(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + for job_id, mode in [("missing-cmd", "missing"), + ("null-cmd", "null"), + ("empty-cmd", "empty")]: + meta = self._base_meta(job_id) + if mode == "missing": + del meta["cmd"] + elif mode == "null": + meta["cmd"] = None + else: + meta["cmd"] = "" + self._write_raw(state_dir, job_id, meta) + meta = self._base_meta("real-cmd") + meta["cmd"] = "ls -la" + self._write_raw(state_dir, "real-cmd", meta) + stderr = self._load(la, state_dir) + self.assertEqual(stderr, "") + for job_id in ("missing-cmd", "null-cmd", "empty-cmd"): + self.assertEqual(la.JOBS[job_id]["cmd_repr"], "") + self.assertEqual(la.JOBS["real-cmd"]["cmd_repr"], "ls -la") + + def test_malformed_exit_summary_public_and_reaper_succeed(self): + la = self._import_agent() + with tempfile.TemporaryDirectory() as state_dir: + meta = self._base_meta("bad-exit") + meta["exit"] = "0" + self._write_raw(state_dir, "bad-exit", meta) + self._write_raw(state_dir, "healthy", + self._base_meta("healthy")) + stderr = self._load(la, state_dir) + self.assertEqual(sorted(la.JOBS), ["healthy"]) + lines = [ln for ln in stderr.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1, stderr) + with patch.object(la, "STATE_DIR", Path(state_dir)): + summaries = [la.job_summary(j) + for j in list(la.JOBS.values())] + publics = [la.job_public(j) + for j in list(la.JOBS.values())] + la.reap_old_jobs() + self.assertEqual([s["job_id"] for s in summaries], + ["healthy"]) + self.assertEqual(publics[0]["exit"], 0) + + +class ReaperStartupTest(unittest.TestCase): + """#1504: past-TTL finished jobs are reaped at startup, with no + new POST /jobs — the daemon is only ever health-polled here. + + Oracle: a persisted done job whose ended_at is past the 24h TTL + loses both its index entry and its spool dir at startup, while a + within-TTL done job and a restored (interrupted) job survive. + """ + + def _write_job(self, state_dir, job_id, **meta): + spool = Path(state_dir) / "jobs" / job_id + spool.mkdir(parents=True) + meta.setdefault("id", job_id) + meta.setdefault("cwd", "/") + meta.setdefault("cmd", "test") + meta.setdefault("exit", 0) + meta.setdefault("state", "done") + (spool / "meta.json").write_text(json.dumps(meta)) + (spool / "stdout").write_bytes(b"") + (spool / "stderr").write_bytes(b"") + return spool + + def test_past_ttl_restored_job_reaped_at_startup(self): + now = time.time() + with tempfile.TemporaryDirectory() as state_dir: + old = self._write_job(state_dir, "old-done", + started_at=now - 26 * 3600, + ended_at=now - 25 * 3600) + fresh = self._write_job(state_dir, "fresh-done", + started_at=now - 7200, + ended_at=now - 3600) + running = self._write_job(state_dir, "was-running", + state="running", exit=None, + started_at=now - 26 * 3600, + ended_at=None) + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write("reaper-test-token\n") + token_path = f.name + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_STATE=state_dir) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + try: + req = urllib.request.Request( + f"http://127.0.0.1:{port}/jobs", + headers={"X-Agent-Token": "reaper-test-token"}) + deadline = time.time() + 15 + jobs = None + while time.time() < deadline: + try: + with urllib.request.urlopen(req, timeout=2) as r: + jobs = json.loads(r.read())["jobs"] + break + except (urllib.error.URLError, ConnectionError): + time.sleep(0.1) + else: + self.fail("agent did not start") + ids = {j["job_id"] for j in jobs} + self.assertEqual(ids, {"fresh-done", "was-running"}) + self.assertFalse(old.exists()) + self.assertTrue(fresh.exists()) + self.assertTrue(running.exists()) + finally: + proc.terminate() + proc.wait(timeout=10) + os.unlink(token_path) + + def test_unsafe_persisted_ids_do_not_escape_jobs_at_startup(self): + now = time.time() + with tempfile.TemporaryDirectory() as state_dir: + state = Path(state_dir) + bad_parent = self._write_job( + state_dir, "bad-parent", id="..", started_at=now - 26 * 3600, + ended_at=now - 25 * 3600) + bad_separator = self._write_job( + state_dir, "bad-separator", id="a/b", + started_at=now - 26 * 3600, ended_at=now - 25 * 3600) + cross_job = self._write_job( + state_dir, "cross-job", id="healthy", + started_at=now - 26 * 3600, ended_at=now - 25 * 3600) + healthy = self._write_job( + state_dir, "healthy", started_at=now - 3600, + ended_at=now - 1800) + sentinel = state / "keep-me" + sentinel.write_text("state outside jobs must survive") + + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write("reaper-test-token\n") + token_path = f.name + port = free_port() + env = dict(os.environ, + LAPTOP_AGENT_TOKEN_FILE=token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(port), + LAPTOP_AGENT_STATE=state_dir) + proc = subprocess.Popen([sys.executable, str(AGENT)], env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + try: + req = urllib.request.Request( + f"http://127.0.0.1:{port}/jobs", + headers={"X-Agent-Token": "reaper-test-token"}) + deadline = time.time() + 15 + jobs = None + while time.time() < deadline: + try: + with urllib.request.urlopen(req, timeout=2) as r: + jobs = json.loads(r.read())["jobs"] + break + except (urllib.error.URLError, ConnectionError): + time.sleep(0.1) + else: + self.fail("agent did not start") + + self.assertEqual({j["job_id"] for j in jobs}, {"healthy"}) + self.assertEqual(jobs[0]["cmd"], "test") + self.assertTrue(sentinel.exists()) + self.assertTrue(healthy.exists()) + self.assertTrue(bad_parent.exists()) + self.assertTrue(bad_separator.exists()) + self.assertTrue(cross_job.exists()) + finally: + proc.terminate() + proc.wait(timeout=10) + os.unlink(token_path) + + +if __name__ == "__main__": + unittest.main()