|
| 1 | +/** |
| 2 | + * Sync FK regression test (issue #455). |
| 3 | + * |
| 4 | + * #62 plugged FK violations at the extraction layer (empty-named nodes whose |
| 5 | + * containment edges had no target). #455 reports the same `FOREIGN KEY constraint |
| 6 | + * failed` reappearing on v0.9.5, but during *watch sync* on a Python-only project — |
| 7 | + * a different trigger than the C/C++ header empty-name issue #62 covered. |
| 8 | + * |
| 9 | + * The reproducer below drives the same path the daemon takes: extract → resolve → |
| 10 | + * insert edges. The resolution pass's `insertEdges` was not guarded the way the |
| 11 | + * extraction-layer insert was after #62, so any edge with a stale source/target |
| 12 | + * (e.g. a synthesized framework target whose node was deleted by a concurrent |
| 13 | + * file rewrite) throws and aborts the sync, leaving the FK error the user sees. |
| 14 | + * |
| 15 | + * The test asserts: a sequence of file rewrites + sync()s never throws, and the |
| 16 | + * graph stays internally consistent (every edge's source + target are real nodes). |
| 17 | + */ |
| 18 | +import { describe, it, expect, beforeAll, afterEach } from 'vitest'; |
| 19 | +import * as fs from 'fs'; |
| 20 | +import * as path from 'path'; |
| 21 | +import * as os from 'os'; |
| 22 | +import CodeGraph from '../src/index'; |
| 23 | +import { initGrammars, loadAllGrammars } from '../src/extraction/grammars'; |
| 24 | + |
| 25 | +beforeAll(async () => { |
| 26 | + await initGrammars(); |
| 27 | + await loadAllGrammars(); |
| 28 | +}); |
| 29 | + |
| 30 | +describe('watch sync FK regression (#455)', () => { |
| 31 | + let tmpDir: string | undefined; |
| 32 | + let cg: CodeGraph | undefined; |
| 33 | + |
| 34 | + afterEach(() => { |
| 35 | + if (cg) { |
| 36 | + cg.close(); |
| 37 | + cg = undefined; |
| 38 | + } |
| 39 | + if (tmpDir) { |
| 40 | + fs.rmSync(tmpDir, { recursive: true, force: true }); |
| 41 | + tmpDir = undefined; |
| 42 | + } |
| 43 | + }); |
| 44 | + |
| 45 | + function assertGraphIntegrity(cg: CodeGraph): void { |
| 46 | + // Every edge must reference real nodes. If FK was disabled or violated, |
| 47 | + // dangling refs would show up here. |
| 48 | + const db = (cg as unknown as { db: { getDb(): { prepare(sql: string): { get(): unknown } } } }).db; |
| 49 | + const sqlite = db.getDb(); |
| 50 | + const dangling = sqlite |
| 51 | + .prepare( |
| 52 | + `SELECT count(*) as c FROM edges e |
| 53 | + WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source) |
| 54 | + OR NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)` |
| 55 | + ) |
| 56 | + .get() as { c: number }; |
| 57 | + expect(dangling.c).toBe(0); |
| 58 | + } |
| 59 | + |
| 60 | + it('survives repeated sync() cycles on a Django-style Python project without FK errors', async () => { |
| 61 | + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-fk455-')); |
| 62 | + |
| 63 | + // Mimic a small Django app: requirements + manage.py marker, models/views/urls |
| 64 | + // in two app packages that cross-reference each other. |
| 65 | + fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# django marker\n'); |
| 66 | + fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n'); |
| 67 | + |
| 68 | + fs.mkdirSync(path.join(tmpDir, 'users')); |
| 69 | + fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), ''); |
| 70 | + fs.writeFileSync( |
| 71 | + path.join(tmpDir, 'users/models.py'), |
| 72 | + 'class User:\n' + |
| 73 | + ' def __init__(self, name):\n' + |
| 74 | + ' self.name = name\n' |
| 75 | + ); |
| 76 | + fs.writeFileSync( |
| 77 | + path.join(tmpDir, 'users/views.py'), |
| 78 | + 'from users.models import User\n' + |
| 79 | + 'class UserListView:\n' + |
| 80 | + ' def get(self, request):\n' + |
| 81 | + ' return User("a")\n' |
| 82 | + ); |
| 83 | + fs.writeFileSync( |
| 84 | + path.join(tmpDir, 'users/urls.py'), |
| 85 | + 'from django.urls import path\n' + |
| 86 | + 'from users.views import UserListView\n' + |
| 87 | + 'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n' |
| 88 | + ); |
| 89 | + |
| 90 | + fs.mkdirSync(path.join(tmpDir, 'posts')); |
| 91 | + fs.writeFileSync(path.join(tmpDir, 'posts/__init__.py'), ''); |
| 92 | + fs.writeFileSync( |
| 93 | + path.join(tmpDir, 'posts/models.py'), |
| 94 | + 'from users.models import User\n' + |
| 95 | + 'class Post:\n' + |
| 96 | + ' def __init__(self, author):\n' + |
| 97 | + ' self.author = author\n' |
| 98 | + ); |
| 99 | + fs.writeFileSync( |
| 100 | + path.join(tmpDir, 'posts/views.py'), |
| 101 | + 'from posts.models import Post\n' + |
| 102 | + 'class PostListView:\n' + |
| 103 | + ' def get(self, request):\n' + |
| 104 | + ' return Post(None)\n' |
| 105 | + ); |
| 106 | + fs.writeFileSync( |
| 107 | + path.join(tmpDir, 'posts/urls.py'), |
| 108 | + 'from django.urls import path\n' + |
| 109 | + 'from posts.views import PostListView\n' + |
| 110 | + 'urlpatterns = [path("posts/", PostListView.as_view(), name="post-list")]\n' |
| 111 | + ); |
| 112 | + |
| 113 | + cg = CodeGraph.initSync(tmpDir); |
| 114 | + await cg.indexAll(); |
| 115 | + assertGraphIntegrity(cg); |
| 116 | + |
| 117 | + // Drive the same path the daemon's file watcher drives: a series of file |
| 118 | + // rewrites + sync()s. We shuffle line counts on each rewrite so node IDs |
| 119 | + // (file:kind:name:line) shift around, forcing real INSERT OR REPLACE + |
| 120 | + // CASCADE behavior across files that cross-reference each other. |
| 121 | + const targets = [ |
| 122 | + 'users/views.py', |
| 123 | + 'posts/views.py', |
| 124 | + 'users/urls.py', |
| 125 | + 'posts/urls.py', |
| 126 | + 'users/models.py', |
| 127 | + ]; |
| 128 | + |
| 129 | + for (let iter = 0; iter < 8; iter++) { |
| 130 | + const file = targets[iter % targets.length]!; |
| 131 | + const full = path.join(tmpDir, file); |
| 132 | + const content = fs.readFileSync(full, 'utf8'); |
| 133 | + // Insert N blank lines at the top to shift every node's line number. |
| 134 | + const padded = '\n'.repeat(iter + 1) + content; |
| 135 | + // Use a future mtime so the size+mtime pre-filter in |
| 136 | + // ExtractionOrchestrator.sync can't skip the file. |
| 137 | + fs.writeFileSync(full, padded); |
| 138 | + const now = Date.now() + (iter + 1) * 1_000; |
| 139 | + fs.utimesSync(full, now / 1000, now / 1000); |
| 140 | + |
| 141 | + // The fix should make this never throw; before the fix, FK errors fire |
| 142 | + // during the resolution-layer insertEdges call inside sync(). |
| 143 | + await expect(cg.sync()).resolves.toBeDefined(); |
| 144 | + assertGraphIntegrity(cg); |
| 145 | + } |
| 146 | + }); |
| 147 | + |
| 148 | + it("drops resolution edges whose target node is no longer in the graph (the pathology #455 reports)", async () => { |
| 149 | + // This narrower test reproduces the exact failure mode the user sees in |
| 150 | + // their daemon log: the resolver hands `insertEdges` an edge whose target |
| 151 | + // doesn't exist in `nodes`, and the FK constraint aborts the whole sync. |
| 152 | + // |
| 153 | + // We force the bug by populating the resolver's per-name cache with a |
| 154 | + // stale node (whose id is *not* in the DB) and then asking it to resolve |
| 155 | + // a reference to that name. Without the fix this throws |
| 156 | + // `FOREIGN KEY constraint failed`; with it, the bad edge is filtered out |
| 157 | + // and resolution returns normally. |
| 158 | + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-fk455-stale-')); |
| 159 | + fs.writeFileSync(path.join(tmpDir, 'a.py'), 'def caller():\n Target()\n'); |
| 160 | + fs.writeFileSync(path.join(tmpDir, 'b.py'), 'class Target:\n pass\n'); |
| 161 | + |
| 162 | + cg = CodeGraph.initSync(tmpDir); |
| 163 | + await cg.indexAll(); |
| 164 | + |
| 165 | + // Reach in to the internals — the simplest way to forge the "stale node |
| 166 | + // ID in the resolver's lookup path" condition the production bug arises |
| 167 | + // from. The fix is what the test is verifying; touching internals here |
| 168 | + // is a means to that end, not a contract we're asserting. |
| 169 | + type Internals = { |
| 170 | + queries: { |
| 171 | + getNodesByName(name: string): Array<{ id: string; name: string }>; |
| 172 | + getAllNodeNames(): string[]; |
| 173 | + }; |
| 174 | + resolver: { |
| 175 | + warmCaches(): void; |
| 176 | + resolveAndPersist( |
| 177 | + refs: Array<{ |
| 178 | + fromNodeId: string; |
| 179 | + referenceName: string; |
| 180 | + referenceKind: string; |
| 181 | + line: number; |
| 182 | + column: number; |
| 183 | + filePath: string; |
| 184 | + language: string; |
| 185 | + }> |
| 186 | + ): { resolved: unknown[] }; |
| 187 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 188 | + nameCache: { set(key: string, value: any): void }; |
| 189 | + }; |
| 190 | + }; |
| 191 | + const internals = cg as unknown as Internals; |
| 192 | + const queries = internals.queries; |
| 193 | + const resolver = internals.resolver; |
| 194 | + |
| 195 | + const caller = queries.getNodesByName('caller')[0]; |
| 196 | + const target = queries.getNodesByName('Target')[0]; |
| 197 | + expect(caller).toBeDefined(); |
| 198 | + expect(target).toBeDefined(); |
| 199 | + |
| 200 | + // Warm caches so warmCaches no-ops on the resolveAndPersist call below |
| 201 | + // and our seeded nameCache entry isn't overwritten. |
| 202 | + resolver.warmCaches(); |
| 203 | + |
| 204 | + // Forge a stale lookup result: a Node whose `id` doesn't exist in the |
| 205 | + // `nodes` table. This is structurally what happens when a framework |
| 206 | + // resolver's WeakMap cache hands back a Node that was deleted by a |
| 207 | + // concurrent file rewrite — the user's #455 scenario. |
| 208 | + const staleNode = { ...target!, id: 'class:stale.py:Target:1' }; |
| 209 | + resolver.nameCache.set('Target', [staleNode]); |
| 210 | + |
| 211 | + // Ask the resolver to persist an edge that will resolve via the seeded |
| 212 | + // (stale) cache entry. Without the FK filter this would throw |
| 213 | + // `FOREIGN KEY constraint failed` and abort the whole batch. |
| 214 | + expect(() => |
| 215 | + resolver.resolveAndPersist([ |
| 216 | + { |
| 217 | + fromNodeId: caller!.id, |
| 218 | + referenceName: 'Target', |
| 219 | + referenceKind: 'calls', |
| 220 | + line: 2, |
| 221 | + column: 4, |
| 222 | + filePath: 'a.py', |
| 223 | + language: 'python', |
| 224 | + }, |
| 225 | + ]) |
| 226 | + ).not.toThrow(); |
| 227 | + |
| 228 | + // The bad edge must not have been persisted either — FK enforcement is |
| 229 | + // still on, and post-fix the dangling-edge count remains zero. |
| 230 | + assertGraphIntegrity(cg); |
| 231 | + }); |
| 232 | +}); |
0 commit comments