mvd001/cyberset / scripts /graphs /make_graph_docs.py
mvd001's picture
download
raw
16.8 kB
#!/usr/bin/env python3
"""Write data/graphs/README.md, data/graphs/STATS.md and work/graphs/card_section.md (spliced into the bucket README by
scripts/publish/make_card.py) from the published graph shards, graph_status, the plan and the worker metrics."""
import os, glob, json, time, datetime, duckdb
ROOT = "/workspace/security-dataset"; D = f"{ROOT}/data/graphs"; W = f"{ROOT}/work/graphs"
IST = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
ist = lambda t: datetime.datetime.fromtimestamp(t, IST).strftime("%Y-%m-%d %H:%M IST")
now = ist(time.time())
c = duckdb.connect(); c.execute("SET threads=2; SET memory_limit='2GB'")
fmt = lambda n: f"{int(n):,}" if n is not None else "–"
def table(head, rows):
out = ["| " + " | ".join(head) + " |", "|" + "|".join("---:" if i else "---" for i in range(len(head))) + "|"]
for r in rows: out.append("| " + " | ".join(fmt(x) if isinstance(x, int) and not isinstance(x, bool) else (f"{x:,.2f}" if isinstance(x, float) else str(x)) for x in r) + " |")
return "\n".join(out)
q = lambda s: c.execute(s).fetchall()
size = lambda p: sum(os.path.getsize(f) for f in glob.glob(p, recursive=True) if os.path.isfile(f) and "box-store-snap" not in f)
c.execute(f"CREATE VIEW plan AS SELECT sample_id, language, split, primary_source, is_vulnerable, priority_group, pilot, batch_id, frontend FROM '{W}/plan.parquet'")
c.execute(f"CREATE VIEW st AS SELECT * FROM read_parquet('{D}/graph_status/*.parquet', union_by_name=true)")
CG = f"read_parquet('{D}/code_graph/*/*/*.parquet', hive_partitioning=true)"
GROUPS = ["p1_vuln_pairs", "p2_realworld", "p3_bigvul", "p4_juliet", "p5_draper"]
GDESC = {"p1_vuln_pairs": "vulnerable functions + paired fixed versions (PrimeVul, CVEfixes, MoreFixes, CrossVul, Big-Vul)",
"p2_realworld": "other PrimeVul / CVEfixes / MoreFixes / CrossVul functions", "p3_bigvul": "other Big-Vul functions",
"p4_juliet": "Juliet C/C++ (all; vulnerable + good)", "p5_draper": "Draper VDISC (all)"}
tot = q("select count(*) from plan")[0][0]
by_group = q(f"""select p.priority_group, count(*), count(s.sample_id), count(*) filter (where s.status='ok'),
count(*) filter (where s.status='no_graph'), count(*) filter (where s.status in ('parse_failed')), count(*) filter (where s.status='timeout'),
count(*) filter (where s.status='unsupported_language')
from plan p left join st s using(sample_id) group by 1 order by 1""")
by_lang = q(f"""select p.language, count(*), count(s.sample_id), count(*) filter (where s.status='ok'), count(*) filter (where s.status='no_graph'),
count(*) filter (where s.status='parse_failed'), count(*) filter (where s.status='timeout'), count(*) filter (where s.status='unsupported_language')
from plan p left join st s using(sample_id) group by 1 order by 2 desc""")
by_src = q(f"""select p.primary_source, count(*), count(s.sample_id), count(*) filter (where s.status='ok'),
count(*) filter (where s.status='ok' and p.is_vulnerable) from plan p left join st s using(sample_id) group by 1 order by 2 desc""")
by_split = q(f"select split, count(*) filter (where status='ok') from st group by 1 order by 1")
reprs = q(f"select repr, count(*), avg(num_nodes), median(num_nodes), max(num_nodes), avg(num_edges), median(num_edges), max(num_edges), count(*) filter (where num_edges=0) from {CG} group by 1 order by 1") if glob.glob(f"{D}/code_graph/*/*/*.parquet") else []
pairs = q("""select count(distinct p.pair_id) from (select pair_id from read_parquet('%s/data/code/code_sample/*/*.parquet', hive_partitioning=true) where pair_id is not null) p""" % ROOT)[0][0]
ok_pairs = q(f"""with x as (select cs.pair_id, cs.pair_role from read_parquet('{ROOT}/data/code/code_sample/*/*.parquet', hive_partitioning=true) cs
join st using(sample_id) where st.status='ok' and cs.pair_id is not null)
select count(*) from (select pair_id from x group by 1 having count(*) filter (where pair_role='vuln')>0 and count(*) filter (where pair_role='fix')>0)""")[0][0]
files = sorted(glob.glob(f"{D}/code_graph/*/*/*.parquet"))
part = q(f"""select language, split, count(distinct sample_id) from {CG} group by all order by 1, 2""") if files else []
part_rows = [(l, s, n, round(size(f"{D}/code_graph/language={l}/split={s}/*.parquet") / 1e6, 1)) for l, s, n in part]
cg_bytes = size(f"{D}/code_graph/**"); st_bytes = size(f"{D}/graph_status/**"); voc_bytes = size(f"{D}/vocab/**")
n_ok = q("select count(*) from st where status='ok'")[0][0]
vocab = {t: q(f"select count(*) from '{D}/vocab/{t}.parquet'")[0][0] for t in ("node_type", "token")}
# metrics (last record per batch)
M = {}
for l in open(f"{W}/metrics.jsonl"):
d = json.loads(l); M[d["batch"]] = d
pilot_b = {b for (b,) in q("select distinct batch_id from plan where pilot and batch_id >= 0")}
def agg(recs):
out = {}
for d in recs:
a = out.setdefault(d["frontend"], [0, 0, 0.0, 0, 0.0, 0])
a[0] += d["n"]; a[1] += d["ok"]; a[2] += d["seconds"]; a[3] += d["out_bytes"]; a[4] = max(a[4], d["peak_rss_mb"]); a[5] += d["runs"]
return [(k, a[0], a[1], f"{a[1]/a[0]:.1%}", a[0] / a[2], a[3] / max(a[1], 1) / 1024, a[4], a[5]) for k, a in sorted(out.items(), key=lambda x: -x[1][0])]
pilot_rows = agg([M[b] for b in sorted(pilot_b) if b in M])
pil = [M[b] for b in pilot_b if b in M]
pilot_fn = sum(d["n"] for d in pil); pilot_ws = sum(d["seconds"] for d in pil)
full = sorted((d for b, d in M.items() if b not in pilot_b), key=lambda d: d["ts"])
done_b = len([1 for b in M]); all_b = q("select count(distinct batch_id) from plan where batch_id >= 0")[0][0]
rem = q(f"select count(*), count(*) filter (where frontend='c') from plan where batch_id >= 0 and batch_id not in (select unnest({sorted(M) or [-5]}))")[0]
rate = None
if full:
t_end = full[-1]["ts"]; win = [d for d in full if d["ts"] >= t_end - 3600]
span = max(t_end - min(d["ts"] - d["seconds"] for d in win), 1)
rate = sum(d["n"] for d in win) / span
eta = (f"{rem[0]:,} functions in {all_b - done_b:,} batches left; at the last hour's rate of {rate:.1f} functions/s the remainder needs "
f"≈{rem[0]/rate/3600:.1f} h (finish ≈ {ist(time.time() + rem[0]/rate)})") if rate and rem[0] else ("complete" if not rem[0] else "no full-run rate yet")
status_note = "complete" if not rem[0] else "in progress (shards are published as they are built)"
stats = [f"# cyberset graph tier statistics\n\nGenerated {now}. Run status: **{status_note}**. Joern v4.0.645.\n",
"## Coverage by priority group\n", "Processing order = group order (P1 first). `planned` = public `code/code_sample` rows; `processed` = rows with a graph_status record.\n",
table(["group", "planned", "processed", "ok (graphed)", "no_graph", "parse_failed", "timeout", "unsupported_language"], by_group),
"\n" + "\n".join(f"- `{g}`: {GDESC[g]}" for g in GROUPS) + "\n",
"\n## Coverage by language\n", table(["language", "planned", "processed", "ok", "no_graph", "parse_failed", "timeout", "unsupported_language"], by_lang),
"\n## Coverage by primary source\n", table(["primary_source", "planned", "processed", "ok", "ok & vulnerable"], by_src),
f"\nVuln/fix pairs with both sides graphed: {fmt(ok_pairs)} (of {fmt(pairs)} pair_ids in code_sample).\n",
"\n## Graphed functions by split\n", table(["split", "ok"], by_split),
"\n## Graph sizes per representation\n", table(["repr", "rows", "mean nodes", "median nodes", "max nodes", "mean edges", "median edges", "max edges", "rows with 0 edges"], reprs),
"\n## Published files\n", table(["language", "split", "functions", "MB"], part_rows),
f"\nTotals: code_graph {cg_bytes/1e9:.3f} GB in {len(files)} files ({cg_bytes/max(n_ok,1)/1024:.2f} KB per graphed function, all 6 reprs); "
f"graph_status {st_bytes/1e6:.1f} MB; vocab {voc_bytes/1e6:.1f} MB ({fmt(vocab['node_type'])} node types, {fmt(vocab['token'])} tokens).\n",
"\n## Pilot (stratified 20,000 functions)\n",
f"3 concurrent workers, 8-core box (shared with other processes). Per-worker throughput below is functions / batch wall-clock (parse + dataflow overlay + export + encode, including JVM start-ups and failure bisection). "
f"Pilot total: {fmt(pilot_fn)} functions in {pilot_ws/60:.0f} worker-minutes.\n",
table(["frontend", "functions", "ok", "ok rate", "fn/s per worker", "KB per ok fn (zstd)", "peak RSS MB (one JVM)", "joern runs"], pilot_rows),
"\n## Full run\n", f"Batches done: {fmt(done_b)} / {fmt(all_b)}. {eta}.\n",
table(["frontend", "functions", "ok", "ok rate", "fn/s per worker", "KB per ok fn", "peak RSS MB", "joern runs"], agg(full)) if full else ""]
open(f"{D}/STATS.md", "w").write("\n".join(stats) + "\n")
readme = f"""# cyberset — graph tier (`graphs/`)
Code graphs for the functions in the public `code/code_sample` table, built with **Joern v4.0.645** (Apache-2.0,
`joern-cli-linux-x86_64.zip`, sha256 `ea392a3f061be979750d143a2410794204365c7495d5322227620d7e61aefc93`), OpenJDK 21.
Only public rows are graphed (the restricted ID-only index and the separate GPL `code/gpl/` folder are not). Status: **{status_note}**, generated {now}.
See `STATS.md` for counts.
## Layout
| path | content |
|---|---|
| `code_graph/language=<l>/split=<s>/shard-NNNNN.parquet` | graphs, 6 rows per function (one per `repr`), zstd Parquet |
| `graph_status/part-NNNNN.parquet` | one row per processed function: `status` = ok / no_graph / parse_failed / timeout, `error`, `num_nodes` |
| `graph_status/unsupported_language.parquet` | functions in languages without a Joern frontend (objc, scala, lua, shell, perl, …) |
| `vocab/node_type.parquet`, `vocab/token.parquet` | `id → string` for `nodes.type` and `nodes.token` (ids are stable and only grow) |
| `vocab/edge_type.parquet`, `vocab/repr.parquet` | edge type ids, and which edge types each `repr` contains |
Shard numbers are batch-flush sequence numbers, so a partition can have gaps. Read a whole partition or the full
glob: `read_parquet('graphs/code_graph/*/*/*.parquet', hive_partitioning=true)`.
## Schema (`code_graph`)
| column | type | meaning |
|---|---|---|
| `sample_id` | string | join key to `code/code_sample.sample_id` (labels, CVE/CWE, pair_id, split live there) |
| `repr` | string | `AST`, `CFG`, `CDG`, `DDG`, `PDG`, `CALL` |
| `tool`, `tool_version` | string | `joern`, `v4.0.645` |
| `frontend` | string | Joern frontend used (`c`, `javasrc`, `jssrc`, `pythonsrc`, `php`, `golang`, `rubysrc`, `csharpsrc`, `kotlin`, `swiftsrc`, `rust`) |
| `priority_group` | string | processing group (see below) |
| `num_nodes`, `num_edges` | int32 | size of this repr |
| `nodes` | list<struct<idx int32, type int16, token int32, line int32>> | node list of this repr |
| `edges` | list<fixed_size_list<int32, 3>> | `[src, dst, etype]`, src/dst are **positions in this row's `nodes` list** |
| `graph_blob_uri` | string | always null (all graphs are inline) |
| `language`, `split` | partition columns | same values as `code_sample` |
**Nodes.** `type` → `vocab/node_type` (Joern node label: METHOD, CALL, IDENTIFIER, LITERAL, CONTROL_STRUCTURE, …).
`token` → `vocab/token`: CALL → callee name (operators as `<operator>.addition` etc.), IDENTIFIER/LITERAL/PARAM/LOCAL → type full name
(not the variable name or literal value; keeps the vocabulary closed), CONTROL_STRUCTURE → kind (IF, WHILE, …), FIELD_IDENTIFIER → field name,
METHOD/METHOD_REF → method name, otherwise empty string. `line` is relative to the first line of the function's code in `code_sample`
(1 = first line; -1 = unknown). `idx` is the node's index in the function's full node list, so the same node has the same `idx` in every repr
of a function (use it to align reprs).
**Edges / reprs.** Edge type ids: AST=0, CFG=1, CDG=2, REACHING_DEF=3 (data dependence), CALL=4, CONTAINS=5.
| repr | edges | node list |
|---|---|---|
| AST | AST | every AST node of the function's method(s) |
| CFG | CFG | CFG endpoints + METHOD node(s) |
| CDG | CDG | CDG endpoints + METHOD node(s) |
| DDG | REACHING_DEF | endpoints + METHOD node(s) |
| PDG | CDG + REACHING_DEF | endpoints + METHOD node(s) |
| CALL | CONTAINS (method → call site) + CALL (call site → callee METHOD) | endpoints; callees are METHOD stub nodes (`idx` ≥ AST size, line -1) |
CFG/CDG/REACHING_DEF come from Joern's default overlays plus the `dataflowOss` layer. Calls to `<operator>.*` are excluded from CALL.
## How the graphs are built
Each function is written to its own file, then `joern-parse` runs over a batch of files (≤1000) and
`scripts/graphs/export_graphs.sc` exports, for each file, the AST of every non-wrapper method (Joern's `<global>`, `<module>`,
`:program`, `<init>`, `<clinit>` are dropped) and the edges between those nodes. A function with nested lambdas/closures yields one graph
that contains all of them. Minimal wrappers make bare functions parseable (line numbers are corrected for them):
Java/C# methods → `class __W {{…}}` (unless the code already starts with package/import/using/a type declaration), Go → `package p`,
PHP → `<?php` (and `class __W {{…}}` for methods with visibility modifiers), JS/TS class-method snippets → `class __W {{…}}`, Python → dedent,
Rust → a one-crate Cargo project with one module per function. C/C++ functions are parsed by the C or C++ dialect according to
`language_detail`; when that gives no method (the source labels mix the two) the file is retried in the other dialect.
If a batch fails (frontend crash or timeout: 120 s + 0.5 s/file for parse, twice that for export) it is bisected down to single files, so one
bad file only affects itself. Code: `scripts/graphs/` (`plan_graphs.py`, `graph_worker.py`, `export_graphs.sc`, `graph_shards.py`).
## Priority groups and processing order
| group | content |
|---|---|
""" + "\n".join(f"| `{g}` | {GDESC[g]} |" for g in GROUPS) + f"""
A stratified 20,000-function pilot (C/C++ 11,000, then JS/PHP/Python/Java 1,500 each, Go 1,000, Ruby 700, TS 400, Rust/C# 300, Kotlin/Swift 150;
≈25% complete vuln/fix pairs; `graph_status.pilot = true`) ran first, followed by P1…P5. Juliet's and Draper's vulnerable functions are in
P4/P5, not P1 (synthetic / static-analyser labels).
## Example
```python
import duckdb
g = duckdb.sql(\"\"\"
SELECT g.sample_id, g.num_nodes, g.nodes, g.edges, c.is_vulnerable, c.cwe_ids
FROM read_parquet('hf://buckets/mvd001/cyberset/graphs/code_graph/language=c_cpp/split=train/*.parquet') g
JOIN read_parquet('hf://buckets/mvd001/cyberset/code/code_sample/language=c_cpp/*.parquet') c USING (sample_id)
WHERE g.repr = 'PDG' LIMIT 100\"\"\").df()
# node feature = (type, token) ids; edge_index = [[s for s,d,t in e], [d for s,d,t in e]]
```
## Limitations
- **Function-level, not whole-program.** Each function is parsed alone (no headers, includes or build config), so types are often unresolved
(`ANY`), macros are not expanded, and CALL edges point to stub METHOD nodes named after the callee rather than to callee bodies.
REACHING_DEF is intra-procedural.
- **`no_graph` rows** are functions for which Joern found no method definition. These are mostly broken source records (CVEfixes JS
"functions" that are fragments of minified bundles; Big-Vul diff residue with two signatures; constructors and test macros outside
their class), plus some C++ that CDT cannot parse without headers. `parse_failed`/`timeout` rows are frontend crashes (some Kotlin/C#/PHP
files trigger Joern AST-parent assertions) or runs over the time limit. See `graph_status` and `STATS.md`.
- **Tokens are coarse.** Identifiers and literals carry their type, not their name or value. Use `code_sample.code` + `line` for lexical features.
- Graph sizes depend on the frontend: the per-language ASTs are not normalised to one cross-language schema beyond Joern's node labels.
- Juliet and Draper graphs inherit those datasets' label caveats (see the root card).
"""
open(f"{D}/README.md", "w").write(readme)
grp_ok = {r[0]: r[3] for r in by_group}
card = f"""## Graph tier (`graphs/`)
Joern **v4.0.645** (Apache-2.0) code graphs for the public `code/code_sample` functions: six representations per function
(AST, CFG, CDG, DDG, PDG, CALL) as integer node lists (`type`, `token` vocab ids, relative line) and int32 `[src, dst, etype]` edge lists,
zstd Parquet partitioned by `language` and `split`, joined on `sample_id`. Vocabularies are in `graphs/vocab/`; per-function outcomes are in
`graphs/graph_status/`. Status as of {now}: **{status_note}**. {fmt(n_ok)} functions graphed ({cg_bytes/1e9:.2f} GB):
""" + table(["group", "planned", "graphed"], [(r[0], r[1], r[3]) for r in by_group]) + f"""
Details: `graphs/README.md` (schema, reprs, construction, limitations) and `graphs/STATS.md`.
"""
open(f"{W}/card_section.md", "w").write(card)
print(f"ok={n_ok} files={len(files)} cg={cg_bytes/1e9:.3f}GB; {eta}")

Xet Storage Details

Size:
16.8 kB
·
Xet hash:
f206a6021d2cbca7b0435ba4a8a3eb3797a824d7f35701324cd985fe0f360d23

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