#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Bounded /release adapter for this run: one POST, the op persisted BEFORE the socket. The shared tool has a `release` verb but it only appends a LEDGER line (`cmd_release` writes to the attempt-state file and prints it); it never contacts the server. So a release that can be *verified* needs its own call. Same shape as the run's other adapters (file_audit.py): the op file is written first, the response is stored with its HTTP code, and an uncertain response is retried with the SAME request id and byte-identical body -- never a second attempt id. Usage: python release_bounded.py --attempt <32hex> --reason "..." [--status released] [--dry-run] Writes: /state/ops/release-.json (+ prints the receipt) """ import argparse import hashlib import json import os import sys import urllib.error import urllib.request from datetime import datetime, timezone SERVER = "https://solveathome.org" PROJECT = "twin-primes" def now_iso(): return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" def base_dir(): return os.environ.get("LOCALAPPDATA") or os.path.expanduser("~/.local/share") def token_file(): return os.path.join(base_dir(), "solveathome", "credentials", "twin-primes.token") def headers(state, attempt): rr = json.load(open(os.path.join(state, "run.json"), encoding="utf-8")) tok = open(token_file(), encoding="utf-8").read().strip() return { "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + tok, "X-Model": rr["model"], "X-Effort": rr["effort"], "X-Session": rr["session"], "X-Department": rr["department_id"], "X-Launch-ID": rr["launch_id"], "X-Attempt": attempt, } def write_atomic(path, obj): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8", newline="\n") as fh: json.dump(obj, fh, indent=1, ensure_ascii=False, sort_keys=True) fh.write("\n") fh.flush() os.fsync(fh.fileno()) os.replace(tmp, path) def main(): ap = argparse.ArgumentParser() ap.add_argument("run") ap.add_argument("--attempt", required=True) ap.add_argument("--job", default=None, help="the assignment id being handed back; the endpoint REFUSES 400 without it " "('job_id is required: the id of the assignment you are handing back')") ap.add_argument("--reason", required=True) ap.add_argument("--status", default="released") ap.add_argument("--dry-run", action="store_true") ap.add_argument("--retry", action="store_true") a = ap.parse_args() st = os.path.join(a.run, "state") payload = {"attempt_id": a.attempt, "reason": a.reason, "status": a.status} if a.job: payload["job_id"] = a.job body = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8") bhash = hashlib.sha256(body).hexdigest() url = "%s/projects/%s/release" % (SERVER, PROJECT) opf = os.path.join(st, "ops", "release-%s.json" % a.attempt) op = {"tool": "release-bounded/1.0", "method": "POST", "url": url, "request_id": a.attempt, "attempt_id": a.attempt, "body_sha256": bhash, "sent": False, "at": now_iso()} if os.path.exists(opf): prev = json.load(open(opf, encoding="utf-8")) accepted = prev.get("receipt") and prev.get("response_code") in (200, 201, 202) if accepted and not a.retry: print(json.dumps({"ok": True, "already": True, "op": opf, "receipt": prev["receipt"]}, indent=1)) return 0 if a.retry and prev.get("body_sha256") != bhash: raise SystemExit("refusing to retry with a changed body") write_atomic(opf, op) if a.dry_run: print(json.dumps({"ok": True, "dry_run": True, "url": url, "op": opf, "payload": payload}, indent=1)) return 0 req = urllib.request.Request(url, data=body, headers=headers(st, a.attempt), method="POST") try: with urllib.request.urlopen(req, timeout=60) as r: code, raw = r.status, r.read().decode("utf-8", "replace") except urllib.error.HTTPError as e: code, raw = e.code, e.read().decode("utf-8", "replace") except Exception as e: # noqa: BLE001 - reported, never raised code, raw = 0, "ERR %s" % e try: j = json.loads(raw) except Exception: # noqa: BLE001 j = None if code == 0: write_atomic(opf, dict(op, sent=True, uncertain=True, last_error=raw[:200])) print(json.dumps({"ok": False, "uncertain": True, "op": opf}, indent=1)) return 1 write_atomic(opf, dict(op, sent=True, response_code=code, receipt=j if isinstance(j, dict) else raw[:600])) print(json.dumps({"ok": code == 200, "http": code, "op": opf, "receipt": j if isinstance(j, dict) else raw[:600]}, indent=1)[:1500]) return 0 if code == 200 else 1 if __name__ == "__main__": sys.exit(main())