Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions src/domain/graph/builder/incremental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ export interface IncrementalStmts {
upsertFileHash: { run: (...params: unknown[]) => unknown };
/** Delete a `file_hashes` row for a file removed from disk. */
deleteFileHash: { run: (...params: unknown[]) => unknown };
/**
* Mark a node `exported = 1`, keyed by `(name, kind, file, line)` —
* mirrors the full-build path's `markExportedSymbols` (issue #2220).
*/
markExported: { run: (...params: unknown[]) => unknown };
}

interface RebuildResult {
Expand All @@ -102,32 +107,75 @@ interface RebuildResult {

// ── Node insertion ──────────────────────────────────────────────────────

/**
* Insert this file's node, its definitions and their children, and its
* exports — mirroring `insertDefinitionsAndExports`/`collectChildRowsAndFileEdges`
* in `stages/insert-nodes.ts` (the full-build path) so a symbol touched only
* by watch-mode rebuilds gets the same `qualified_name`/`scope`/`visibility`/
* `parent_id`/`content_hash`/`exported` columns a full or regular incremental
* `codegraph build` would have given it (issue #2220) — downstream queries
* that filter/join on those columns must not behave differently depending on
* which rebuild path last touched a symbol.
*
* `def.name` scoping mirrors insert-nodes.ts exactly: a dotted definition
* name (e.g. some extractors' `ClassName.methodName` convention) yields a
* `scope` of everything before the last dot; children get `parent_id` set to
* their def's real node id (looked up post-insert, not `lastInsertRowid`,
* since `INSERT OR IGNORE` leaves that unreliable for an already-existing
* row on a re-rebuild) and a `qualified_name` of `${def.name}.${child.name}`.
*/
function insertFileNodes(stmts: IncrementalStmts, relPath: string, symbols: ExtractorOutput): void {
stmts.insertNode.run(relPath, 'file', relPath, 0, null, null);
stmts.insertNode.run(relPath, 'file', relPath, 0, null, null, null, null, null, null, null);
for (const def of symbols.definitions) {
const dotIdx = def.name.lastIndexOf('.');
const scope = dotIdx !== -1 ? def.name.slice(0, dotIdx) : null;
stmts.insertNode.run(
def.name,
def.kind,
relPath,
def.line,
def.endLine || null,
null,
def.name,
scope,
def.visibility ?? null,
def.contentHash ?? null,
def.accessorKind ?? null,
);
if (def.children?.length) {
const defId = stmts.getNodeId.get(def.name, def.kind, relPath, def.line)?.id ?? null;
for (const child of def.children) {
stmts.insertNode.run(
child.name,
child.kind,
relPath,
child.line,
child.endLine || null,
defId,
`${def.name}.${child.name}`,
def.name,
child.visibility ?? null,
child.contentHash ?? null,
null,
);
}
}
}
for (const exp of symbols.exports) {
stmts.insertNode.run(exp.name, exp.kind, relPath, exp.line, null, null);
stmts.insertNode.run(
exp.name,
exp.kind,
relPath,
exp.line,
null,
null,
exp.name,
null,
null,
null,
null,
);
stmts.markExported.run(exp.name, exp.kind, relPath, exp.line);
}
}

Expand Down
11 changes: 10 additions & 1 deletion src/domain/graph/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,17 @@ function shouldIgnorePath(filePath: string, ignoreSet: ReadonlySet<string>): boo
/** Prepare all SQL statements needed by the watcher's incremental rebuild. */
function prepareWatcherStatements(db: ReturnType<typeof openDb>): IncrementalStmts {
return {
// Column set and order mirror the full-build path's getNodeStmt
// (src/domain/graph/builder/helpers.ts) — issue #2220: a symbol touched
// only by a watch-mode rebuild must get the same qualified_name/scope/
// visibility/parent_id/content_hash a full or regular incremental build
// would have given it.
insertNode: db.prepare(
'INSERT OR IGNORE INTO nodes (name, kind, file, line, end_line, accessor_kind) VALUES (?, ?, ?, ?, ?, ?)',
'INSERT OR IGNORE INTO nodes (name,kind,file,line,end_line,parent_id,qualified_name,scope,visibility,content_hash,accessor_kind) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
),
// Mirrors the full-build path's getExportStmt (issue #2220).
markExported: db.prepare(
'UPDATE nodes SET exported = 1 WHERE name = ? AND kind = ? AND file = ? AND line = ?',
),
getNodeId: {
get: (...params: unknown[]) => {
Expand Down
45 changes: 45 additions & 0 deletions tests/helpers/incremental-stmts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { getNodeId as getNodeIdQuery, type openDb } from '../../src/db/index.js';
import type { IncrementalStmts } from '../../src/domain/graph/builder/incremental.js';

/**
* Build the `IncrementalStmts` bundle `rebuildFile` needs, matching
* production's `prepareWatcherStatements` (`src/domain/graph/watcher.ts`)
* exactly — shared by every watch-mode/incremental integration test instead
* of each duplicating (and risking drifting out of sync with) the same set
* of prepared statements.
*/
export function createIncrementalStmts(db: ReturnType<typeof openDb>): IncrementalStmts {
return {
insertNode: db.prepare(
'INSERT OR IGNORE INTO nodes (name,kind,file,line,end_line,parent_id,qualified_name,scope,visibility,content_hash,accessor_kind) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
),
markExported: db.prepare(
'UPDATE nodes SET exported = 1 WHERE name = ? AND kind = ? AND file = ? AND line = ?',
),
getNodeId: {
get: (...params: unknown[]) => {
const [name, kind, file, line] = params as [string, string, string, number];
const id = getNodeIdQuery(db, name, kind, file, line);
return id != null ? { id } : undefined;
},
},
insertEdge: db.prepare(
'INSERT OR IGNORE INTO edges (source_id, target_id, kind, confidence, dynamic) VALUES (?, ?, ?, ?, ?)',
),
countNodes: db.prepare('SELECT COUNT(*) as c FROM nodes WHERE file = ?'),
countEdges: db.prepare(
'SELECT COUNT(*) as c FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
),
findNodeInFile: db.prepare(
"SELECT id, kind, file, line, accessor_kind AS accessorKind FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant') AND file = ?",
),
findNodeByName: db.prepare(
"SELECT id, file, kind, line, accessor_kind AS accessorKind FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')",
),
listSymbols: db.prepare("SELECT name, kind, line FROM nodes WHERE file = ? AND kind != 'file'"),
upsertFileHash: db.prepare(
'INSERT OR REPLACE INTO file_hashes (file, hash, mtime, size) VALUES (?, ?, ?, ?)',
),
deleteFileHash: db.prepare('DELETE FROM file_hashes WHERE file = ?'),
};
}
46 changes: 10 additions & 36 deletions tests/integration/issue-1259-watch-call-resolution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { getNodeId as getNodeIdQuery, initSchema, openDb } from '../../src/db/index.js';
import { initSchema, openDb } from '../../src/db/index.js';
import { rebuildFile } from '../../src/domain/graph/builder/incremental.js';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { createIncrementalStmts } from '../helpers/incremental-stmts.js';

// Files are laid out so that an unimported call to a same-named symbol in a
// distant directory resolves at confidence 0.3 (different grandparent dir) —
Expand Down Expand Up @@ -72,40 +73,6 @@ function readEdges(dbPath: string) {
}
}

/** Prepared statements the watcher normally supplies (mirrors watcher.ts). */
function makeStmts(db: ReturnType<typeof openDb>) {
return {
insertNode: db.prepare(
'INSERT OR IGNORE INTO nodes (name, kind, file, line, end_line, accessor_kind) VALUES (?, ?, ?, ?, ?, ?)',
),
getNodeId: {
get: (name: string, kind: string, file: string, line: number) => {
const id = getNodeIdQuery(db, name, kind, file, line);
return id != null ? { id } : undefined;
},
},
insertEdge: db.prepare(
'INSERT INTO edges (source_id, target_id, kind, confidence, dynamic) VALUES (?, ?, ?, ?, ?)',
),
countNodes: db.prepare('SELECT COUNT(*) as c FROM nodes WHERE file = ?'),
countEdges: db.prepare(
'SELECT COUNT(*) as c FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
),
findNodeInFile: db.prepare(
"SELECT id, kind, file FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant') AND file = ?",
),
findNodeByName: db.prepare(
// `kind` column included for resolveByMethodOrGlobal's method filter.
"SELECT id, file, kind FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')",
),
listSymbols: db.prepare("SELECT name, kind, line FROM nodes WHERE file = ? AND kind != 'file'"),
upsertFileHash: db.prepare(
'INSERT OR REPLACE INTO file_hashes (file, hash, mtime, size) VALUES (?, ?, ?, ?)',
),
deleteFileHash: db.prepare('DELETE FROM file_hashes WHERE file = ?'),
};
}

describe('Watch-mode call resolution parity (#1259)', () => {
let fullEdges: ReturnType<typeof readEdges>;
let watchEdges: ReturnType<typeof readEdges>;
Expand All @@ -131,7 +98,14 @@ describe('Watch-mode call resolution parity (#1259)', () => {
// consumer.js, which is where the resolver divergence manifested).
const db = openDb(path.join(watchDir, '.codegraph', 'graph.db'));
initSchema(db);
await rebuildFile(db, watchDir, watchLeaf, makeStmts(db), { engine: 'auto' }, null);
await rebuildFile(
db,
watchDir,
watchLeaf,
createIncrementalStmts(db),
{ engine: 'auto' },
null,
);
db.close();

// Same edit + clean full rebuild on the other copy for the parity oracle.
Expand Down
44 changes: 10 additions & 34 deletions tests/integration/issue-1370-incremental-caller-name.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { getNodeId as getNodeIdQuery, initSchema, openDb } from '../../src/db/index.js';
import { initSchema, openDb } from '../../src/db/index.js';
import { rebuildFile } from '../../src/domain/graph/builder/incremental.js';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { createIncrementalStmts } from '../helpers/incremental-stmts.js';

const FILES: Record<string, string> = {
'service.js': `
Expand Down Expand Up @@ -70,38 +71,6 @@ function readCallEdges(dbPath: string) {
}
}

function makeStmts(db: ReturnType<typeof openDb>) {
return {
insertNode: db.prepare(
'INSERT OR IGNORE INTO nodes (name, kind, file, line, end_line, accessor_kind) VALUES (?, ?, ?, ?, ?, ?)',
),
getNodeId: {
get: (name: string, kind: string, file: string, line: number) => {
const id = getNodeIdQuery(db, name, kind, file, line);
return id != null ? { id } : undefined;
},
},
insertEdge: db.prepare(
'INSERT INTO edges (source_id, target_id, kind, confidence, dynamic) VALUES (?, ?, ?, ?, ?)',
),
countNodes: db.prepare('SELECT COUNT(*) as c FROM nodes WHERE file = ?'),
countEdges: db.prepare(
'SELECT COUNT(*) as c FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
),
findNodeInFile: db.prepare(
"SELECT id, kind, file FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant') AND file = ?",
),
findNodeByName: db.prepare(
"SELECT id, file, kind FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')",
),
listSymbols: db.prepare("SELECT name, kind, line FROM nodes WHERE file = ? AND kind != 'file'"),
upsertFileHash: db.prepare(
'INSERT OR REPLACE INTO file_hashes (file, hash, mtime, size) VALUES (?, ?, ?, ?)',
),
deleteFileHash: db.prepare('DELETE FROM file_hashes WHERE file = ?'),
};
}

describe('Incremental rebuildFile passes callerName to resolver (#1370)', () => {
let fullEdges: ReturnType<typeof readCallEdges>;
let watchEdges: ReturnType<typeof readCallEdges>;
Expand All @@ -124,7 +93,14 @@ describe('Incremental rebuildFile passes callerName to resolver (#1370)', () =>
// Run the incremental watch path — this is where callerName was missing.
const db = openDb(path.join(watchDir, '.codegraph', 'graph.db'));
initSchema(db);
await rebuildFile(db, watchDir, watchFile, makeStmts(db), { engine: 'wasm' }, null);
await rebuildFile(
db,
watchDir,
watchFile,
createIncrementalStmts(db),
{ engine: 'wasm' },
null,
);
db.close();

// Apply the same touch to the full-build copy and rebuild from scratch.
Expand Down
39 changes: 4 additions & 35 deletions tests/integration/issue-1731-hash-edge-coupling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getNodeId as getNodeIdQuery, initSchema, openDb } from '../../src/db/index.js';
import { initSchema, openDb } from '../../src/db/index.js';
import { fileHash } from '../../src/domain/graph/builder/helpers.js';
import { rebuildFile } from '../../src/domain/graph/builder/incremental.js';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { createIncrementalStmts } from '../helpers/incremental-stmts.js';

// ── Fault injection for suite 1 ──────────────────────────────────────────
// A `vi.hoisted` object is used (rather than a plain module-scope `let`) so
Expand Down Expand Up @@ -160,38 +161,6 @@ describe('Issue #1731: file_hashes/edges coupling survives a mid-build failure',

// ── Suite 2: watch-mode rebuildFile ───────────────────────────────────────

function makeStmts(db: ReturnType<typeof openDb>) {
return {
insertNode: db.prepare(
'INSERT OR IGNORE INTO nodes (name, kind, file, line, end_line, accessor_kind) VALUES (?, ?, ?, ?, ?, ?)',
),
getNodeId: {
get: (name: string, kind: string, file: string, line: number) => {
const id = getNodeIdQuery(db, name, kind, file, line);
return id != null ? { id } : undefined;
},
},
insertEdge: db.prepare(
'INSERT INTO edges (source_id, target_id, kind, confidence, dynamic) VALUES (?, ?, ?, ?, ?)',
),
countNodes: db.prepare('SELECT COUNT(*) as c FROM nodes WHERE file = ?'),
countEdges: db.prepare(
'SELECT COUNT(*) as c FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
),
findNodeInFile: db.prepare(
"SELECT id, kind, file FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant') AND file = ?",
),
findNodeByName: db.prepare(
"SELECT id, file, kind FROM nodes WHERE name = ? AND kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')",
),
listSymbols: db.prepare("SELECT name, kind, line FROM nodes WHERE file = ? AND kind != 'file'"),
upsertFileHash: db.prepare(
'INSERT OR REPLACE INTO file_hashes (file, hash, mtime, size) VALUES (?, ?, ?, ?)',
),
deleteFileHash: db.prepare('DELETE FROM file_hashes WHERE file = ?'),
};
}

describe('Issue #1731: watch-mode rebuildFile keeps file_hashes in sync with edges', () => {
let tmpDir: string;
let dbPath: string;
Expand Down Expand Up @@ -220,7 +189,7 @@ describe('Issue #1731: watch-mode rebuildFile keeps file_hashes in sync with edg
const db = openDb(dbPath);
try {
initSchema(db);
const stmts = makeStmts(db);
const stmts = createIncrementalStmts(db);
await rebuildFile(db, tmpDir, path.join(tmpDir, 'a.js'), stmts, { engine: 'wasm' }, null);
} finally {
db.close();
Expand All @@ -240,7 +209,7 @@ describe('Issue #1731: watch-mode rebuildFile keeps file_hashes in sync with edg
const db = openDb(dbPath);
try {
initSchema(db);
const stmts = makeStmts(db);
const stmts = createIncrementalStmts(db);
await rebuildFile(db, tmpDir, path.join(tmpDir, 'a.js'), stmts, { engine: 'wasm' }, null);
} finally {
db.close();
Expand Down
Loading
Loading