File size: 12,499 Bytes
f3ad3db | 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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | #!/usr/bin/env python3
# Copyright 2026 SyzPilot Authors
# SPDX-License-Identifier: Apache-2.0
"""Convert the paired SyzPilot corpus into deterministic Parquet shards."""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import math
import os
from pathlib import Path
import re
import sys
import time
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
SCHEMA_VERSION = 1
ID_PATTERN = re.compile(r"^[0-9a-f]{40}$")
SCHEMA = pa.schema(
[
pa.field("id", pa.string(), nullable=False),
pa.field("program", pa.string(), nullable=False),
pa.field("coverage", pa.string(), nullable=False),
pa.field("program_size_bytes", pa.int32(), nullable=False),
pa.field("coverage_size_bytes", pa.int32(), nullable=False),
pa.field("coverage_count", pa.int32(), nullable=False),
]
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Convert dataset_224w/programs and dataset_224w/coverages into "
"paired, deterministically ordered Parquet shards."
)
)
parser.add_argument(
"--source",
type=Path,
default=Path.home() / "datasets" / "dataset_224w",
help="Directory containing programs/ and coverages/.",
)
parser.add_argument(
"--output",
type=Path,
default=Path.cwd(),
help="Dataset repository directory.",
)
parser.add_argument(
"--rows-per-shard",
type=int,
default=5_000,
help="Maximum rows in each Parquet shard.",
)
parser.add_argument(
"--row-group-rows",
type=int,
default=512,
help="Rows in each Parquet row group.",
)
parser.add_argument(
"--workers",
type=int,
default=32,
help="Threads used to read pairs of source files.",
)
parser.add_argument(
"--compression-level",
type=int,
default=3,
help="Zstandard compression level.",
)
parser.add_argument(
"--limit",
type=int,
help="Convert only the first N sorted IDs (for validation runs only).",
)
args = parser.parse_args()
if args.rows_per_shard <= 0:
parser.error("--rows-per-shard must be positive")
if args.row_group_rows <= 0:
parser.error("--row-group-rows must be positive")
if args.workers <= 0:
parser.error("--workers must be positive")
if args.limit is not None and args.limit <= 0:
parser.error("--limit must be positive")
return args
def file_sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
def write_json_atomic(path: Path, value: Any) -> None:
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as handle:
json.dump(value, handle, indent=2, sort_keys=True)
handle.write("\n")
os.replace(temporary, path)
def list_source_ids(directory: Path) -> list[str]:
if not directory.is_dir():
raise FileNotFoundError(f"source directory does not exist: {directory}")
names: list[str] = []
invalid: list[str] = []
with os.scandir(directory) as entries:
for entry in entries:
if not entry.is_file(follow_symlinks=False):
continue
if not ID_PATTERN.fullmatch(entry.name):
invalid.append(entry.name)
if len(invalid) >= 10:
break
names.append(entry.name)
if invalid:
joined = ", ".join(repr(name) for name in invalid)
raise ValueError(f"unexpected source filenames in {directory}: {joined}")
return names
def count_lines(data: bytes) -> int:
if not data:
return 0
return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)
def read_pair(
item: tuple[str, Path, Path],
) -> tuple[str, str, str, int, int, int]:
sample_id, program_dir, coverage_dir = item
program_bytes = (program_dir / sample_id).read_bytes()
coverage_bytes = (coverage_dir / sample_id).read_bytes()
try:
program = program_bytes.decode("utf-8")
coverage = coverage_bytes.decode("ascii")
except UnicodeDecodeError as error:
raise ValueError(f"text decoding failed for sample {sample_id}") from error
return (
sample_id,
program,
coverage,
len(program_bytes),
len(coverage_bytes),
count_lines(coverage_bytes),
)
def build_table(rows: list[tuple[str, str, str, int, int, int]]) -> pa.Table:
columns = list(zip(*rows, strict=True))
return pa.Table.from_arrays(
[pa.array(column, type=field.type) for column, field in zip(columns, SCHEMA)],
schema=SCHEMA,
)
def validate_source(program_dir: Path, coverage_dir: Path) -> list[str]:
started = time.monotonic()
print("Listing source IDs...", flush=True)
program_ids = list_source_ids(program_dir)
coverage_ids = set(list_source_ids(coverage_dir))
program_set = set(program_ids)
missing_coverages = sorted(program_set - coverage_ids)[:10]
orphan_coverages = sorted(coverage_ids - program_set)[:10]
if missing_coverages or orphan_coverages:
raise ValueError(
"program/coverage pairing mismatch; "
f"missing coverage examples={missing_coverages}, "
f"orphan coverage examples={orphan_coverages}"
)
del coverage_ids
del program_set
program_ids.sort()
elapsed = time.monotonic() - started
print(f"Validated {len(program_ids):,} paired IDs in {elapsed:.1f}s", flush=True)
return program_ids
def load_state(path: Path, expected: dict[str, Any]) -> dict[str, Any]:
if not path.exists():
return {**expected, "completed_shards": {}}
with path.open("r", encoding="utf-8") as handle:
state = json.load(handle)
for key, value in expected.items():
if state.get(key) != value:
raise ValueError(
f"existing build state has {key}={state.get(key)!r}; "
f"expected {value!r}"
)
if not isinstance(state.get("completed_shards"), dict):
raise ValueError("existing build state has no completed_shards mapping")
return state
def main() -> int:
args = parse_args()
source = args.source.resolve()
output = args.output.resolve()
program_dir = source / "programs"
coverage_dir = source / "coverages"
data_dir = output / "data"
data_dir.mkdir(parents=True, exist_ok=True)
sample_ids = validate_source(program_dir, coverage_dir)
source_total = len(sample_ids)
if args.limit is not None:
sample_ids = sample_ids[: args.limit]
total_rows = len(sample_ids)
total_shards = math.ceil(total_rows / args.rows_per_shard)
state_path = output / "_build_state.json"
state_expected = {
"schema_version": SCHEMA_VERSION,
"source": str(source),
"source_total_pairs": source_total,
"selected_rows": total_rows,
"rows_per_shard": args.rows_per_shard,
"row_group_rows": args.row_group_rows,
"compression": "zstd",
"compression_level": args.compression_level,
}
state = load_state(state_path, state_expected)
completed: dict[str, dict[str, Any]] = state["completed_shards"]
build_started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.workers) as executor:
for shard_index in range(total_shards):
start = shard_index * args.rows_per_shard
stop = min(start + args.rows_per_shard, total_rows)
shard_ids = sample_ids[start:stop]
shard_name = f"train-{shard_index:05d}-of-{total_shards:05d}.parquet"
shard_path = data_dir / shard_name
relative_path = f"data/{shard_name}"
old_entry = completed.get(relative_path)
if old_entry and shard_path.is_file():
current_size = shard_path.stat().st_size
if current_size == old_entry.get("size_bytes"):
current_hash = file_sha256(shard_path)
if current_hash == old_entry.get("sha256"):
print(
f"[{shard_index + 1}/{total_shards}] Reusing {shard_name}",
flush=True,
)
continue
shard_started = time.monotonic()
tasks = ((sample_id, program_dir, coverage_dir) for sample_id in shard_ids)
rows = list(executor.map(read_pair, tasks, chunksize=16))
table = build_table(rows)
temporary = shard_path.with_suffix(".parquet.tmp")
pq.write_table(
table,
temporary,
compression="zstd",
compression_level=args.compression_level,
use_dictionary=False,
write_statistics=[
"id",
"program_size_bytes",
"coverage_size_bytes",
"coverage_count",
],
row_group_size=args.row_group_rows,
data_page_size=1024 * 1024,
)
os.replace(temporary, shard_path)
entry = {
"first_id": shard_ids[0],
"last_id": shard_ids[-1],
"num_rows": len(rows),
"program_bytes": sum(row[3] for row in rows),
"coverage_bytes": sum(row[4] for row in rows),
"coverage_addresses": sum(row[5] for row in rows),
"size_bytes": shard_path.stat().st_size,
"sha256": file_sha256(shard_path),
}
completed[relative_path] = entry
write_json_atomic(state_path, state)
elapsed = time.monotonic() - shard_started
ratio = entry["size_bytes"] / max(
entry["program_bytes"] + entry["coverage_bytes"], 1
)
print(
f"[{shard_index + 1}/{total_shards}] Wrote {shard_name}: "
f"{len(rows):,} rows, {entry['size_bytes'] / 2**20:.1f} MiB, "
f"ratio={ratio:.3f}, {elapsed:.1f}s",
flush=True,
)
expected_paths = {
f"data/train-{index:05d}-of-{total_shards:05d}.parquet"
for index in range(total_shards)
}
if set(completed) != expected_paths:
missing = sorted(expected_paths - set(completed))[:10]
extra = sorted(set(completed) - expected_paths)[:10]
raise RuntimeError(f"build state mismatch: missing={missing}, extra={extra}")
ordered_shards = [
{"path": path, **completed[path]} for path in sorted(expected_paths)
]
manifest = {
"dataset": "SyzPilot-dataset",
"format": "parquet",
"schema_version": SCHEMA_VERSION,
"schema": [
{"name": field.name, "type": str(field.type), "nullable": field.nullable}
for field in SCHEMA
],
"ordering": "Rows are sorted lexicographically by id across shards.",
"num_rows": sum(shard["num_rows"] for shard in ordered_shards),
"num_shards": len(ordered_shards),
"program_bytes": sum(shard["program_bytes"] for shard in ordered_shards),
"coverage_bytes": sum(shard["coverage_bytes"] for shard in ordered_shards),
"coverage_addresses": sum(
shard["coverage_addresses"] for shard in ordered_shards
),
"parquet_bytes": sum(shard["size_bytes"] for shard in ordered_shards),
"shards": ordered_shards,
}
write_json_atomic(output / "manifest.json", manifest)
elapsed = time.monotonic() - build_started
print(
f"Completed {manifest['num_rows']:,} rows in {manifest['num_shards']} "
f"shards ({manifest['parquet_bytes'] / 2**30:.2f} GiB) in "
f"{elapsed / 60:.1f} minutes.",
flush=True,
)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("Interrupted; completed shards can be reused on the next run.", file=sys.stderr)
raise SystemExit(130)
|