File size: 9,245 Bytes
a2222d5 | 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 | """Build data/explorer.sqlite from the scrubbed release tables and the board export.
Usage: build_db.py TABLES_DIR BOARD_DIR TRACE_MANIFEST OUT_SQLITE
TABLES_DIR has prs/reviews/commits.jsonl; BOARD_DIR is the board export (data/manifest.json,
data/messages/*.json.gz); TRACE_MANIFEST is traces/_manifest.jsonl.
"""
import glob, gzip, json, os, re, sqlite3, sys
from datetime import datetime, timezone
CUTOFF = "2026-11-13T10:17:13.000Z" # commit 24cbc04
AUTHOR_LEAD_S, REVIEW_PAD_S = 600, 900
# Links to the run's PR pages become plain "#N" (the UI links those to the explorer); workspace paths are masked.
PR_LINK = re.compile(r"(?:https?://)?huggingface\.co/datasets/HuggingFaceSwarms/[\w.-]+/discussions/(\d+)(?:/files)?")
WS_PATH = re.compile(r"/data/workspaces/[^\s`'\"()<>\[\]]*")
CLEANED = {}
def clean(s, column):
if not s:
return s
out, n1 = PR_LINK.subn(r"#\1", s)
out, n2 = WS_PATH.subn("[WORKSPACE-PATH]", out)
if n1 or n2:
CLEANED[column] = [a + b for a, b in zip(CLEANED.get(column, [0, 0]), [n1, n2])]
return out
PR_REF = re.compile(r"(?:#|\bPR\s*#?\s*|\bpr:|refs/pr/)(\d{1,6})\b", re.I)
def iso(x):
"""Normalise ISO strings and epoch seconds to YYYY-MM-DDTHH:MM:SS.mmmZ (sorts as text)."""
if x is None:
return None
dt = datetime.fromtimestamp(x, timezone.utc) if isinstance(x, (int, float)) else \
datetime.fromisoformat(x.replace("Z", "+00:00"))
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
def epoch(s):
return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
def rows(path):
with open(path) as f:
return [json.loads(line) for line in f]
def main(tables, board, trace_manifest, out):
if os.path.exists(out):
os.remove(out)
db = sqlite3.connect(out)
db.executescript("""
CREATE TABLE commits(idx INT, sha TEXT PRIMARY KEY, parent TEXT, ts TEXT, author TEXT, title TEXT, pr INT,
approvers TEXT, lp_win_rate REAL, standard_error REAL, score_revision TEXT);
CREATE TABLE prs(pr INT PRIMARY KEY, author TEXT, title TEXT, description TEXT, branch TEXT, base_sha TEXT,
opened_ts TEXT, state TEXT, merged_ts TEXT, merged_sha TEXT, head_sha_final TEXT,
close_reason TEXT, n_updates INT, approvers TEXT, first_event_ts TEXT, last_event_ts TEXT);
CREATE TABLE reviews(pr INT, reviewer TEXT, ts TEXT, head_sha TEXT, verdict TEXT, comment TEXT);
CREATE TABLE channels(id INT PRIMARY KEY, name TEXT, description TEXT);
CREATE TABLE messages(id INT PRIMARY KEY, channel TEXT, author TEXT, ts TEXT, thread_id INT, reply_to INT, body TEXT);
CREATE VIRTUAL TABLE messages_fts USING fts5(body, content='messages', content_rowid='id');
CREATE TABLE agents(name TEXT PRIMARY KEY, lane TEXT, trace_records INT, trace_bytes INT, trace_last TEXT,
posts INT, prs_opened INT, prs_merged INT, reviews INT);
CREATE TABLE pr_traces(pr INT, agent TEXT, role TEXT, from_ts TEXT, to_ts TEXT);
CREATE TABLE pr_messages(pr INT, message_id INT, reason TEXT, PRIMARY KEY(pr, message_id)) WITHOUT ROWID;
""")
commits = rows(f"{tables}/commits.jsonl")
db.executemany("INSERT INTO commits VALUES (?,?,?,?,?,?,?,?,?,?,?)", [
(i, c["sha"], (c["parent_shas"] or [None])[0], iso(c["ts"]), c["author"], clean(c["title"], "commits.title"), c["pr"],
json.dumps(c["approvers"]) if c["approvers"] else None,
*((c["score"]["lp_win_rate"], c["score"]["standard_error"], c["score"]["revision"]) if c["score"] else (None,) * 3))
for i, c in enumerate(commits)])
prs = rows(f"{tables}/prs.jsonl")
db.executemany("INSERT INTO prs VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [
(p["pr"], p["author"], clean(p["title"], "prs.title"), clean(p["description"], "prs.description"), p["branch"],
p["base_sha"], iso(p["opened_ts"]), p["state_at_cutoff"], iso(p["merged_ts"]), p["merged_sha"],
p["head_sha_final"], clean(p["close_reason"], "prs.close_reason"),
p["n_updates"], json.dumps(p["approvers"]) if p["approvers"] else None,
iso(p["first_event_ts"]), iso(p["last_event_ts"])) for p in prs])
reviews = rows(f"{tables}/reviews.jsonl")
db.executemany("INSERT INTO reviews VALUES (?,?,?,?,?,?)", [
(r["pr"], r["reviewer"], iso(r["ts"]), r["head_sha"], r["verdict"], clean(r["comment"], "reviews.comment"))
for r in reviews])
# Board export: chunk rows are [id, seq, sender, created_at, body, reply_to, thread_id, edited_at, mentions].
manifest = json.load(open(f"{board}/data/manifest.json"))
people = {p["id"]: p["external_id"] for p in manifest["people"]}
chans = {c["id"]: c["name"] for c in manifest["channels"]}
db.executemany("INSERT INTO channels VALUES (?,?,?)",
[(c["id"], c["name"], c["description"]) for c in manifest["channels"]])
cutoff = manifest["last_at"]
msgs = []
for path in glob.glob(f"{board}/data/messages/*.json.gz"):
cid = int(os.path.basename(path).split("-")[0])
for r in json.load(gzip.open(path)):
body = r[4]
if r[7] and r[7] > cutoff: # same rule as the board reader: show the text as of the cutoff
prev = [v for v in manifest["revisions"].get(str(r[0]), []) if v[2] <= cutoff < v[3]]
body = prev[0][1] if prev else body
msgs.append((r[0], chans[cid], people.get(r[2], f"principal-{r[2]}"), iso(r[3]), r[6] or None, r[5] or None,
clean(body, "messages.body")))
msgs.sort()
db.executemany("INSERT INTO messages VALUES (?,?,?,?,?,?,?)", msgs)
db.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
# Agents: the board's experiment agents (1,000), with their lane and trace size when a trace was released.
traced = {m["agent"]: m for m in map(json.loads, open(trace_manifest))}
roster = sorted({p["external_id"] for p in manifest["people"] if p.get("experiment_agent")} | set(traced))
db.executemany("INSERT INTO agents(name, lane, trace_records, trace_bytes, trace_last) VALUES (?,?,?,?,?)",
[(a, *((traced[a]["lane"], traced[a]["kept"], traced[a]["bytes_out"], traced[a]["last_record"])
if a in traced else (None,) * 4)) for a in roster])
# Trace windows: author [opened - 10 min, merged | closed | cutoff]; each review ts +/- 15 min.
pr_end, windows = {}, []
for p in prs:
end = p["merged_ts"] or (p["last_event_ts"] if p["state_at_cutoff"] == "closed" else CUTOFF)
start = epoch(p["opened_ts"]) - AUTHOR_LEAD_S
pr_end[p["pr"]] = (p["author"], iso(start), iso(end))
windows.append((p["pr"], p["author"], "author", iso(start), iso(end)))
for r in reviews:
t = epoch(r["ts"])
windows.append((r["pr"], r["reviewer"], "reviewer", iso(t - REVIEW_PAD_S), iso(t + REVIEW_PAD_S)))
db.executemany("INSERT INTO pr_traces VALUES (?,?,?,?,?)", windows)
# Messages: those naming the PR number, plus the author's posts inside the author window.
# A mention counts only from the PR's opening until a day after it ended: "#1" in a later post is rarely PR 1.
opened = {p["pr"]: iso(p["opened_ts"]) for p in prs}
late = {pr: iso(epoch(end) + 86400) for pr, (_, _, end) in pr_end.items()}
links = set()
for mid, _, _, ts, _, _, body in msgs:
for n in {int(x) for x in PR_REF.findall(body or "")}:
if n in pr_end and opened[n] <= ts <= late[n]:
links.add((n, mid, "mention"))
db.executemany("INSERT OR IGNORE INTO pr_messages VALUES (?,?,?)", sorted(links))
db.execute("CREATE INDEX messages_author_ts ON messages(author, ts)")
for pr, (author, start, end) in pr_end.items():
db.execute("""INSERT OR IGNORE INTO pr_messages SELECT ?, id, 'author_window' FROM messages
WHERE author = ? AND ts BETWEEN ? AND ?""", (pr, author, start, end))
db.executescript("""
UPDATE agents SET
posts = (SELECT count(*) FROM messages WHERE author = name),
prs_opened = (SELECT count(*) FROM prs WHERE author = name),
prs_merged = (SELECT count(*) FROM prs WHERE author = name AND state = 'merged'),
reviews = (SELECT count(*) FROM reviews WHERE reviewer = name);
CREATE INDEX commits_pr ON commits(pr); CREATE INDEX commits_author ON commits(author);
CREATE INDEX commits_idx ON commits(idx); CREATE INDEX prs_author ON prs(author);
CREATE INDEX reviews_pr ON reviews(pr); CREATE INDEX reviews_reviewer ON reviews(reviewer);
CREATE INDEX messages_thread ON messages(thread_id); CREATE INDEX pr_traces_pr ON pr_traces(pr);
""")
db.commit()
for t in ["commits", "prs", "reviews", "messages", "agents", "pr_traces", "pr_messages"]:
print(t, db.execute(f"SELECT count(*) FROM {t}").fetchone()[0])
print(db.execute("SELECT reason, count(*) FROM pr_messages GROUP BY 1").fetchall())
print("rewritten [PR links, workspace paths] by column:", CLEANED)
db.execute("VACUUM")
db.close()
print("bytes", os.path.getsize(out))
if __name__ == "__main__":
main(*sys.argv[1:])
|