"""Publish verified live review metrics and idempotent cumulative token totals. The textfile directory is the only writable host mount in the trusted metrics helper. Its ledger is authoritative; writing it before the .prom file lets a retry finish an interrupted publication without counting the same run twice. """ import argparse import fcntl import json import os from pathlib import Path import re import tempfile SHA = re.compile(r"[0-9a-f]{40}\Z") POSITIVE = re.compile(r"[1-9][0-9]*\Z") VERSION = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+\Z") TOTAL_NAMES = ("review_input_tokens_total", "review_output_tokens_total") def atomic_write(path, data, mode=0o600): path = Path(path) with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, prefix=path.name + ".", delete=False) as stream: stream.write(data) temp = Path(stream.name) os.chmod(temp, mode) os.replace(temp, path) def total_lines(totals): return ("# HELP review_input_tokens_total Measured live input tokens since counter activation.\n" "# TYPE review_input_tokens_total counter\n" f'review_input_tokens_total{{mode="live"}} {totals["input"]}\n' "# HELP review_output_tokens_total Measured live output tokens since counter activation.\n" "# TYPE review_output_tokens_total counter\n" f'review_output_tokens_total{{mode="live"}} {totals["output"]}\n') def load_ledger(path): if not path.exists(): return {"schema_version": 1, "totals": {"input": 0, "output": 0}, "runs": {}} ledger = json.loads(path.read_text(encoding="utf-8")) if ledger.get("schema_version") != 1 or not isinstance(ledger.get("runs"), dict): raise ValueError("Invalid token ledger") totals = ledger.get("totals", {}) if any(type(totals.get(key)) is not int or totals[key] < 0 for key in ("input", "output")): raise ValueError("Invalid token ledger totals") return ledger def publish(directory, review_path=None, bundle_path=None, gauge_path=None, version=None): directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) with (directory / ".final-project-metrics.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) ledger_path = directory / "final-project-token-ledger.json" prometheus_path = directory / "final-project.prom" ledger = load_ledger(ledger_path) if review_path is None: # An honest zero baseline for cumulative totals. Existing per-run # gauges are retained as historical last-run values. if not ledger_path.exists(): existing = prometheus_path.read_text(encoding="utf-8") if prometheus_path.exists() else "" atomic_write(ledger_path, json.dumps(ledger, sort_keys=True, indent=2) + "\n") atomic_write(prometheus_path, existing.rstrip("\n") + "\n" + total_lines(ledger["totals"]), 0o644) elif prometheus_path.exists(): os.chmod(prometheus_path, 0o644) return ledger review = json.loads(Path(review_path).read_text(encoding="utf-8")) bundle = json.loads(Path(bundle_path).read_text(encoding="utf-8")) if bundle.get("mode") != "live" or review.get("mode") != "live" or review.get("model_id") in (None, "fixture-model"): raise ValueError("Only a verified real-model live run may update totals") if review.get("source_commit") != bundle.get("source_commit") or not SHA.fullmatch(str(bundle.get("source_commit"))): raise ValueError("Review and bundle source identities differ") if any(not POSITIVE.fullmatch(str(bundle.get(key))) for key in ("run_id", "attempt")): raise ValueError("Invalid Actions run identity") if not VERSION.fullmatch(str(version)): raise ValueError("Release version required for live metrics") if review.get("status") != "corrected": raise ValueError("Live demo requires a corrected review") counts = {} for key in ("input_tokens", "output_tokens"): value = review.get(key) if value is not None and (type(value) is not int or value < 0): raise ValueError("Invalid measured token count") counts[key] = value gauges = Path(gauge_path).read_text(encoding="utf-8") for key in ("input_tokens", "output_tokens"): available = int(counts[key] is not None) if f'review_{key}_available{{mode="live"}} {available}\n' not in gauges: raise ValueError("Gauge availability disagrees with review") if counts[key] is not None and f'review_{key}{{mode="live"}} {counts[key]}\n' not in gauges: raise ValueError("Gauge count disagrees with review") key = ":".join((bundle["source_commit"], str(bundle["run_id"]), str(bundle["attempt"]))) event = {"source_commit": bundle["source_commit"], "run_id": str(bundle["run_id"]), "attempt": str(bundle["attempt"]), "version": version, "input_tokens": counts["input_tokens"], "output_tokens": counts["output_tokens"]} if key in ledger["runs"]: if ledger["runs"][key] != event: raise ValueError("Retry disagrees with recorded run") else: ledger["runs"][key] = event for token_key, total_key in (("input_tokens", "input"), ("output_tokens", "output")): if counts[token_key] is not None: ledger["totals"][total_key] += counts[token_key] # Commit the ledger first. An interrupted publication can safely retry. atomic_write(ledger_path, json.dumps(ledger, sort_keys=True, indent=2) + "\n") info = f'review_release_info{{mode="live",version="{version}"}} 1\n' atomic_write(prometheus_path, gauges.rstrip("\n") + "\n" + total_lines(ledger["totals"]) + info, 0o644) return ledger def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--metrics-dir", required=True) parser.add_argument("--initialize", action="store_true") parser.add_argument("--review") parser.add_argument("--bundle") parser.add_argument("--gauges") parser.add_argument("--version") args = parser.parse_args() if args.initialize: if any((args.review, args.bundle, args.gauges, args.version)): parser.error("--initialize takes no review inputs") result = publish(args.metrics_dir) else: if not all((args.review, args.bundle, args.gauges, args.version)): parser.error("review, bundle, gauges and version are required") result = publish(args.metrics_dir, args.review, args.bundle, args.gauges, args.version) print(json.dumps({"totals": result["totals"], "recorded_runs": len(result["runs"])})) if __name__ == "__main__": main()