File size: 13,777 Bytes
902d2bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""The archive: every evaluated kernel with its parent. An append-only ledger, and a rebuilt SQLite copy."""
from __future__ import annotations
import collections
import fcntl
import hashlib
import json
import math
import os
import pathlib
import re
import sqlite3
import tempfile
import threading
import time
from .checks import precision
# One run of one problem lives in <root>/<problem>/<run>/: ledger.jsonl (append-only), one folder
# per candidate (solution.json, eval.json), sessions/ (transcripts) and archive.sqlite. A
# candidate's files are written first and its ledger row last, so a row always points to complete
# files. The SQLite database is a copy rebuilt from the ledger; agents only read it. Failed tries
# are rows too (correct = 0), so agents can see dead ends; only correct kernels are tree nodes.
EVAL_FIELDS = ("compiled", "correct", "fail_class", "n_workloads", "n_passed", "t_k_ms_mean",
"reward", "reward_basis", "sol_score", "flags")
COLUMNS = {
"candidates": ("cand_id TEXT PRIMARY KEY", "parent_id TEXT", "ts TEXT", "language TEXT",
"direction TEXT", "notes TEXT", "compiled INTEGER", "correct INTEGER",
"fail_class TEXT", "n_workloads INTEGER", "n_passed INTEGER",
"t_k_ms_mean REAL", "reward REAL", "reward_basis TEXT", "sol_score REAL",
"flags TEXT", "precision TEXT", "robustness TEXT", "sanitizer TEXT",
"counted INTEGER"),
"evaluation": ("cand_id TEXT", "workload_idx INTEGER", "workload TEXT", "axes TEXT",
"status TEXT", "t_k_ms REAL"),
"lineage": ("cand_id TEXT PRIMARY KEY", "root_id TEXT", "depth INTEGER", "n_children INTEGER",
"n_descendants INTEGER", "n_correct_descendants INTEGER",
"best_descendant_reward REAL"),
}
VIEWS = ("CREATE VIEW incumbent AS SELECT * FROM candidates WHERE counted = 1"
" ORDER BY reward DESC LIMIT 1",)
_READ_ACTIONS = frozenset({20, 21, 31, 33}) # SQLite authorizer: READ, SELECT, FUNCTION, RECURSIVE
_PRAGMA, _PRAGMAS_OK = 19, frozenset({"table_info", "table_list", "index_list"})
_CAND_ID = re.compile(r"[0-9a-f]{12}")
def cand_id_of(problem_id: str, sol_text: str) -> str:
"""The candidate id: a hash of the problem and the exact solution text (a replay adds no copy)."""
return hashlib.sha1((problem_id + "\n" + sol_text).encode("utf-8", "surrogatepass")).hexdigest()[:12]
def is_cand_id(s) -> bool:
return isinstance(s, str) and _CAND_ID.fullmatch(s) is not None
def _authorize(action, arg1, arg2, dbname, source):
if action in _READ_ACTIONS or (action == _PRAGMA and (arg1 or "").lower() in _PRAGMAS_OK):
return sqlite3.SQLITE_OK
return sqlite3.SQLITE_DENY
def _sql_value(v):
if isinstance(v, bool):
return int(v)
return json.dumps(v) if isinstance(v, (list, dict)) else v
def _counted(r, policy):
"""A correct kernel counts unless a check failed it; its measured numbers never change."""
if not r.get("correct") or {"impossibly_fast", "below_sol"} & set(r.get("flags") or ()):
return 0
if r.get("robustness") == "NOT_ROBUST" or r.get("sanitizer") == "errors":
return 0
return 1 if precision.counts(r.get("precision"), r.get("robustness"), policy) else 0
def _lineage(rows):
"""Per node: root, depth, children, and its subtree's size, correct count and best reward."""
kids, out = collections.defaultdict(list), {}
for r in rows: # ledger order: a parent comes before its children
up = out.get(r.get("parent_id"))
if up is not None:
kids[r["parent_id"]].append(r)
out[r["cand_id"]] = {"root_id": up["root_id"] if up else r["cand_id"],
"depth": up["depth"] + 1 if up else 0}
for r in reversed(rows): # children first: sum each subtree
o, best = out[r["cand_id"]], []
o.update(n_children=len(kids[r["cand_id"]]), n_descendants=0, n_correct_descendants=0)
for k in kids[r["cand_id"]]:
ko = out[k["cand_id"]]
o["n_descendants"] += 1 + ko["n_descendants"]
o["n_correct_descendants"] += int(bool(k.get("correct"))) + ko["n_correct_descendants"]
best += [v for v in (k.get("reward") if k.get("counted") else None,
ko["best_descendant_reward"]) if v is not None]
o["best_descendant_reward"] = max(best) if best else None
return out
class Archive:
"""One run of one problem. Safe for several children (threads or processes) at once."""
def __init__(self, root, problem_id, run_id, precision_policy="paper"):
self.problem_id, self.run_id, self.policy = problem_id, run_id, precision_policy
self.dir = os.path.join(root, problem_id, run_id)
self.ledger = os.path.join(self.dir, "ledger.jsonl")
self.db = os.path.join(self.dir, "archive.sqlite")
for sub in ("candidates", "sessions", "work", "checks"):
os.makedirs(os.path.join(self.dir, sub), exist_ok=True)
self._lock, self._rows, self._evals = threading.RLock(), None, {}
# -- writing ------------------------------------------------------------------------------
def _append(self, row):
row = dict(row, ts=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
with self._lock, open(self.ledger, "a", encoding="utf-8") as f:
fcntl.flock(f, fcntl.LOCK_EX)
f.write(json.dumps(row) + "\n")
f.flush()
fcntl.flock(f, fcntl.LOCK_UN)
self.rebuild()
def record(self, sol_text, result, parent_id=None, **fields) -> str:
"""Store one evaluated candidate: its files first, then its ledger row (the commit)."""
cid = cand_id_of(self.problem_id, sol_text)
d = os.path.join(self.dir, "candidates", cid)
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "solution.json"), "w", encoding="utf-8") as f:
f.write(sol_text)
with open(os.path.join(d, "eval.json"), "w", encoding="utf-8") as f:
json.dump({k: v for k, v in result.items() if k != "output"}, f, indent=1, default=str)
row = {"kind": "eval", "cand_id": cid, "parent_id": parent_id or None}
row.update((k, result.get(k)) for k in EVAL_FIELDS)
row.update(fields)
self._append(row)
return cid
def add_check(self, cand_id, check, verdict):
"""A later check verdict (robustness, sanitizer) for a stored candidate."""
self._append({"kind": "check", "cand_id": cand_id, "check": check, "verdict": verdict})
def save_session(self, name, records):
with open(os.path.join(self.dir, "sessions", name + ".jsonl"), "w", encoding="utf-8") as f:
f.writelines(json.dumps(r, default=str) + "\n" for r in records)
# -- the rebuilt copy -----------------------------------------------------------------------
def rebuild(self) -> list:
"""Rebuild the SQLite copy from the ledger (a temporary file, then swapped in)."""
with self._lock:
cands, checks = collections.OrderedDict(), collections.defaultdict(dict)
lines = []
if os.path.exists(self.ledger):
with open(self.ledger, encoding="utf-8") as f:
lines = f.read().splitlines()
for line in lines:
try:
row = json.loads(line)
except ValueError:
continue # a torn last line: not committed
cid = row.get("cand_id") if isinstance(row, dict) else None
if not cid:
continue
if row.get("kind") == "check":
checks[cid][row.get("check")] = row.get("verdict")
elif cid not in cands: # the first record of a candidate decides
p = row.get("parent_id")
row["parent_id"] = p if p in cands and cands[p].get("correct") else None
cands[cid] = row
rows = []
for cid, r in cands.items():
r = dict(r, **{k: v for k, v in checks[cid].items() if k in ("robustness", "sanitizer")})
r["counted"] = _counted(r, self.policy)
rows.append(r)
self._write_db(rows, _lineage(rows))
self._rows = rows
return rows
def _workloads(self, cid):
if cid not in self._evals:
try:
with open(os.path.join(self.dir, "candidates", cid, "eval.json"), encoding="utf-8") as f:
ev = json.load(f)
except (OSError, ValueError):
ev = {}
self._evals[cid] = [(cid, i, r.get("uuid"), json.dumps(r.get("axes")), r.get("status"),
r.get("latency_ms")) for i, r in enumerate(ev.get("rows") or [])]
return self._evals[cid]
def _write_db(self, rows, lin):
fd, tmp = tempfile.mkstemp(prefix=".archive-", suffix=".sqlite", dir=self.dir)
os.close(fd)
conn = sqlite3.connect(tmp)
try:
for table, cols in COLUMNS.items():
conn.execute("CREATE TABLE %s (%s)" % (table, ", ".join(cols)))
for view in VIEWS:
conn.execute(view)
names = [c.split()[0] for c in COLUMNS["candidates"]]
conn.executemany("INSERT INTO candidates VALUES (%s)" % ",".join("?" * len(names)),
[[_sql_value(r.get(c)) for c in names] for r in rows])
conn.executemany("INSERT INTO evaluation VALUES (?,?,?,?,?,?)",
[w for r in rows for w in self._workloads(r["cand_id"])])
lcols = [c.split()[0] for c in COLUMNS["lineage"]][1:]
conn.executemany("INSERT INTO lineage VALUES (?,?,?,?,?,?,?)",
[[cid] + [o[c] for c in lcols] for cid, o in lin.items()])
conn.commit()
finally:
conn.close()
os.replace(tmp, self.db)
# -- reading ------------------------------------------------------------------------------
def candidates(self) -> list:
return self._rows if self._rows is not None else self.rebuild()
def get(self, cand_id):
return next((r for r in self.candidates() if r["cand_id"] == cand_id), None)
def find_key(self, key):
"""An earlier candidate of this run with the same code (harness.solution_key), if any."""
return next((r for r in self.candidates() if key and r.get("key") == key), None)
def solution_path(self, cand_id) -> str:
return os.path.join(self.dir, "candidates", cand_id, "solution.json")
def solution(self, cand_id):
if not is_cand_id(cand_id) or self.get(cand_id) is None:
return None
with open(self.solution_path(cand_id), encoding="utf-8") as f:
return json.load(f)
def nodes(self) -> list:
"""The tree nodes: correct kernels that count."""
return [r for r in self.candidates() if r.get("counted")]
def best(self, pending_ok=False):
"""The best node by reward. pending_ok: also a kernel still waiting for its checks."""
rows = [r for r in self.candidates() if r.get("counted") or (
pending_ok and _counted(dict(r, robustness=r.get("robustness") or "ROBUST"), self.policy))]
return max(rows, key=lambda r: r.get("reward") or 0.0, default=None)
def query(self, sql, limit=200) -> dict:
"""Read-only SQL over this run's archive: a read-only connection plus an authorizer."""
if not os.path.exists(self.db):
self.rebuild()
conn = sqlite3.connect(pathlib.Path(self.db).resolve().as_uri() + "?mode=ro", uri=True)
try:
conn.execute("PRAGMA query_only = ON")
conn.set_authorizer(_authorize)
cur = conn.execute(sql)
rows = cur.fetchmany(limit + 1)
return {"columns": [c[0] for c in cur.description or ()],
"rows": [list(r) for r in rows[:limit]], "truncated": len(rows) > limit}
except Exception as e: # sqlite errors, a second statement, a denied write
return {"error": "sql_error", "detail": str(e)[:300]}
finally:
conn.close()
# -- the tree baseline (the A/B arm; the final run's controller did not use it) ------------------
def select_tree(nodes, want, pruned, c=0.7) -> list:
"""UCB-style pick: reward / best + c * sqrt(ln(|A| + 1) / (children + 1)), over live nodes."""
visits = collections.Counter(n.get("parent_id") for n in nodes if n.get("parent_id"))
live = [n for n in nodes if n["cand_id"] not in pruned]
best = max([n.get("reward") or 0.0 for n in live] + [1e-12])
def ucb(n):
explore = math.sqrt(math.log(len(nodes) + 1) / (visits[n["cand_id"]] + 1))
return (n.get("reward") or 0.0) / best + c * explore
return sorted(live, key=ucb, reverse=True)[:want]
def prune_tree(nodes, pruned, margin, grace) -> None:
"""Prune a node that has had `grace` children and is still more than `margin` below the best."""
if not nodes:
return
best = max(n.get("reward") or 0.0 for n in nodes)
visits = collections.Counter(n.get("parent_id") for n in nodes if n.get("parent_id"))
for n in nodes:
r = n.get("reward") or 0.0
if n["cand_id"] not in pruned and visits[n["cand_id"]] >= grace and r < best - margin:
pruned.add(n["cand_id"])
|