1#!/usr/bin/env python3
2"""Csmith-style differential testing & fuzzing harness: Fusion Render Node 21.1 (sg render) vs Fission (render-check).
3
4Generates synthetic test plates & OBJ geometry (pure Python stdlib, no PIL/numpy),
5runs an exhaustive edge-case parameter matrix (--matrix) across Merge, HDR/BitDepth,
6Masks, Color/Blur/Glow, Warps/Shapes, 3D, and Misc tools, and runs a seeded randomized
7DAG fuzzer (--fuzz) with automatic node-by-node graph bisection (--bisect).
8"""
9
10import argparse
11import json
12import sys
13from pathlib import Path
14from typing import Any, Dict, List
15
16from diff_fuzz.assets import generate_assets
17from diff_fuzz.fuzzer import generate_random_dag
18from diff_fuzz.matrix import MATRIX_BUILDERS
19from diff_fuzz.runner import (
20 bisect_failing_graph,
21 print_table,
22 run_comp_both,
23 run_multi_graph_batch,
24 write_standalone_graph_comp,
25)
26
27
28def main() -> int:
29 parser = argparse.ArgumentParser(description="Fusion 21.1 vs Fission differential matrix & DAG fuzzer")
30 parser.add_argument("--matrix", action="store_true", help="Run all edge-case parameter matrix suites")
31 parser.add_argument("--suite", action="append", default=[], help="Specific matrix suite(s) to run")
32 parser.add_argument("--fuzz", action="store_true", help="Run seeded randomized DAG fuzzer")
33 parser.add_argument("--deterministic", action="store_true", default=True, help="Use deterministic sources only in --fuzz (default)")
34 parser.add_argument("--allow-noise", action="store_false", dest="deterministic", help="Allow non-deterministic FastNoise sources in --fuzz")
35 parser.add_argument("--seeds", type=int, default=20, help="Number of random seeds to fuzz (default 20)")
36 parser.add_argument("--seed-start", type=int, default=1, help="Starting seed integer (default 1)")
37 parser.add_argument("--bisect", action="store_true", help="Auto-bisect failing fuzz seeds (> threshold MAE%%)")
38 parser.add_argument("--threshold", type=float, default=1.5, help="MAE%% failure threshold (default 1.5)")
39 parser.add_argument("--batch-size", type=int, default=15, help="Seeds per batched Fusion render (default 15)")
40 parser.add_argument("--timeout", type=int, default=180, help="Per-render timeout in seconds (default 180)")
41 parser.add_argument("--no-gt", action="store_true", help="Skip sg render and reuse existing GT PNGs")
42 parser.add_argument("--report-json", type=str, default="", help="Write structured JSON report to path")
43 args = parser.parse_args()
44
45 if not args.matrix and not args.suite and not args.fuzz:
46 parser.print_help()
47 return 1
48
49 assets = generate_assets()
50 report: Dict[str, Any] = {
51 "threshold_pct": args.threshold,
52 "matrix": {},
53 "fuzz": {"seeds": [], "bisected": []},
54 }
55
56 if args.matrix or args.suite:
57 suites = args.suite if args.suite else list(MATRIX_BUILDERS.keys())
58 for sname in suites:
59 if sname not in MATRIX_BUILDERS:
60 print(f"Unknown matrix suite: {sname}", file=sys.stderr)
61 return 2
62 comp_path, prefix, cases = MATRIX_BUILDERS[sname](assets)
63 frames = [c[0] for c in cases]
64 labels = {c[0]: c[1] for c in cases}
65 res = run_comp_both(
66 comp_path,
67 prefix,
68 frames,
69 labels,
70 render_gt=not args.no_gt,
71 timeout_sec=args.timeout,
72 )
73 rows = [res[f] for f in frames]
74 print_table(sname, rows, args.threshold)
75 fails = [r for r in rows if r.get("mae_pct", 100.0) > args.threshold or r.get("size_mismatch") or r.get("error")]
76 mean_mae = sum(r["mae_pct"] for r in rows) / max(1, len(rows))
77 report["matrix"][sname] = {
78 "total": len(rows),
79 "passed": len(rows) - len(fails),
80 "failed": len(fails),
81 "mean_mae_pct": round(mean_mae, 4),
82 "cases": rows,
83 }
84
85 if args.fuzz:
86 seed_ids = list(range(args.seed_start, args.seed_start + args.seeds))
87 graphs = {s: generate_random_dag(s, assets, deterministic=args.deterministic) for s in seed_ids}
88 fuzz_rows: List[Dict[str, Any]] = []
89
90 for chunk_idx in range(0, len(seed_ids), args.batch_size):
91 chunk = seed_ids[chunk_idx : chunk_idx + args.batch_size]
92 batch_items = [(f"seed_{s}_n{len(graphs[s].nodes)}", graphs[s]) for s in chunk]
93 batch_prefix = f"fuzz_batch_{chunk[0]}_{chunk[-1]}"
94 res = run_multi_graph_batch(
95 batch_items,
96 batch_prefix,
97 render_gt=not args.no_gt,
98 timeout_sec=args.timeout,
99 )
100 # If the whole batch errored in sg render, fall back to individual seed renders
101 batch_errored = all(res[i].get("error") for i in range(len(chunk)))
102 if batch_errored:
103 print(f"[warn] Batch {batch_prefix} errored; falling back to per-seed renders...", file=sys.stderr)
104 for s in chunk:
105 g = graphs[s]
106 sp = f"fuzz_seed_{s}"
107 sc = write_standalone_graph_comp(g, sp)
108 sr = run_comp_both(
109 sc, sp, [g.eval_frame], {g.eval_frame: f"seed_{s}_n{len(g.nodes)}"},
110 render_gt=not args.no_gt, timeout_sec=args.timeout,
111 )[g.eval_frame]
112 sr["seed"] = s
113 sr["tools"] = [n.kind for n in g.nodes if not n.is_source]
114 fuzz_rows.append(sr)
115 else:
116 for i, s in enumerate(chunk):
117 r = res[i]
118 r["seed"] = s
119 r["tools"] = [n.kind for n in graphs[s].nodes if not n.is_source]
120 fuzz_rows.append(r)
121
122 print_table(f"fuzz seeds {args.seed_start}..{args.seed_start + args.seeds - 1}", fuzz_rows, args.threshold)
123 report["fuzz"]["seeds"] = fuzz_rows
124
125 if args.bisect:
126 failing_seeds = [r for r in fuzz_rows if not r.get("error") and (r.get("mae_pct", 0.0) > args.threshold or r.get("size_mismatch"))]
127 print(f"\n=== Bisecting {len(failing_seeds)} failing seeds (MAE > {args.threshold}%) ===")
128 for r in failing_seeds:
129 s = r["seed"]
130 try:
131 b_res = bisect_failing_graph(
132 graphs[s],
133 threshold_pct=args.threshold,
134 render_gt=not args.no_gt,
135 timeout_sec=args.timeout,
136 )
137 report["fuzz"]["bisected"].append(b_res)
138 except Exception as exc:
139 print(f" [bisect] seed={s} exception: {exc}", file=sys.stderr)
140 report["fuzz"]["bisected"].append({"seed": s, "error": str(exc)})
141
142 if args.report_json:
143 rp = Path(args.report_json)
144 rp.parent.mkdir(parents=True, exist_ok=True)
145 rp.write_text(json.dumps(report, indent=2))
146 print(f"\n[report] Wrote JSON summary to {rp}")
147
148 return 0
149
150
151if __name__ == "__main__":
152 raise SystemExit(main())