sync-rebuild-convergence.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /**
  2. * Incremental sync must converge to a full rebuild (CG-33).
  3. *
  4. * A long-lived, auto-synced index silently diverged from a clean rebuild of the
  5. * identical tree: 4.3% of distinct edges wrong, in BOTH directions, on
  6. * codegraph's own repo. Two mechanisms, both exercised here:
  7. *
  8. * 1. Resolution binds a reference to one of the same-named definitions
  9. * PROJECT-WIDE, so adding or removing a definition changes the answer for
  10. * references in files the sync never touches. Those references resolved once
  11. * and their rows were deleted, so nothing revisited them — the index kept an
  12. * answer that was only correct against an older graph.
  13. * 2. When nothing disambiguated the candidates, the winner was whichever row
  14. * the index scan reached first — i.e. the order files were WRITTEN. A full
  15. * index writes in scan order; a sync appends each file as it changes, so the
  16. * same tree resolved differently depending on how the index was built.
  17. *
  18. * The assertions here compare the whole edge SET, never counts: the divergence
  19. * is bidirectional and nets out of a total (raw rows differed by 0.7% while
  20. * 4.3% of edges were wrong), so a count check passes on a broken index.
  21. *
  22. * ---
  23. *
  24. * THIS SUITE MUST FAIL WITH `CODEGRAPH_NO_REBIND=1` (CG-35).
  25. *
  26. * That environment variable is the kill switch on the rebind half of the fix
  27. * (`src/index.ts`, guarding `resurrectStaleResolutionEdges`). The convergence
  28. * cases below are the only coverage that half has, so the check is the suite's
  29. * own regression test:
  30. *
  31. * CODEGRAPH_NO_REBIND=1 npx vitest run __tests__/sync-rebuild-convergence.test.ts
  32. *
  33. * must report failures, and an unset run must be green. If you change a case
  34. * here, re-run both. A version of this suite passed under the kill switch
  35. * because `rebuildEdgeSet` was not rebuilding anything — see the note there.
  36. */
  37. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  38. import * as fs from 'fs';
  39. import * as path from 'path';
  40. import * as os from 'os';
  41. import CodeGraph from '../src/index';
  42. import { createDatabase } from '../src/db/sqlite-adapter';
  43. describe('Incremental sync converges to a full rebuild (CG-33)', () => {
  44. let testDir: string;
  45. let cg: CodeGraph;
  46. const write = (rel: string, content: string) => {
  47. const full = path.join(testDir, rel);
  48. fs.mkdirSync(path.dirname(full), { recursive: true });
  49. fs.writeFileSync(full, content);
  50. };
  51. /**
  52. * Every edge as a `source|target|kind` triple, read from the database with a
  53. * second read-only connection. Node ids are `sha256(filePath:kind:name:line)`,
  54. * so for an identical tree they are identical across a sync and a rebuild —
  55. * which is what makes the two sets directly comparable.
  56. */
  57. const edgeSet = (): Set<string> => {
  58. const { db } = createDatabase(path.join(testDir, '.codegraph', 'codegraph.db'), { readOnly: true });
  59. try {
  60. const rows = db.prepare('SELECT source, target, kind FROM edges').all() as Array<{
  61. source: string;
  62. target: string;
  63. kind: string;
  64. }>;
  65. return new Set(rows.map((r) => `${r.source}|${r.target}|${r.kind}`));
  66. } finally {
  67. db.close();
  68. }
  69. };
  70. /**
  71. * Run `fn` against a second, WRITABLE connection to the same database. Used
  72. * by the two rule tests below to plant edge shapes the extractor cannot
  73. * produce on demand — an edge from an engine older than the refName stamp,
  74. * and a synthesized dispatch edge.
  75. */
  76. const withDb = <T>(fn: (db: ReturnType<typeof createDatabase>['db']) => T): T => {
  77. const { db } = createDatabase(path.join(testDir, '.codegraph', 'codegraph.db'));
  78. try {
  79. return fn(db);
  80. } finally {
  81. db.close();
  82. }
  83. };
  84. /** Human-readable diff, so a failure names the edges instead of just a count. */
  85. const describeDiff = (synced: Set<string>, rebuilt: Set<string>): string => {
  86. const missing = [...rebuilt].filter((e) => !synced.has(e));
  87. const stale = [...synced].filter((e) => !rebuilt.has(e));
  88. return `missing from synced: ${missing.length}, stale in synced: ${stale.length}`;
  89. };
  90. /**
  91. * Rebuild the index from scratch over the CURRENT tree and return its edge
  92. * set — the ground truth a user gets from `codegraph index`.
  93. *
  94. * It must go through `CodeGraph.recreate`, which is what the CLI's `index`
  95. * command does: it DELETES the database file and builds an empty one. Calling
  96. * `indexAll` on the live handle instead is not a rebuild at all — every file
  97. * hashes identical, so the store writes nothing (`nodesCreated: 0`), no
  98. * reference is re-created, and every existing edge survives untouched. The
  99. * comparison then reads the synced index against ITSELF and can never fail,
  100. * which is exactly how this suite passed with `CODEGRAPH_NO_REBIND=1` (CG-35).
  101. */
  102. const rebuildEdgeSet = async (): Promise<Set<string>> => {
  103. // Close the live handle first: `recreate` unlinks the database file, and a
  104. // held handle makes that EBUSY on Windows.
  105. cg.destroy();
  106. cg = await CodeGraph.recreate(testDir);
  107. await cg.indexAll();
  108. return edgeSet();
  109. };
  110. beforeEach(() => {
  111. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cg33-'));
  112. });
  113. afterEach(() => {
  114. cg?.destroy();
  115. if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  116. });
  117. /**
  118. * The originating shape. `caller.ts` calls `pct` with no import, so it binds
  119. * by name; at index time `zeta.ts` is the only definition. A later sync adds
  120. * `alpha.ts`, which sorts FIRST and is therefore the rebuild's answer — but
  121. * `caller.ts` never changes, so nothing re-resolves it.
  122. */
  123. it('rebinds references in UNCHANGED files when a sync adds a competing definition', async () => {
  124. write('src/caller.ts', `export function run(): number {\n return pct(1);\n}\n`);
  125. write('src/zeta.ts', `export function pct(n: number): number {\n return n;\n}\n`);
  126. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  127. await cg.indexAll();
  128. write('src/alpha.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  129. const result = await cg.sync();
  130. expect(result.filesAdded).toBe(1);
  131. expect(result.definitionDelta).toContain('pct');
  132. const synced = edgeSet();
  133. const rebuilt = await rebuildEdgeSet();
  134. expect(describeDiff(synced, rebuilt)).toBe('missing from synced: 0, stale in synced: 0');
  135. });
  136. /**
  137. * The mirror direction: removing a definition narrows the candidate set too,
  138. * so the delta must include names the sync DROPPED, not just names it added.
  139. *
  140. * This one already converged before the fix — a removal cascades the edge
  141. * away and the #1240 removal path resurrects it, so the reference gets
  142. * re-resolved for free. It is here as a standing guard on the invariant, and
  143. * because the removal half of the delta has no other coverage: an
  144. * implementation that only sampled post-sync names would still pass every
  145. * other test in this file.
  146. */
  147. it('rebinds references in UNCHANGED files when a sync removes a competing definition', async () => {
  148. write('src/caller.ts', `export function run(): number {\n return pct(1);\n}\n`);
  149. write('src/alpha.ts', `export function pct(n: number): number {\n return n;\n}\n`);
  150. write('src/zeta.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  151. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  152. await cg.indexAll();
  153. fs.rmSync(path.join(testDir, 'src', 'alpha.ts'));
  154. const result = await cg.sync();
  155. expect(result.filesRemoved).toBe(1);
  156. const synced = edgeSet();
  157. const rebuilt = await rebuildEdgeSet();
  158. expect(describeDiff(synced, rebuilt)).toBe('missing from synced: 0, stale in synced: 0');
  159. });
  160. /**
  161. * The delta must be computed per FILE. Comparing one name set across the whole
  162. * changed batch cancels a name that is added in one changed file while another
  163. * changed file already defined it — which is precisely the shape a commit that
  164. * splits a module out has, and it was the largest residual class in the first
  165. * measurement of this fix.
  166. */
  167. it('flags a name added in one changed file even when another changed file already defines it', async () => {
  168. write('src/caller.ts', `export function run(): number {\n return pct(1);\n}\n`);
  169. write('src/zeta.ts', `export function pct(n: number): number {\n return n;\n}\nexport function keep(): number {\n return 0;\n}\n`);
  170. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  171. await cg.indexAll();
  172. // One commit: a NEW file gains `pct`, and the file that already had `pct`
  173. // is edited too (so a batch-wide name set would see `pct` on both sides).
  174. write('src/alpha.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  175. write('src/zeta.ts', `export function pct(n: number): number {\n return n + 1;\n}\nexport function keep(): number {\n return 0;\n}\n`);
  176. const result = await cg.sync();
  177. expect(result.definitionDelta).toContain('pct');
  178. const synced = edgeSet();
  179. const rebuilt = await rebuildEdgeSet();
  180. expect(describeDiff(synced, rebuilt)).toBe('missing from synced: 0, stale in synced: 0');
  181. });
  182. /**
  183. * The realistic case the issue was filed from: many edits driven through sync
  184. * one after another, the way a watcher or a `git pull` applies them. Drift
  185. * accumulated across syncs, so a single-edit test would not have caught it.
  186. */
  187. it('stays converged across a sequence of adds, edits, renames and deletes', async () => {
  188. write('src/caller.ts', `export function run(): number {\n return pct(1) + fmt(2) + collect(3);\n}\n`);
  189. write('src/util/zeta.ts', `export function pct(n: number): number {\n return n;\n}\n`);
  190. write('src/util/omega.ts', `export function fmt(n: number): number {\n return n;\n}\n`);
  191. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  192. await cg.indexAll();
  193. // 1. add a competing `pct` that sorts before the existing one
  194. write('src/util/alpha.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  195. await cg.sync();
  196. // 2. body-only edit — must produce NO definition delta, so the common sync
  197. // pays nothing for this machinery
  198. write('src/util/alpha.ts', `export function pct(n: number): number {\n return n * 3;\n}\n`);
  199. const bodyOnly = await cg.sync();
  200. expect(bodyOnly.filesModified).toBe(1);
  201. expect(bodyOnly.definitionDelta).toBeUndefined();
  202. // 3. a rename: `fmt` moves out of omega.ts into a file that sorts first
  203. write('src/util/omega.ts', `export function other(n: number): number {\n return n;\n}\n`);
  204. write('src/util/beta.ts', `export function fmt(n: number): number {\n return n;\n}\n`);
  205. await cg.sync();
  206. // 4. a symbol appears for a reference that never resolved at all
  207. write('src/util/gamma.ts', `export function collect(n: number): number {\n return n;\n}\n`);
  208. await cg.sync();
  209. // 5. delete the current `pct` winner, so the reference must fall back...
  210. fs.rmSync(path.join(testDir, 'src', 'util', 'alpha.ts'));
  211. await cg.sync();
  212. // 6. ...and then a later sync introduces a new winner ahead of it again.
  213. // Ending here rather than on the delete matters: after the delete the
  214. // binding happens to land back where it started, which a broken index
  215. // also reaches. The final state must be one only re-resolution reaches.
  216. write('src/util/aaa.ts', `export function pct(n: number): number {\n return n * 5;\n}\n`);
  217. await cg.sync();
  218. const synced = edgeSet();
  219. expect(synced.size).toBeGreaterThan(0);
  220. const rebuilt = await rebuildEdgeSet();
  221. expect(describeDiff(synced, rebuilt)).toBe('missing from synced: 0, stale in synced: 0');
  222. });
  223. /**
  224. * The rebind pass DELETES an edge and re-inserts the reference behind it, so
  225. * it may only touch edges it can reconstruct. Two shapes it must leave alone,
  226. * both of which it would otherwise destroy permanently:
  227. *
  228. * - an edge with no `metadata.refName` — written by an engine older than the
  229. * stamp. Rebuilding a reference from the target's plain name would strip the
  230. * receiver context the original text carried (`h.greet` → `greet`);
  231. * - a synthesized dispatch edge (`provenance='heuristic'`), which is not
  232. * resolution output at all: nothing would re-create it, and the synthesizer
  233. * that wired it does not run again on this sync.
  234. *
  235. * Both are planted directly, since extraction cannot be asked to emit them.
  236. * The sync then changes the answer for `pct`, which is exactly the condition
  237. * that makes the pass want to re-open every edge targeting `pct`.
  238. */
  239. it('never deletes an edge it cannot reconstruct — no refName stamp, or synthesized', async () => {
  240. write('src/caller.ts', `export function run(): number {\n return pct(1);\n}\n`);
  241. write('src/other.ts', `export function other(): number {\n return 0;\n}\n`);
  242. write('src/zeta.ts', `export function pct(n: number): number {\n return n;\n}\n`);
  243. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  244. await cg.indexAll();
  245. const planted = withDb((db) => {
  246. const pct = db.prepare("SELECT id FROM nodes WHERE name = 'pct'").get() as { id: string };
  247. const other = db.prepare("SELECT id FROM nodes WHERE name = 'other'").get() as { id: string };
  248. // 1. Strip the stamp off the real edge, leaving the rest of its metadata
  249. // intact — the shape an index built before the stamp existed has.
  250. db.prepare(
  251. `UPDATE edges SET metadata = json_remove(metadata, '$.refName')
  252. WHERE target = ? AND kind = 'calls'`
  253. ).run(pct.id);
  254. // 2. A synthesized edge that DOES carry a stamp, so only the provenance
  255. // rule can save it.
  256. db.prepare(
  257. `INSERT INTO edges (source, target, kind, metadata, line, col, provenance)
  258. VALUES (?, ?, 'calls', ?, 1, 0, 'heuristic')`
  259. ).run(other.id, pct.id, JSON.stringify({ refName: 'pct', synthesizedBy: 'cg35-test' }));
  260. return {
  261. unstamped: `${(db.prepare("SELECT source FROM edges WHERE target = ? AND provenance IS NULL AND kind = 'calls'").get(pct.id) as { source: string }).source}|${pct.id}|calls`,
  262. synthesized: `${other.id}|${pct.id}|calls`,
  263. };
  264. });
  265. const before = edgeSet();
  266. expect(before.has(planted.unstamped)).toBe(true);
  267. expect(before.has(planted.synthesized)).toBe(true);
  268. write('src/alpha.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  269. const result = await cg.sync();
  270. expect(result.definitionDelta).toContain('pct');
  271. // Both survive: the pass considered them (their target is `pct`) and
  272. // declined. Drift is the acceptable outcome here; an edge that no pass can
  273. // ever restore is not.
  274. const after = edgeSet();
  275. expect(after.has(planted.unstamped)).toBe(true);
  276. expect(after.has(planted.synthesized)).toBe(true);
  277. });
  278. /**
  279. * The per-name ceiling in `getResolutionEdgesByTargetName` (500 by default).
  280. * Above it a name is generic — `push`, `get`, `join` — one new definition
  281. * won't flip most of its references, and rebinding an arbitrary subset would
  282. * manufacture wrong edges while costing the most work. It must DECLINE the
  283. * name outright, and declining must be lossless.
  284. *
  285. * The rare name in the same sync is the control: it proves the pass ran and
  286. * that the ceiling is what spared the generic one, not a dead rebind pass.
  287. */
  288. it('declines a name over the per-name ceiling instead of rebinding an arbitrary subset', async () => {
  289. // Must exceed the 500 default in getResolutionEdgesByTargetName.
  290. const OVER_CEILING = 501;
  291. const callers = Array.from(
  292. { length: OVER_CEILING },
  293. (_, i) => `export function hot${i}(): number {\n return push(${i});\n}\n`
  294. ).join('');
  295. write('src/hot.ts', callers);
  296. write('src/rare.ts', `export function rare(): number {\n return tug(1);\n}\n`);
  297. write(
  298. 'src/zzz_defs.ts',
  299. `export function push(n: number): number {\n return n;\n}\nexport function tug(n: number): number {\n return n;\n}\n`
  300. );
  301. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  302. await cg.indexAll();
  303. const targetsOf = (name: string): string[] =>
  304. withDb((db) =>
  305. (
  306. db
  307. .prepare(
  308. `SELECT t.file_path AS file FROM edges e
  309. JOIN nodes t ON t.id = e.target
  310. JOIN nodes s ON s.id = e.source
  311. WHERE t.name = ? AND e.kind = 'calls'`
  312. )
  313. .all(name) as Array<{ file: string }>
  314. ).map((r) => r.file)
  315. );
  316. expect(targetsOf('push')).toHaveLength(OVER_CEILING);
  317. expect(new Set(targetsOf('push'))).toEqual(new Set(['src/zzz_defs.ts']));
  318. expect(targetsOf('tug')).toEqual(['src/zzz_defs.ts']);
  319. // One sync adds a competing definition of BOTH names, in a file that sorts
  320. // first and is therefore the rebuild's answer for each.
  321. write(
  322. 'src/aaa.ts',
  323. `export function push(n: number): number {\n return n * 2;\n}\nexport function tug(n: number): number {\n return n * 2;\n}\n`
  324. );
  325. const result = await cg.sync();
  326. expect(result.definitionDelta).toContain('push');
  327. expect(result.definitionDelta).toContain('tug');
  328. // `push` is untouched — every edge still there, still on the old target.
  329. // This is knowingly divergent from a rebuild; see "Don't chase the
  330. // residual" in docs/benchmarks/index-drift-cg33.md.
  331. const pushTargets = targetsOf('push');
  332. expect(pushTargets).toHaveLength(OVER_CEILING);
  333. expect(new Set(pushTargets)).toEqual(new Set(['src/zzz_defs.ts']));
  334. // `tug` — the control — rebound.
  335. expect(targetsOf('tug')).toEqual(['src/aaa.ts']);
  336. });
  337. /**
  338. * Guards the escape hatch itself: with the rebind pass off, the same sequence
  339. * must still produce a structurally sound index (no lost or orphaned edges) —
  340. * just a drifted one. If this ever fails, the pass is doing something the
  341. * kill switch cannot undo.
  342. */
  343. it('CODEGRAPH_NO_REBIND=1 disables the pass without corrupting the index', async () => {
  344. write('src/caller.ts', `export function run(): number {\n return pct(1);\n}\n`);
  345. write('src/zeta.ts', `export function pct(n: number): number {\n return n;\n}\n`);
  346. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  347. await cg.indexAll();
  348. const before = edgeSet();
  349. process.env.CODEGRAPH_NO_REBIND = '1';
  350. try {
  351. write('src/alpha.ts', `export function pct(n: number): number {\n return n * 2;\n}\n`);
  352. await cg.sync();
  353. } finally {
  354. delete process.env.CODEGRAPH_NO_REBIND;
  355. }
  356. const after = edgeSet();
  357. // Every edge that existed before is still there — the pass is the only
  358. // thing that would have re-opened them, and it did not run.
  359. for (const edge of before) expect(after.has(edge)).toBe(true);
  360. });
  361. });
  362. /**
  363. * Resolution's candidate order must be a property of the CODE, not of the order
  364. * rows were written. This is the half of CG-33 that a re-resolution pass alone
  365. * cannot fix: without it, re-resolving a reference against the very same graph
  366. * can still pick a different winner than a rebuild does.
  367. */
  368. describe('Same-name candidate order is content-derived, not insertion-derived (CG-33)', () => {
  369. let testDir: string;
  370. let cg: CodeGraph;
  371. afterEach(() => {
  372. cg?.destroy();
  373. if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  374. });
  375. it('getNodesByName orders by (file_path, start_line) even when rows were written in another order', async () => {
  376. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cg33-order-'));
  377. fs.mkdirSync(path.join(testDir, 'src'), { recursive: true });
  378. fs.writeFileSync(path.join(testDir, 'src', 'mid.ts'), `export function pad(): void {}\nexport function dup(): number {\n return 2;\n}\n`);
  379. fs.writeFileSync(path.join(testDir, 'src', 'zeta.ts'), `export function dup(): number {\n return 1;\n}\n`);
  380. cg = CodeGraph.initSync(testDir, { config: { include: ['**/*.ts'], exclude: [] } });
  381. await cg.indexAll();
  382. // A sync APPENDS this file's nodes, so `alpha.ts` gets the highest rowids
  383. // despite sorting first — exactly the divergence a full index never has,
  384. // and the reason candidate order cannot come from the physical row order.
  385. fs.writeFileSync(path.join(testDir, 'src', 'alpha.ts'), `export function dup(): number {\n return 3;\n}\n`);
  386. await cg.sync();
  387. const keys = cg.getNodesByName('dup').map((n) => `${n.filePath}:${String(n.startLine).padStart(6, '0')}`);
  388. expect(keys.length).toBeGreaterThanOrEqual(3);
  389. expect(keys).toEqual([...keys].sort());
  390. expect(keys[0]).toContain('src/alpha.ts');
  391. });
  392. });