#!/usr/bin/env python3 """RamWeave foreground volunteer and receipt client, Python 3.9+, macOS/Linux. Copyright (c) 2026 RamWeave contributors. MIT licence. The fixed operation reconciles public NHS England aggregate A&E returns. Contains public sector information licensed under the Open Government Licence v3.0. """ import argparse import csv import ctypes from datetime import datetime, timezone import fcntl import hashlib import http.client import io import json import math import mmap import os from pathlib import Path import re import resource import secrets import signal import socket import sys import tempfile import time from urllib.parse import urlsplit ORIGIN = "https://ramweave.com" OPERATION = "monthly-ae-totals-v1" MIB = 1024 * 1024 MAX_CSV = 48 * 1024 RAM_CHOICES = (16, 32, 64, 128) # Frozen detail-only UTF-8 bytes. The independent national control stays at the coordinator. KNOWN_RELEASES = { "2025-04": "bd4ba63b8b05d233e94635d82d855bfc9e0e3334afc68ef6d8fa5b1006b1162c", "2025-05": "eec137a44389b77ef4640f710e9d7e6e1f65695a12fa7a14ff537c97a000f2dc", "2025-06": "9ec7a8a0993556ea5b6a3affe79c5b27b36288cffe38d9a71c194b121ebe79c1", "2025-07": "109c680b9371ce1c10de491515c373079f78ed8a2e315c8b7232395ac596e8fc", "2025-08": "02d12493cd2f3bb20a384e41c5ae21ad92ddb948acef059aa72b88a7efefcd24", "2025-09": "494b9c2df181528dc62ab1e6504440da4e2faa53f6972929959ecd7b658c9d6e", "2025-10": "b36cb87d8d361b592528393fa43619614cdb17e4d932f0d9497a9ea62e73ed99", "2025-11": "67e475207e377195d2553df8f4cfb692c0abcafbe496817d80d0b71a0f5a6455", "2025-12": "ac700824555e978ed05c09c9579ecca7e039f18903242554dd2f18e50c01adf8", "2026-01": "8aa149c2e7df91e8936a72a9d1ea5082e22da66ae70af622e12fddd83b491b61", "2026-02": "2ca024a2e6b330c6339e7380b62dd804d4bd0979b974e05f493649882dc2dda6", "2026-03": "383ccd7e5b00ebbaa3a16c226d19dff9683a1be92e5b92b25401ab5438c11cca", } class RequestError(ValueError): def __init__(self, status, detail, retry_after=0): self.status, self.retry_after = status, retry_after super().__init__(detail) class SessionEnded(Exception): pass def timestamp(value): date = datetime.fromisoformat(str(value).replace("Z", "+00:00")) if date.utcoffset() is None: raise ValueError("A timestamp with a timezone is required.") return date.timestamp() def utc(value): return datetime.fromtimestamp(value, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") def emit(event, **fields): print(json.dumps({"event": event, **fields}, separators=(",", ":")), flush=True) def require(condition, message): if not condition: raise ValueError(message) def hex_id(value, length): return isinstance(value, str) and re.fullmatch("[0-9a-f]{" + str(length) + "}", value) is not None class Client: def __init__(self, origin): parsed = urlsplit(origin) local = (parsed.scheme == "http" and parsed.hostname in {"127.0.0.1", "::1"} and parsed.port is not None and parsed.username is None and parsed.password is None and not parsed.query and not parsed.fragment and parsed.path in {"", "/"}) require(origin.rstrip("/") == ORIGIN or local, "Use https://ramweave.com or an explicit HTTP loopback demo port.") self.origin, self.host, self.port, self.local = origin.rstrip("/"), parsed.hostname, parsed.port, local def request(self, method, path, token=None, body=None, timeout=12): require(path.startswith("/api/v1/") and re.fullmatch(r"/[a-z0-9/-]+", path), "Invalid API route.") encoded = json.dumps(body, separators=(",", ":")).encode() if body is not None else None headers = {"Accept": "application/json", "User-Agent": "RamWeave-Volunteer/1"} if encoded is not None: headers["Content-Type"] = "application/json" if token is not None: require(hex_id(token, 64), "Invalid bearer in the local credential file.") headers["Authorization"] = "Bearer " + token kind = http.client.HTTPConnection if self.local else http.client.HTTPSConnection conn = kind(self.host, self.port, timeout=max(0.05, min(timeout, 12))) try: # http.client makes exactly this request and never follows redirects. conn.request(method, path, encoded, headers) response = conn.getresponse() if 300 <= response.status < 400: raise RequestError(response.status, "The coordinator redirected the request. Stopping.") raw = response.read(131073) require(len(raw) <= 131072, "Coordinator reply exceeded 128 KiB.") if response.status >= 400: wait = response.getheader("Retry-After", "") retry_after = min(180, int(wait)) if re.fullmatch(r"[0-9]{1,3}", wait) else 0 try: detail = json.loads(raw).get("error", "") except (ValueError, AttributeError): detail = "" # Do not print arbitrary server text or terminal control sequences. readable = ("".join(c for c in str(detail) if c.isascii() and c.isprintable()))[:170] raise RequestError(response.status, readable or f"Coordinator returned HTTP {response.status}.", retry_after) require(response.getheader("Content-Type", "").split(";")[0] == "application/json", "Expected pilot JSON.") data = json.loads(raw) require(isinstance(data, dict), "Invalid coordinator reply.") return data finally: conn.close() def load_file(path): with Path(path).open("rb") as source: raw = source.read(8193) require(len(raw) <= 8192, "The credential file is too large.") data = json.loads(raw) require(isinstance(data, dict), "Expected a JSON credential file.") return data def save_file(path, value, initial=False): path = Path(path) with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".ramweave-", delete=False) as target: temp = Path(target.name) try: target.write((json.dumps(value, indent=2) + "\n").encode()) target.flush() os.fsync(target.fileno()) except BaseException: temp.unlink(missing_ok=True) raise try: if initial: os.link(temp, path) else: os.replace(temp, path) directory = os.open(path.parent, os.O_RDONLY) try: os.fsync(directory) finally: os.close(directory) finally: temp.unlink(missing_ok=True) def peak_rss(): # Same Darwin/Linux rusage conversion as workbench/ramweave_desk/reserve_worker.py. size = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss return int(size if sys.platform == "darwin" else size * 1024) def resident_payload(mapping, size): # From ram-contribution/lender_state.py, sampled on the actual job input mapping. page = mmap.PAGESIZE flags = (ctypes.c_ubyte * ((size + page - 1) // page))() addr = ctypes.addressof(ctypes.c_char.from_buffer(mapping)) try: probe = ctypes.CDLL(None, use_errno=True).mincore except AttributeError: return None if probe(ctypes.c_void_p(addr), ctypes.c_size_t(size), ctypes.byref(flags)): return None return sum(min(page, size - i * page) for i, flag in enumerate(flags) if flag & 1) def reconcile(lease, cap_mib, deadline): started = time.monotonic() require(lease.get("operation") == OPERATION and hex_id(lease.get("runId"), 32), "Unrecognised work assignment.") period, text, reserved = lease.get("period"), lease.get("csv"), lease.get("reservedMiB") require(isinstance(period, str) and period in KNOWN_RELEASES, "Unexpected reporting month.") require(type(reserved) is int and 32 <= reserved <= cap_mib, "The assignment exceeds your RAM offer.") require(isinstance(text, str) and 0 < len(text) <= MAX_CSV, "Input exceeds the fixed CSV allowance.") data = text.encode() require(len(data) <= MAX_CSV and hashlib.sha256(data).hexdigest() == lease.get("inputSHA256") == KNOWN_RELEASES[period], "Input differs from the pinned public release.") charged = math.ceil(len(data) / mmap.PAGESIZE) * mmap.PAGESIZE def check_budget(): if time.monotonic() >= deadline: raise SessionEnded("The assignment reached its local deadline.") require(peak_rss() <= reserved * MIB, "Reached the RAM budget. The result was withheld.") check_budget() with mmap.mmap(-1, len(data)) as pages: pages.write(data) resident = resident_payload(pages, len(data)) pages.seek(0) # Iterate directly across the mapping. Keep only distinct provider IDs, headers and counts. reader = csv.reader(iter(lambda: pages.readline().decode("utf-8"), "")) header = next(reader) require(header[:5] == ["Period", "Org Code", "Parent Org", "Org name", "A&E attendances Type 1"] and len(set(header)) == len(header) == 22, "Unexpected public return schema.") seen, totals = set(), dict.fromkeys(header[4:], 0) for row in reader: require(len(row) == len(header) and row[1] and row[1] != "TOTAL" and row[1] not in seen, "Repeated provider, control row or invalid row width.") seen.add(row[1]) for key, raw in zip(header[4:], row[4:]): require(raw.isascii() and raw.isdecimal(), "Invalid published count.") totals[key] += int(raw) if len(seen) % 16 == 0: check_budget() require(bool(seen), "No provider rows found.") check_budget() return {"rows": len(seen), "totals": totals, "metrics": { "peakRssBytes": peak_rss(), "residentInputBytes": resident, "reservedInputBytes": charged, "durationMs": max(0.001, round((time.monotonic() - started) * 1000, 3))}} def device_config(path): data = load_file(path) require(hex_id(data.get("offerId"), 32) and hex_id(data.get("workerToken"), 64) and type(data.get("ramMiB")) is int and data["ramMiB"] in RAM_CHOICES, "Download the device file with its offer, worker token and RAM limit.") seconds = timestamp(data.get("expiresAt")) - time.time() return data, max(0, min(seconds, 7200)) def retry_request(client, path, token, body, deadline): delay = 1 while time.monotonic() < deadline: try: return client.request("POST", path, token, body, timeout=deadline - time.monotonic()) except RequestError as err: if err.status not in {429, 500, 502, 503, 504}: raise delay = max(delay, err.retry_after) except (OSError, http.client.HTTPException): pass emit("connection-retry", seconds=round(min(delay, max(0, deadline - time.monotonic())), 1)) time.sleep(min(delay, max(0, deadline - time.monotonic()))) delay = min(30, delay * 2) raise SessionEnded("The time window ended.") def work(client, args): config, seconds = device_config(args.offer) require(config.get("origin", ORIGIN) == client.origin, "This device file belongs to another coordinator.") cap = min(config["ramMiB"], args.ram_mib or 128) deadline = time.monotonic() + min(seconds, (args.minutes or 120) * 60) oid, token = config["offerId"], config["workerToken"] require(0.25 <= args.poll_seconds <= 60 and args.max_jobs >= 0, "Invalid polling interval or job limit.") require(args.minutes is None or 1 <= args.minutes <= 120, "Choose a 1–120 minute foreground session.") if deadline <= time.monotonic(): emit("ended", reason="local offer expired") return def cut_off(_signum, _frame): raise SessionEnded("Your foreground time window ended.") signal.signal(signal.SIGALRM, cut_off) signal.setitimer(signal.ITIMER_REAL, max(0.001, deadline - time.monotonic())) try: # Multiple copies of one invitation still share a single slot at the coordinator. with open(args.offer, "rb") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise ValueError("This device file already has a running foreground worker.") from None emit("ready", ramMiB=cap, expiresAt=utc(time.time() + deadline - time.monotonic())) completed, idle = 0, 2 while time.monotonic() + 1 < deadline and (not args.max_jobs or completed < args.max_jobs): # Leave 8 MiB for TLS, JSON and the fixed <48 KiB streaming calculation. need = next((n for n in RAM_CHOICES if n >= 32 and n * MIB >= peak_rss() + 8 * MIB), None) if need is None or need > cap: emit("insufficient-capacity", ramMiB=cap, measuredPeakBytes=peak_rss(), minimumMiB=need) return nonce = secrets.token_hex(32) claim = {"offerId": oid, "nonce": nonce, "needMiB": need, "remainingSeconds": min(7200, max(1, int(deadline - time.monotonic())))} answer = retry_request(client, "/api/v1/worker/claim", token, claim, deadline) offer = answer["offer"] require(offer.get("id") == oid and offer.get("status") == "enrolled" and offer.get("ramMiB") in RAM_CHOICES, "Invalid device grant.") cap = min(cap, offer["ramMiB"]) deadline = min(deadline, time.monotonic() + timestamp(offer["expiresAt"]) - time.time()) if deadline <= time.monotonic(): raise SessionEnded("Your contribution has ended.") signal.setitimer(signal.ITIMER_REAL, max(0.001, deadline - time.monotonic())) lease = answer.get("lease") if lease is None: advertised = answer.get("retryAfterSeconds", 5) delay = min(idle, args.poll_seconds, max(1, advertised), max(0, deadline - time.monotonic())) time.sleep(delay) idle = min(30, idle * 2) continue idle = 2 until = min(deadline, time.monotonic() + timestamp(lease["expiresAt"]) - time.time()) if until <= time.monotonic(): continue emit("claimed", period=lease.get("period"), reservedMiB=lease.get("reservedMiB")) result = reconcile(lease, cap, until) message = {"offerId": oid, "runId": lease["runId"], "nonce": nonce, **result} try: commit = retry_request(client, "/api/v1/worker/finish", token, message, until) except RequestError as err: if err.status == 409: emit("lease-ended") continue raise require(commit.get("accepted") is True and commit.get("receiptId") == lease["runId"], "The coordinator did not acknowledge the result.") completed += 1 emit("completed", period=lease["period"], rows=result["rows"], **result["metrics"]) emit("ended", completedRuns=completed) except RequestError as err: if err.status != 410: raise emit("ended", reason="offer withdrawn or expired") except SessionEnded as end: emit("ended", reason=str(end)) finally: signal.setitimer(signal.ITIMER_REAL, 0) def enrol(client, args): require(1 <= args.minutes <= 120, "Choose 1–120 minutes.") body = {"ramMiB": args.ram_mib, "minutes": args.minutes, "consent": True} manager = Path(args.manager) if manager.exists(): record = load_file(manager) require(record.get("request") == body and record.get("origin") == client.origin, "This manager file belongs to a different offer.") else: record = {"origin": client.origin, "manageToken": secrets.token_hex(32), "request": body} save_file(manager, record, initial=True) reply = client.request("POST", "/api/v1/offers", record["manageToken"], body) offer = reply["offer"] require(offer["status"] == "enrolled", "This offer has ended. Start a fresh enrolment.") record["offerId"] = offer["id"] save_file(manager, record) device = {"origin": client.origin, "offerId": offer["id"], "workerToken": reply["workerToken"], "ramMiB": offer["ramMiB"], "expiresAt": offer["expiresAt"]} if Path(args.offer).exists(): require(load_file(args.offer) == device, "Choose a new device file for this offer.") else: save_file(args.offer, device, initial=True) emit("enrolled", ramMiB=offer["ramMiB"], expiresAt=offer["expiresAt"]) def submit(client, args): path = Path(args.receipt) require(1 <= len(args.period) <= 12 and len(set(args.period)) == len(args.period), "Choose distinct reporting months.") if path.exists(): record = load_file(path) require(record.get("origin") == client.origin and record["request"]["periods"] == args.period and record["request"]["intervalSeconds"] == args.every, "This receipt file belongs to another schedule.") else: body = {"periods": args.period, "startAt": utc(time.time() + args.after), "intervalSeconds": args.every, "consent": True} record = {"origin": client.origin, "token": secrets.token_hex(32), "request": body} save_file(path, record, initial=True) schedule = client.request("POST", "/api/v1/schedules", record["token"], record["request"])["schedule"] record["scheduleId"] = schedule["id"] save_file(path, record) emit("submitted", scheduleId=schedule["id"], runs=len(schedule["runs"]), createdAt=schedule["createdAt"]) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--origin", default=ORIGIN, help="canonical HTTPS service or explicit loopback test origin") commands = parser.add_subparsers(dest="cmd", required=True) start = commands.add_parser("work", help="volunteer in the foreground until your offer expires; Ctrl-C stops") start.add_argument("--offer", type=Path, required=True, help="device file downloaded on enrolment") start.add_argument("--ram-mib", type=int, choices=RAM_CHOICES, help="optionally lower the downloaded limit") start.add_argument("--minutes", type=int, help="optionally shorten this foreground session") start.add_argument("--max-jobs", type=int, default=0, help="stop after this many accepted jobs") start.add_argument("--poll-seconds", type=float, default=30, help="maximum idle polling interval") join = commands.add_parser("enrol", help="create a bounded offer and private files") join.add_argument("--ram-mib", type=int, choices=RAM_CHOICES, required=True) join.add_argument("--minutes", type=int, required=True) join.add_argument("--manager", type=Path, required=True) join.add_argument("--offer", type=Path, required=True) job = commands.add_parser("submit", help="schedule retained NHS reporting periods and exit") job.add_argument("--period", action="append", required=True, choices=KNOWN_RELEASES) job.add_argument("--after", type=int, default=0, help="seconds before the first run") job.add_argument("--every", type=int, default=86400, help="seconds between successive periods, 10–2678400") job.add_argument("--receipt", type=Path, required=True) read = commands.add_parser("receipt", help="retrieve the current durable result") read.add_argument("--receipt", type=Path, required=True) end = commands.add_parser("withdraw", help="revoke a contribution immediately at the coordinator") end.add_argument("--manager", type=Path, required=True) args = parser.parse_args() require(sys.platform in {"darwin", "linux"}, "This pilot worker supports macOS and Linux.") client = Client(args.origin) if args.cmd == "work": work(client, args) elif args.cmd == "enrol": enrol(client, args) elif args.cmd == "submit": submit(client, args) elif args.cmd == "receipt": record = load_file(args.receipt) require(record.get("origin") == client.origin and hex_id(record.get("scheduleId"), 32), "Invalid receipt file.") output = client.request("GET", "/api/v1/schedules/" + record["scheduleId"], record["token"]) print(json.dumps(output, indent=2)) else: record = load_file(args.manager) require(record.get("origin") == client.origin and hex_id(record.get("offerId"), 32), "Invalid manager file.") offer = client.request("DELETE", "/api/v1/offers/" + record["offerId"], record["manageToken"])["offer"] emit("withdrawn", status=offer["status"]) if __name__ == "__main__": try: main() except KeyboardInterrupt: emit("stopped", reason="foreground worker interrupted") except (ValueError, OSError, http.client.HTTPException, KeyError) as exc: print(str(exc), file=sys.stderr) sys.exit(1)