"""Perf runs as atproto records in okami.mom's repo, the store every page reads. Each run is one `pet.nekomimi.albedo.perf.run` record with rkey = commit sha (`-2`, ... when a commit runs again). Records hold strings and integers only, since the atproto data model has no floats: `summary` is the JSON text of the numbers pages compare, and the full results.json files are blobs. Reads are public (getRecord, listRecords and getBlob send CORS headers); writes use an app password session. The `albedo-perf` site draws them. """ from __future__ import annotations import json from pathlib import Path import tomllib import urllib.error import urllib.parse import urllib.request DID = "did:plc:3rwz3xfw2crswgifqgc3g7zh" HANDLE = "okami.mom" COLLECTION = "pet.nekomimi.albedo.perf.run" SITE = "albedo-perf" SITE_URL = f"https://sites.wisp.place/{HANDLE}/{SITE}/" USER_AGENT = "albedo-perf (+https://tangled.org/okami.mom/albedo)" def run_url(rkey): """The run's page: the short commit plus the rkey's rerun suffix, if any.""" commit, _, rerun = rkey.partition("-") return f"{SITE_URL}{commit[:7]}{'-' + rerun if rerun else ''}/" def http(url, body=None, headers=None, method=None): request = urllib.request.Request( url, data=body, method=method, headers={"User-Agent": USER_AGENT, **(headers or {})}, ) with urllib.request.urlopen(request, timeout=60) as response: return response.read() def pds(): """The PDS endpoint named in okami.mom's DID document.""" document = json.loads(http(f"https://plc.directory/{DID}")) return next( service["serviceEndpoint"] for service in document["service"] if service["id"] == "#atproto_pds" ) def is_main_push(record): return record["event"] == "push" and record["ref"] in ("main", "refs/heads/main") ACCEPTED = Path(__file__).parents[1] / "accepted.toml" def accepted(path=ACCEPTED): """accepted.toml as {metric: {commit: {value, reason}}}.""" return tomllib.loads(Path(path).read_text()) def baseline(records, accepted): """Each gated metric's baseline: the metric from the newest of `records` (main ancestors, newest first) that passed it, or that accepted.toml names for it with the value it measured. A regressed metric never becomes a baseline by itself, and an improved one only once the next newer record improved on the same baseline too: a one-off low reading would otherwise fail every commit after it. None when no record has a usable metric.""" gated, base, wanted, newer = {}, None, None, {} for record in records: metrics = json.loads(record["summary"])["gated"] wanted = wanted or set(metrics) for name, metric in metrics.items(): entry = accepted.get(name, {}).get(record["commit"]) verdict = metric.get("verdict") usable = ( verdict == "pass" or (verdict == "improved" and newer.get(name) == "improved") or (entry and entry["value"] == metric["value"]) ) newer[name] = verdict if name in gated or not usable: continue gated[name] = {**metric, "commit": record["commit"]} base = base or record["commit"] if wanted <= set(gated): break return {"commit": base, "gated": gated} if gated else None class Repo: def __init__(self, password=None): self.endpoint = pds() self.token = None if password is not None: session = self.call( "com.atproto.server.createSession", {"identifier": HANDLE, "password": password}, ) self.token = session["accessJwt"] def url(self, method, **params): return f"{self.endpoint}/xrpc/{method}?{urllib.parse.urlencode(params)}" def call(self, method, payload): headers = {"Content-Type": "application/json"} if self.token: headers["Authorization"] = f"Bearer {self.token}" body = json.dumps(payload).encode() return json.loads( http(f"{self.endpoint}/xrpc/{method}", body, headers) or b"{}" ) def runs(self): """Every run record's value with its rkey, in repo order.""" runs, cursor = [], None while True: params = {"repo": DID, "collection": COLLECTION, "limit": 100} if cursor: params["cursor"] = cursor page = json.loads(http(self.url("com.atproto.repo.listRecords", **params))) for item in page["records"]: runs.append({**item["value"], "rkey": item["uri"].rsplit("/", 1)[1]}) cursor = page.get("cursor") if not cursor or not page["records"]: return runs def exists(self, rkey): try: http( self.url( "com.atproto.repo.getRecord", repo=DID, collection=COLLECTION, rkey=rkey, ) ) except urllib.error.HTTPError as error: if error.code == 400 and b"RecordNotFound" in error.read(): return False raise return True def blob(self, reference): cid = reference["ref"]["$link"] return http(self.url("com.atproto.sync.getBlob", did=DID, cid=cid)) def upload(self, data): headers = { "Content-Type": "application/json", "Authorization": f"Bearer {self.token}", } response = http( f"{self.endpoint}/xrpc/com.atproto.repo.uploadBlob", data, headers ) return json.loads(response)["blob"] def claim(self, commit, make_value): """Create a record under the first free rkey and return the rkey. createRecord with an explicit rkey fails when the record exists, so two runs of one commit never share a record. """ for attempt in range(1, 100): rkey = commit if attempt == 1 else f"{commit}-{attempt}" if self.exists(rkey): continue payload = { "repo": DID, "collection": COLLECTION, "rkey": rkey, "record": {"$type": COLLECTION, **make_value(rkey)}, } try: self.call("com.atproto.repo.createRecord", payload) except urllib.error.HTTPError: if self.exists(rkey): continue raise return rkey raise RuntimeError(f"no free record key for {commit}")