mvd001/cyberset / scripts /graphs /graph_shards.py
mvd001's picture
download
raw
6.86 kB
#!/usr/bin/env python3
"""cyberset Stage 4 shard builder / publisher (resumable).
Consumes finished worker batches (work/graphs/batches|status/b<id>.parquet), writes
data/graphs/code_graph/language=<l>/split=<s>/shard-<seq>.parquet (zstd)
data/graphs/graph_status/part-<seq>.parquet
data/graphs/vocab/{node_type,token,edge_type,repr}.parquet (snapshot of the shared vocab; ids are stable)
then runs scripts/net/publish_step.sh (secret scan -> sync -> verify) and deletes the consumed batch files only if verified.
Progress: work/graphs/shards.jsonl
"""
import argparse, json, os, sqlite3, subprocess, time
from pathlib import Path
import pyarrow as pa, pyarrow.parquet as pq, pyarrow.compute as pc
ROOT = Path(__file__).resolve().parents[2]; W = ROOT / "work/graphs"; D = ROOT / "data/graphs"
LOG = ROOT / "work/graphs/shards.jsonl"
ETYPES = ["AST", "CFG", "CDG", "REACHING_DEF", "CALL", "CONTAINS"]
REPRS = {"AST": "AST", "CFG": "CFG", "CDG": "CDG", "DDG": "REACHING_DEF", "PDG": "CDG+REACHING_DEF", "CALL": "CONTAINS+CALL"}
def log(msg): print(time.strftime("%Y-%m-%d %H:%M:%S"), msg, flush=True)
def records():
return [json.loads(l) for l in open(LOG)] if LOG.exists() else []
def write_vocab():
(D / "vocab").mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(f"file:{W/'vocab.sqlite'}?mode=ro", uri=True, timeout=600)
for t in ("node_type", "token"):
rows = db.execute(f"SELECT id, s FROM {t} ORDER BY id").fetchall()
tb = pa.table({"id": pa.array([r[0] for r in rows], pa.int32()), t: pa.array([r[1] for r in rows], pa.string())})
pq.write_table(tb, D / "vocab" / f".{t}.parquet", compression="zstd"); os.replace(D / "vocab" / f".{t}.parquet", D / "vocab" / f"{t}.parquet")
pq.write_table(pa.table({"id": pa.array(range(len(ETYPES)), pa.int32()), "edge_type": ETYPES,
"joern_edge_label": ETYPES}), D / "vocab/edge_type.parquet", compression="zstd")
pq.write_table(pa.table({"repr": list(REPRS), "edge_types": list(REPRS.values())}), D / "vocab/repr.parquet", compression="zstd")
db.close()
def write_unsupported():
p = D / "graph_status/unsupported_language.parquet"
if p.exists(): return
t = pq.read_table(W / "plan.parquet", columns=["sample_id", "language", "split", "priority_group", "frontend", "pilot", "batch_id"],
filters=[("batch_id", "=", -1)])
t = t.append_column("status", pa.array(["unsupported_language"] * t.num_rows)).append_column("error", pa.array([""] * t.num_rows))
p.parent.mkdir(parents=True, exist_ok=True); pq.write_table(t, p, compression="zstd")
def flush(bids, seq):
"""streaming: one batch in memory at a time, one ParquetWriter per (language, split) partition"""
for old in D.glob(f"code_graph/*/*/shard-{seq:05d}.parquet"): old.unlink()
for old in D.glob(f"code_graph/*/*/.shard-{seq:05d}.parquet"): old.unlink()
writers, files = {}, []
for b in bids:
f = W / "batches" / f"b{b}.parquet"
if not f.exists(): continue
t = pq.read_table(f)
keys = pc.binary_join_element_wise(t["language"], t["split"], "\x1f")
for k in pc.unique(keys).to_pylist():
part = t.filter(pc.equal(keys, k)).drop_columns(["language", "split"])
if k not in writers:
lang, split = k.split("\x1f")
out = D / "code_graph" / f"language={lang}" / f"split={split}" / f"shard-{seq:05d}.parquet"
out.parent.mkdir(parents=True, exist_ok=True)
writers[k] = (pq.ParquetWriter(out.with_name("." + out.name), part.schema, compression="zstd", compression_level=9), out)
writers[k][0].write_table(part, row_group_size=6000)
del t
for w, out in writers.values():
w.close(); os.replace(out.with_name("." + out.name), out); files.append(str(out.relative_to(ROOT)))
st = pa.concat_tables([pq.read_table(W / "status" / f"b{b}.parquet") for b in bids])
(D / "graph_status").mkdir(parents=True, exist_ok=True)
pq.write_table(st, D / "graph_status" / f"part-{seq:05d}.parquet", compression="zstd")
write_vocab(); write_unsupported()
stat = dict(zip(*[x.to_pylist() for x in pc.value_counts(st["status"]).flatten()]))
return dict(seq=seq, batches=bids, n=st.num_rows, statuses=stat, files=files, ts=time.time())
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--min-samples", type=int, default=30000); ap.add_argument("--pilot-only", action="store_true")
ap.add_argument("--loop", action="store_true"); ap.add_argument("--max-batches", type=int, default=60); ap.add_argument("--sleep", type=int, default=120)
a = ap.parse_args()
meta = pq.read_table(W / "plan.parquet", columns=["batch_id", "pilot"]).to_pandas()
meta = meta[meta.batch_id >= 0]
scope = set(meta[meta.pilot].batch_id) if a.pilot_only else set(meta.batch_id)
sizes = meta.groupby("batch_id").size().to_dict()
while True:
recs = records()
consumed = {b for r in recs if r.get("published") for b in r["batches"]}
pending_rec = [r for r in recs if not r.get("published") and not any(x.get("published") and x["seq"] == r["seq"] for x in recs)]
ready = sorted(b for b in scope - consumed if (W / "done" / f"b{b}.json").exists() and (W / "status" / f"b{b}.parquet").exists())[:a.max_batches]
all_done = all((W / "done" / f"b{b}.json").exists() for b in scope)
n_ready = sum(sizes[b] for b in ready)
if pending_rec: # resume an unpublished flush with exactly the same batches
rec = pending_rec[-1]; ready = rec["batches"]; seq = rec["seq"]
elif ready and (n_ready >= a.min_samples or all_done):
seq = max([r["seq"] for r in recs], default=-1) + 1
rec = flush(ready, seq); rec["published"] = False
with open(LOG, "a") as fh: fh.write(json.dumps(rec) + "\n")
log(f"flush seq={seq} batches={len(ready)} samples={rec['n']} {rec['statuses']} files={len(rec['files'])}")
else:
if all_done and not ready: log("all batches in scope consumed; exit"); break
if not a.loop: log(f"nothing to flush ({n_ready} samples ready)"); break
time.sleep(a.sleep); continue
cleanup = [str(W / d / f"b{b}.parquet") for b in ready for d in ("batches", "status")]
r = subprocess.run(["bash", "scripts/graphs/publish_graphs.sh", f"graphs_{seq:05d}"] + cleanup, cwd=ROOT)
if r.returncode == 0:
with open(LOG, "a") as fh: fh.write(json.dumps({"seq": seq, "published": True, "batches": ready, "ts": time.time()}) + "\n")
log(f"published seq={seq}")
else:
log(f"publish failed seq={seq}; retry in 10 min"); time.sleep(600)
if not a.loop and not pending_rec: break
if __name__ == "__main__":
main()

Xet Storage Details

Size:
6.86 kB
·
Xet hash:
ab737a91482d3052a976456243b8773a40ca0f62ef4c117138072f93fdd23b45

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.