1
0

kernel-parity.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env node
  2. /**
  3. * Kernel↔wasm extraction parity harness (R2/R3 of the kernel migration).
  4. *
  5. * Runs BOTH extraction paths over the given files/directories and diffs the
  6. * per-file ExtractionResults as sets (nodes/edges/refs, canonicalized), so a
  7. * behavioral gap in the native kernel shows up as a categorized diff instead
  8. * of a graph-dump surprise later. This is the fast inner loop; the §5 gate's
  9. * full-repo dump-diff still runs before any default-on.
  10. *
  11. * Usage:
  12. * node scripts/kernel-parity.mjs <file-or-dir>... [--lang typescript,tsx]
  13. * [--max-samples N] [--list-files]
  14. *
  15. * Requires: npm run build (dist/) and a staged kernel (npm run build:kernel).
  16. * Exit code: 0 = parity, 1 = diffs found, 2 = setup error.
  17. */
  18. import * as fs from 'node:fs';
  19. import * as path from 'node:path';
  20. import { fileURLToPath } from 'node:url';
  21. const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
  22. const dist = (p) => path.join(ROOT, 'dist', p);
  23. const args = process.argv.slice(2);
  24. const paths = [];
  25. let langFilter = null;
  26. let maxSamples = 5;
  27. let listFiles = false;
  28. for (let i = 0; i < args.length; i++) {
  29. if (args[i] === '--lang') langFilter = new Set(args[++i].split(','));
  30. else if (args[i] === '--max-samples') maxSamples = Number(args[++i]);
  31. else if (args[i] === '--list-files') listFiles = true;
  32. else paths.push(args[i]);
  33. }
  34. if (paths.length === 0) {
  35. console.error('usage: kernel-parity.mjs <file-or-dir>... [--lang ts,tsx] [--max-samples N]');
  36. process.exit(2);
  37. }
  38. const KERNEL_LANGS = new Set(['typescript', 'tsx', 'javascript', 'jsx', 'java', 'python', 'go']);
  39. const EXTS = new Map([
  40. ['.ts', 'typescript'], ['.mts', 'typescript'], ['.cts', 'typescript'],
  41. ['.tsx', 'tsx'], ['.js', 'javascript'], ['.mjs', 'javascript'],
  42. ['.cjs', 'javascript'], ['.jsx', 'jsx'], ['.java', 'java'], ['.py', 'python'], ['.pyw', 'python'], ['.go', 'go'],
  43. ]);
  44. /** Collect candidate files. */
  45. function collect(p, out) {
  46. let st;
  47. try {
  48. st = fs.statSync(p); // dangling symlinks (Linux-tree dtc fixtures) throw
  49. } catch {
  50. return;
  51. }
  52. if (st.isDirectory()) {
  53. const base = path.basename(p);
  54. if (base === 'node_modules' || base === '.git' || base === 'dist' || base === '.codegraph') return;
  55. for (const e of fs.readdirSync(p)) collect(path.join(p, e), out);
  56. } else if (EXTS.has(path.extname(p))) {
  57. const lang = EXTS.get(path.extname(p));
  58. if (!langFilter || langFilter.has(lang)) out.push({ file: p, lang });
  59. }
  60. }
  61. const files = [];
  62. for (const p of paths) collect(path.resolve(p), files);
  63. if (files.length === 0) {
  64. console.error('no matching files');
  65. process.exit(2);
  66. }
  67. // --- load the built engine ---------------------------------------------------
  68. const { extractFromSource } = await import(dist('extraction/tree-sitter.js'));
  69. const { initGrammars, loadGrammarsForLanguages } = await import(dist('extraction/grammars.js'));
  70. const kernel = await import(dist('extraction/kernel/index.js'));
  71. await initGrammars();
  72. await loadGrammarsForLanguages([...KERNEL_LANGS]);
  73. if (!kernel.getKernel()) {
  74. console.error('kernel .node not found — run: npm run build:kernel');
  75. process.exit(2);
  76. }
  77. // --- canonicalization ---------------------------------------------------------
  78. /**
  79. * Node identity for cross-referencing edges/refs: the node id itself (both
  80. * paths compute the same deterministic ids, and id embeds kind+name+line).
  81. */
  82. function canonNode(n) {
  83. const out = {
  84. id: n.id, kind: n.kind, name: n.name, qualifiedName: n.qualifiedName,
  85. filePath: n.filePath, language: n.language,
  86. startLine: n.startLine, endLine: n.endLine,
  87. startColumn: n.startColumn, endColumn: n.endColumn,
  88. };
  89. for (const k of ['docstring', 'signature', 'visibility', 'isExported', 'isAsync', 'isStatic', 'isAbstract', 'returnType']) {
  90. if (n[k] !== undefined) out[k] = n[k];
  91. }
  92. if (n.decorators !== undefined) out.decorators = n.decorators;
  93. if (n.typeParameters !== undefined) out.typeParameters = n.typeParameters;
  94. return JSON.stringify(out);
  95. }
  96. function canonEdge(e) {
  97. const out = { source: e.source, target: e.target, kind: e.kind };
  98. if (e.line !== undefined) out.line = e.line;
  99. if (e.column !== undefined) out.column = e.column;
  100. if (e.provenance !== undefined) out.provenance = e.provenance;
  101. if (e.metadata !== undefined) out.metadata = e.metadata;
  102. return JSON.stringify(out);
  103. }
  104. function canonRef(r) {
  105. // FULL object — a field only one path sets is a parity bug (the vitest
  106. // parity suite caught decode.ts pre-filling filePath/language this way).
  107. const out = {
  108. from: r.fromNodeId, name: r.referenceName, kind: r.referenceKind,
  109. line: r.line, column: r.column,
  110. };
  111. for (const k of ['filePath', 'language', 'candidates', 'rowId']) {
  112. if (r[k] !== undefined) out[k] = r[k];
  113. }
  114. return JSON.stringify(out);
  115. }
  116. function diffSets(aList, bList) {
  117. const a = new Map(); // canon -> count (multiset — duplicates matter)
  118. const b = new Map();
  119. for (const x of aList) a.set(x, (a.get(x) ?? 0) + 1);
  120. for (const x of bList) b.set(x, (b.get(x) ?? 0) + 1);
  121. const onlyA = [];
  122. const onlyB = [];
  123. for (const [k, c] of a) {
  124. const d = c - (b.get(k) ?? 0);
  125. for (let i = 0; i < d; i++) onlyA.push(k);
  126. }
  127. for (const [k, c] of b) {
  128. const d = c - (a.get(k) ?? 0);
  129. for (let i = 0; i < d; i++) onlyB.push(k);
  130. }
  131. return { onlyA, onlyB };
  132. }
  133. // --- run ----------------------------------------------------------------------
  134. const buckets = new Map(); // category -> {count, samples[]}
  135. function report(category, sample) {
  136. let b = buckets.get(category);
  137. if (!b) buckets.set(category, (b = { count: 0, samples: [] }));
  138. b.count++;
  139. if (b.samples.length < maxSamples) b.samples.push(sample);
  140. }
  141. let filesWithDiffs = 0;
  142. let filesOk = 0;
  143. let deferred = 0;
  144. let totals = { nodes: 0, edges: 0, refs: 0 };
  145. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  146. for (const { file, lang } of files) {
  147. const source = fs.readFileSync(file, 'utf8');
  148. const rel = path.relative(ROOT, file);
  149. delete process.env.CODEGRAPH_KERNEL; // kernel path on
  150. const kres = kernel.tryKernelExtract(rel, source, lang);
  151. if (!kres) {
  152. // Expected: files with parse errors defer to wasm (parity by
  153. // construction — both arms run the same extractor). Counted, and
  154. // guarded below so a broken kernel can't silently defer everything.
  155. deferred++;
  156. report('kernel-deferred', rel);
  157. continue;
  158. }
  159. process.env.CODEGRAPH_KERNEL = '0'; // wasm path
  160. const wres = extractFromSource(rel, source, lang);
  161. delete process.env.CODEGRAPH_KERNEL;
  162. totals.nodes += wres.nodes.length;
  163. totals.edges += wres.edges.length;
  164. totals.refs += wres.unresolvedReferences.length;
  165. let fileHasDiff = false;
  166. const tables = [
  167. ['node', wres.nodes.map(canonNode), kres.nodes.map(canonNode)],
  168. ['edge', wres.edges.map(canonEdge), kres.edges.map(canonEdge)],
  169. ['ref', wres.unresolvedReferences.map(canonRef), kres.unresolvedReferences.map(canonRef)],
  170. ];
  171. for (const [table, wasm, kern] of tables) {
  172. const { onlyA, onlyB } = diffSets(wasm, kern);
  173. for (const x of onlyA) {
  174. fileHasDiff = true;
  175. const o = JSON.parse(x);
  176. report(`${table}:missing-in-kernel:${o.kind ?? ''}`, `${rel}: ${x}`);
  177. }
  178. for (const x of onlyB) {
  179. fileHasDiff = true;
  180. const o = JSON.parse(x);
  181. report(`${table}:extra-in-kernel:${o.kind ?? ''}`, `${rel}: ${x}`);
  182. }
  183. // ORDER matters too: identical multisets in a different emission order
  184. // change DB rowids, and resolution iterates refs in rowid order — the
  185. // full-index dump-diff would surface it as a downstream mystery. Catch it
  186. // here instead.
  187. if (onlyA.length === 0 && onlyB.length === 0) {
  188. for (let i = 0; i < wasm.length; i++) {
  189. if (wasm[i] !== kern[i]) {
  190. fileHasDiff = true;
  191. report(`${table}:order-mismatch`, `${rel}: index ${i}: wasm=${wasm[i]} kernel=${kern[i]}`);
  192. break;
  193. }
  194. }
  195. }
  196. }
  197. if (fileHasDiff) {
  198. filesWithDiffs++;
  199. if (listFiles) console.log(`DIFF ${rel}`);
  200. } else {
  201. filesOk++;
  202. }
  203. }
  204. console.log(`\n=== kernel parity: ${filesOk}/${files.length} files byte-parity` +
  205. ` (${filesWithDiffs} with diffs, ${deferred} deferred-to-wasm)` +
  206. ` | wasm totals: ${totals.nodes} nodes / ${totals.edges} edges / ${totals.refs} refs ===\n`);
  207. const sorted = [...buckets.entries()].sort((a, b) => b[1].count - a[1].count);
  208. for (const [cat, { count, samples }] of sorted) {
  209. console.log(`--- ${cat}: ${count}`);
  210. for (const s of samples) console.log(` ${s.length > 400 ? s.slice(0, 400) + '…' : s}`);
  211. }
  212. // Deferrals are per-file parse-error routing (expected, rare). A high rate
  213. // means the kernel is broken and hiding behind the fallback — fail loudly.
  214. const deferralRate = deferred / files.length;
  215. if (deferralRate > 0.1) {
  216. console.error(`deferral rate ${(deferralRate * 100).toFixed(1)}% exceeds 10% — kernel likely broken`);
  217. process.exit(1);
  218. }
  219. process.exit(filesWithDiffs > 0 ? 1 : 0);