Files
kdm-re/tools/wave/sharder.py
T

135 lines
4.9 KiB
Python

"""Dispatch-only leaf-first wave sharder: never claims an RVA.
Reads any program database (re/rvadb.json or re/<mod>/*_rvadb.json), restricts
the call graph to its status="orig" functions, condenses mutual-recursion
cycles through tools/wave/scc.py into one unit each (docs/reconstruction-loop.md
3a), and emits disjoint shards ordered leaf-first within RTTI/namespace
clusters per section 2.1/2.3. A worker still claims by committing orig ->
reimpl per section 1 step 0; this tool only assigns candidates to shards.
"""
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
from __future__ import annotations
import argparse
import heapq
import json
import sys
from pathlib import Path
from rvadb import ProgramDatabase, Rva, load_database
from scc import SccResult, tarjan_scc
def build_pending_graph(db: ProgramDatabase) -> dict[Rva, tuple[Rva, ...]]:
orig = {row.rva for row in db.functions if row.status == "orig"}
return {
row.rva: tuple(callee for callee in row.callees if callee in orig)
for row in db.functions
if row.rva in orig
}
def leaf_first_order(
graph: dict[Rva, tuple[Rva, ...]], module_of: dict[Rva, str],
) -> tuple[tuple[Rva, ...], SccResult[Rva]]:
scc = tarjan_scc(graph)
component_count = len(scc.components)
deps: list[set[int]] = [set() for _ in range(component_count)]
dependents: list[set[int]] = [set() for _ in range(component_count)]
for node, callees in graph.items():
source = scc.component_of[node]
for callee in callees:
target = scc.component_of[callee]
if target != source:
deps[source].add(target)
dependents[target].add(source)
def sort_key(component_id: int) -> tuple[str, str]:
representative = min(scc.components[component_id])
return (module_of.get(representative, "unknown"), representative)
pending = [set(component) for component in deps]
remaining = [len(component) for component in deps]
heap = [(sort_key(i), i) for i in range(component_count) if remaining[i] == 0]
heapq.heapify(heap)
emitted: list[int] = []
while heap:
_, current = heapq.heappop(heap)
emitted.append(current)
for dependent in sorted(dependents[current]):
pending[dependent].discard(current)
remaining[dependent] -= 1
if remaining[dependent] == 0:
heapq.heappush(heap, (sort_key(dependent), dependent))
if len(emitted) != component_count:
raise ValueError("SCC condensation left a cycle: tarjan_scc invariant violated")
order: list[Rva] = []
for component_id in emitted:
order.extend(sorted(scc.components[component_id]))
return tuple(order), scc
def make_shards(
order: tuple[Rva, ...], scc: SccResult[Rva], shard_size: int,
) -> tuple[tuple[Rva, ...], ...]:
if shard_size < 1:
raise ValueError("shard_size must be at least 1")
shards: list[list[Rva]] = []
current: list[Rva] = []
index = 0
while index < len(order):
component_id = scc.component_of[order[index]]
members = sorted(scc.components[component_id])
if current and len(current) + len(members) > shard_size:
shards.append(current)
current = []
current.extend(members)
index += len(members)
if current:
shards.append(current)
return tuple(tuple(shard) for shard in shards)
def assert_disjoint(shards: tuple[tuple[Rva, ...], ...]) -> None:
seen: set[Rva] = set()
for shard in shards:
overlap = seen.intersection(shard)
if overlap:
raise ValueError(f"shards are not disjoint: {sorted(overlap)}")
seen.update(shard)
def main() -> int:
parser = argparse.ArgumentParser(
description="Emit disjoint leaf-first shards of status=orig functions. Dispatch only, never claims.",
)
parser.add_argument("db", type=Path, help="re/rvadb.json or re/<mod>/*_rvadb.json")
parser.add_argument("--shard-size", type=int, default=50)
parser.add_argument("--json", action="store_true", help="emit machine-readable shard assignments")
args = parser.parse_args()
db = load_database(args.db)
graph = build_pending_graph(db)
module_of = {row.rva: row.owning_module_guess for row in db.functions}
order, scc = leaf_first_order(graph, module_of)
shards = make_shards(order, scc, args.shard_size)
assert_disjoint(shards)
if args.json:
print(json.dumps([list(shard) for shard in shards], indent=2))
return 0
print(f"program={db.program} candidates={len(order)} shards={len(shards)}")
for i, shard in enumerate(shards):
modules = sorted({module_of[rva] for rva in shard})
preview = ", ".join(modules[:3]) + ("..." if len(modules) > 3 else "")
print(f" shard {i}: {len(shard)} functions, modules=[{preview}]")
return 0
if __name__ == "__main__":
sys.exit(main())