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
7 changes: 7 additions & 0 deletions crates/codegraph-core/src/build_pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,13 @@ fn finalize_build(conn: &Connection, root_dir: &str) -> (i64, i64) {
let _ = stmt.execute(["node_count", &node_count.to_string()]);
let _ = stmt.execute(["edge_count", &edge_count.to_string()]);
let _ = stmt.execute(["last_build", &now_ms().to_string()]);
// Persist repo root so downstream commands (e.g. `codegraph embed`)
// can resolve relative file paths regardless of invoking cwd.
let root_canon = std::fs::canonicalize(root_dir)
.ok()
.and_then(|p| p.to_str().map(|s| s.to_string()))
.unwrap_or_else(|| root_dir.to_string());
let _ = stmt.execute(["root_dir", &root_canon]);
Comment on lines +708 to +712
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Symlink inconsistency between Rust and JS root_dir writes

The Rust finalize_build persists root_dir using std::fs::canonicalize (resolves symlinks), but the JS persistBuildMetadata in finalize.ts then overwrites the same key with path.resolve(ctx.rootDir) (which does not resolve symlinks) for any full build using the native engine. On systems where the project root is behind a symlink, these two values can differ — and the JS write wins for full builds, potentially re-introducing the wrong path just after Rust correctly wrote the canonical one.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e48690c. Good catch — for native full builds the JS persistBuildMetadata runs after finalize_build and would overwrite the canonical Rust value. Switched the JS write to fs.realpathSync(path.resolve(ctx.rootDir)) so both engines agree on a symlink-resolved canonical path; kept a safe fallback to path.resolve if realpath throws (e.g. path removed mid-build).

}

// Write journal header
Expand Down
16 changes: 16 additions & 0 deletions src/domain/graph/builder/stages/finalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* WASM cleanup, stats logging, drift detection, build metadata, registry, journal.
*/
import fs from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { performance } from 'node:perf_hooks';
Expand Down Expand Up @@ -88,6 +89,19 @@ function persistBuildMetadata(
// subsequent build to be a full rebuild.
const codeVersionToWrite =
ctx.engineName === 'native' && ctx.engineVersion ? ctx.engineVersion : CODEGRAPH_VERSION;
// Persist the repo root so downstream commands (e.g. `codegraph embed`)
// can resolve relative file paths regardless of the invoking cwd.
// Use realpathSync (symlink-resolving) to match the Rust engine's
// std::fs::canonicalize — otherwise the JS write here would overwrite the
// canonical path Rust wrote for native full builds and could re-introduce
// a non-canonical path when the project root is behind a symlink.
const resolvedRootDir = path.resolve(ctx.rootDir);
let rootDirToWrite = resolvedRootDir;
try {
rootDirToWrite = fs.realpathSync(resolvedRootDir);
} catch {
/* realpath can fail (e.g. path no longer exists); fall back to resolve() */
}
try {
if (useNativeDb) {
ctx.nativeDb!.setBuildMeta(
Expand All @@ -99,6 +113,7 @@ function persistBuildMetadata(
built_at: buildNow.toISOString(),
node_count: String(nodeCount),
edge_count: String(actualEdgeCount),
root_dir: rootDirToWrite,
}).map(([key, value]) => ({ key, value: String(value) })),
);
} else {
Expand All @@ -110,6 +125,7 @@ function persistBuildMetadata(
built_at: buildNow.toISOString(),
node_count: nodeCount,
edge_count: actualEdgeCount,
root_dir: rootDirToWrite,
});
}
} catch (err) {
Expand Down
36 changes: 34 additions & 2 deletions src/domain/search/generator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
import { closeDb, findDbPath, openDb } from '../../db/index.js';
import { closeDb, findDbPath, getBuildMeta, openDb } from '../../db/index.js';
import { warn } from '../../infrastructure/logger.js';
import { DbError } from '../../shared/errors.js';
import type { BetterSqlite3Database, NodeRow } from '../../types.js';
Expand Down Expand Up @@ -73,6 +73,21 @@ export async function buildEmbeddings(
const db = openDb(dbPath) as BetterSqlite3Database;
initEmbeddingsSchema(db);

// Prefer the repo root recorded at build time — embed may be invoked from a
// different cwd (e.g. `codegraph embed --db /abs/path/graph.db`) and the
// positional rootDir will be wrong in that case. For legacy DBs without
// root_dir metadata, fall back to `<dbParent>` only when the DB lives at
// the conventional `<root>/.codegraph/graph.db` layout — otherwise trust
// the caller-provided rootDir (which may be an explicit positional arg).
// `path.dirname(...)` is always non-empty (`'.'` at minimum), so the
// conventional-layout check is required to keep the rootDir path reachable.
const metaRoot = getBuildMeta(db, 'root_dir');
const resolvedDbPath = path.resolve(dbPath);
const dbDirName = path.basename(path.dirname(resolvedDbPath));
const dbParent =
dbDirName === '.codegraph' ? path.dirname(path.dirname(resolvedDbPath)) : undefined;
const resolvedRoot = metaRoot || dbParent || rootDir;

db.exec('DELETE FROM embeddings');
db.exec('DELETE FROM embedding_meta');
db.exec('DELETE FROM fts_index');
Expand All @@ -98,13 +113,17 @@ export async function buildEmbeddings(
const config = getModelConfig(modelKey);
const contextWindow = config.contextWindow;
let overflowCount = 0;
let filesRead = 0;
let filesSkipped = 0;

for (const [file, fileNodes] of byFile) {
const fullPath = path.isAbsolute(file) ? file : path.join(rootDir, file);
const fullPath = path.isAbsolute(file) ? file : path.join(resolvedRoot, file);
let lines: string[];
try {
lines = fs.readFileSync(fullPath, 'utf-8').split('\n');
filesRead++;
} catch (err: unknown) {
filesSkipped++;
warn(`Cannot read ${file} for embeddings: ${(err as Error).message}`);
continue;
}
Expand Down Expand Up @@ -136,6 +155,19 @@ export async function buildEmbeddings(
);
}

// If there were symbols to embed but every file failed to read, the DB was
// almost certainly built from a different location than the current cwd.
// Surface this clearly instead of emitting a silent "Stored 0 embeddings".
if (byFile.size > 0 && filesRead === 0) {
closeDb(db);
throw new DbError(
`embed: could not read any of the ${filesSkipped} source files recorded in the graph — the DB may have been built from a different location than the current working directory.\n` +
`Tried resolving against: ${resolvedRoot}\n` +
'Pass a positional <dir> argument pointing at the original repo root, or re-run "codegraph build" from that directory.',
{ file: dbPath },
);
}

console.log(`Embedding ${texts.length} symbols...`);
const { vectors, dim } = await embed(texts, modelKey);

Expand Down
120 changes: 120 additions & 0 deletions tests/search/embedding-strategy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,126 @@ describe('absolute file paths in DB (#752)', () => {
});
});

describe('embed resolves source files from DB root, not cwd (#983)', () => {
let repoDir: string, otherDir: string, repoDbPath: string;
let originalCwd: string;

beforeAll(() => {
// Repo that was built (files live here)
repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-embed983-repo-'));
// Unrelated directory we'll cd into when running embed
otherDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-embed983-other-'));

fs.writeFileSync(
path.join(repoDir, 'a.js'),
'export function alpha() { return 1; }\nexport function beta() { return alpha(); }\n',
);

const dbDir = path.join(repoDir, '.codegraph');
fs.mkdirSync(dbDir, { recursive: true });
repoDbPath = path.join(dbDir, 'graph.db');

const db = new Database(repoDbPath);
db.pragma('journal_mode = WAL');
initSchema(db);
// DB stores *relative* file paths (typical of WASM-engine builds)
insertNode(db, 'alpha', 'function', 'a.js', 1, 1);
insertNode(db, 'beta', 'function', 'a.js', 2, 2);
// Persist the repo root as the build pipeline would
db.prepare('INSERT OR REPLACE INTO build_meta (key, value) VALUES (?, ?)').run(
'root_dir',
path.resolve(repoDir),
);
db.close();

originalCwd = process.cwd();
});

afterAll(() => {
try {
process.chdir(originalCwd);
} catch {
/* ignore */
}
if (repoDir) fs.rmSync(repoDir, { recursive: true, force: true });
if (otherDir) fs.rmSync(otherDir, { recursive: true, force: true });
});

test('uses root_dir metadata when embed is invoked from unrelated cwd', async () => {
EMBEDDED_TEXTS.length = 0;
process.chdir(otherDir);

// Simulate the CLI: positional dir defaults to cwd (here: otherDir), DB path is absolute
await buildEmbeddings(process.cwd(), 'minilm', repoDbPath);

expect(EMBEDDED_TEXTS.length).toBe(2);

const db = new Database(repoDbPath, { readonly: true });
const count = db.prepare('SELECT COUNT(*) as c FROM embeddings').get().c;
db.close();
expect(count).toBe(2);
});

test('falls back to <dbPath>/../.. when root_dir metadata is missing', async () => {
// Build a fresh DB without root_dir metadata
const legacyRepo = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-embed983-legacy-'));
try {
fs.writeFileSync(path.join(legacyRepo, 'b.js'), 'export function gamma() { return 42; }\n');
const legacyDbDir = path.join(legacyRepo, '.codegraph');
fs.mkdirSync(legacyDbDir, { recursive: true });
const legacyDb = path.join(legacyDbDir, 'graph.db');

const db = new Database(legacyDb);
db.pragma('journal_mode = WAL');
initSchema(db);
insertNode(db, 'gamma', 'function', 'b.js', 1, 1);
// Deliberately NOT writing root_dir — simulates DB built before #983 fix
db.close();

EMBEDDED_TEXTS.length = 0;
process.chdir(otherDir);
await buildEmbeddings(process.cwd(), 'minilm', legacyDb);

expect(EMBEDDED_TEXTS.length).toBe(1);
} finally {
fs.rmSync(legacyRepo, { recursive: true, force: true });
}
});

test('exits non-zero (throws) when no source files can be read', async () => {
// Build a DB pointing at files that no longer exist
const ghostRepo = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-embed983-ghost-'));
try {
const ghostDbDir = path.join(ghostRepo, '.codegraph');
fs.mkdirSync(ghostDbDir, { recursive: true });
const ghostDb = path.join(ghostDbDir, 'graph.db');

const db = new Database(ghostDb);
db.pragma('journal_mode = WAL');
initSchema(db);
insertNode(db, 'missing', 'function', 'does-not-exist.js', 1, 1);
db.prepare('INSERT OR REPLACE INTO build_meta (key, value) VALUES (?, ?)').run(
'root_dir',
path.resolve(ghostRepo),
);
db.close();

EMBEDDED_TEXTS.length = 0;
await expect(buildEmbeddings(ghostRepo, 'minilm', ghostDb)).rejects.toThrow(
/could not read any of the .* source files/,
);

// No embeddings were persisted (they would have been overwritten via DELETE)
const readDb = new Database(ghostDb, { readonly: true });
const count = readDb.prepare('SELECT COUNT(*) as c FROM embeddings').get().c;
readDb.close();
expect(count).toBe(0);
} finally {
fs.rmSync(ghostRepo, { recursive: true, force: true });
}
});
Comment on lines +424 to +455
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Temp dir leak on test failure

ghostRepo (and similarly legacyRepo in the test above) is cleaned up inside the test body. If buildEmbeddings throws unexpectedly before reaching fs.rmSync, the temp directory is leaked. Both should be created in beforeAll and cleaned in afterAll, or at minimum use a try/finally block.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f99f10e. Wrapped both ghostRepo and legacyRepo tests in try/finally blocks so the temp dirs are always cleaned up even if buildEmbeddings throws unexpectedly mid-test.

});

describe('context window overflow detection', () => {
let bigDir: string, bigDbPath: string;

Expand Down
Loading