Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
75978e2
fix: recognize Lua function nodes in complexity metrics computation (…
carlos-alm Jul 6, 2026
af17b6d
fix: scope global call-resolution fallback to same-language candidate…
carlos-alm Jul 6, 2026
dd447bc
fix: credit instanceof ClassName checks as exports consumers
carlos-alm Jul 6, 2026
a79a8a1
fix: update automated-review workflow to use current claude-code-acti…
carlos-alm Jul 6, 2026
d84f6b5
refactor: widen outputResult signature, remove redundant casts at cal…
carlos-alm Jul 6, 2026
e7a2255
fix: port Leiden algorithm to native Rust for cross-engine community-…
carlos-alm Jul 7, 2026
b54972a
feat: detect exported-symbol loss from full file deletion in checkNoS…
carlos-alm Jul 7, 2026
1821a8b
fix(complexity): scope summary stats to file/target/kind filters
carlos-alm Jul 7, 2026
d45aba7
fix(extractors): label property_signature interface/type members as k…
carlos-alm Jul 7, 2026
69d8a6f
fix(roles): exclude genuine class/struct properties from dead-role cl…
carlos-alm Jul 7, 2026
db08219
fix(resolver): scope extends/implements edges to same-file/import/lan…
carlos-alm Jul 7, 2026
79cd761
fix: track inline per-specifier type-only import modifier
carlos-alm Jul 7, 2026
cbfa954
fix(native): widen NativeRepository file filters to accept string[]
carlos-alm Jul 7, 2026
c0e7eae
fix(native): remove unused source param from get_first_call_arg
carlos-alm Jul 7, 2026
2dabe21
fix(extractors): align native/WASM definitions order for object-liter…
carlos-alm Jul 7, 2026
b1eb9af
fix(extractors): capture top-level const definitions regardless of in…
carlos-alm Jul 7, 2026
4a1e279
fix: exclude PHP scalar type-hint/cast keywords from ast --kind string
carlos-alm Jul 7, 2026
40b5e24
fix: track barrel re-export renames (export { X as Y } from ...)
carlos-alm Jul 7, 2026
1506896
fix: record local alias for dynamic import() destructuring renames
carlos-alm Jul 7, 2026
2dfd6bc
fix: resolve renamed-import receiver calls in qualified-method lookup
carlos-alm Jul 7, 2026
ccea0cb
fix(native): propagate edge/node write failures out of run_pipeline
carlos-alm Jul 7, 2026
93ccfa3
fix(exports): discriminate file-level from symbol-level consumer entries
carlos-alm Jul 7, 2026
e105c26
docs: refresh CONTRIBUTING.md for TypeScript architecture and current…
carlos-alm Jul 7, 2026
5d99bf0
fix(exports): credit plain imports of TypeScript interfaces/type aliases
carlos-alm Jul 7, 2026
e0ab9dc
fix(hooks): point update-graph.sh fallback build path at dist/cli.js
carlos-alm Jul 7, 2026
730b49b
fix(hooks): resolve track-edits.sh's PROJECT_DIR from the edited file…
carlos-alm Jul 7, 2026
0d7e8e6
fix: capture removed files' cross-directory neighbors before purge
carlos-alm Jul 7, 2026
c5b9a34
docs: fix stale codegraph check flag names in recommended-practices.md
carlos-alm Jul 7, 2026
2de6550
fix(cycles): classify cycles whose only closing edges are speculative
carlos-alm Jul 7, 2026
e5fe754
fix(resolver): recognize identifier args to user-defined higher-order…
carlos-alm Jul 8, 2026
4eef28e
fix(native): scope barrel-only import skipping to transient barrel re…
carlos-alm Jul 8, 2026
4090355
refactor(ast-analysis): extract shared CFG/complexity result-merging …
carlos-alm Jul 8, 2026
bf8e969
fix(incremental): port CHA/RTA dispatch, points-to, and dynamic-sink …
carlos-alm Jul 8, 2026
51b9e23
fix(config): derive ENV_LLM_KEYS from ENV_LLM_MAP to prevent drift
carlos-alm Jul 8, 2026
a62bab7
fix(resolver): resolveByGlobal picks the single best match, not every…
carlos-alm Jul 8, 2026
8f52d28
fix(embed): resolve default DB path from positional dir, not cwd
carlos-alm Jul 8, 2026
59220a5
refactor(leiden): extract makePartition's inline getters to cut cyclo…
carlos-alm Jul 8, 2026
2e1aa11
docs: regenerate stale audit/diff-impact example output blocks
carlos-alm Jul 8, 2026
3d436ca
fix(rust): resolve self.field, unit-struct, and constructor-typed locals
carlos-alm Jul 8, 2026
668451c
docs: add missing titan-grind mirror to claude-code-skills examples
carlos-alm Jul 8, 2026
4bccd4b
fix(scripts): migrate ts-resolve-loader.js off deprecated module.regi…
carlos-alm Jul 8, 2026
25ba42f
fix(native): recover renamed import names in the FFI hybrid import-ed…
carlos-alm Jul 8, 2026
431c0e5
fix: reconnect reverse-dep edges correctly when a sibling group's siz…
carlos-alm Jul 8, 2026
ab6a685
fix: derive loadConfig() rootDir from --db path in read-only query fu…
carlos-alm Jul 8, 2026
17e265b
fix(native): thread config.db.busyTimeoutMs into NativeDatabase open …
carlos-alm Jul 8, 2026
1e104f1
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 10, 2026
c90afdf
test(native-db): cover the remaining 3 busyTimeoutMs threading call s…
carlos-alm Jul 10, 2026
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
31 changes: 23 additions & 8 deletions crates/codegraph-core/src/db/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ use crate::db::repository::edges::{self, EdgeRow};
use crate::domain::graph::builder::stages::insert_nodes::{self, FileHashEntry, InsertNodesBatch};
use crate::graph::classifiers::roles::{self, RoleSummary};

/// Fallback `PRAGMA busy_timeout` (ms) used when the caller doesn't pass a
/// resolved value. Mirrors `DEFAULTS.db.busyTimeoutMs` in
/// `src/infrastructure/config.ts` — keep both in sync.
const DEFAULT_BUSY_TIMEOUT_MS: u32 = 5000;

// ── Migration DDL (mirrored from src/db/migrations.ts) ──────────────────

struct Migration {
Expand Down Expand Up @@ -483,8 +488,12 @@ pub struct NativeDatabase {
impl NativeDatabase {
/// Open a read-write connection to the database at `db_path`.
/// Creates the file and parent directories if they don't exist.
///
/// `busy_timeout_ms` mirrors `config.db.busyTimeoutMs` on the TS side
/// (`DEFAULTS.db.busyTimeoutMs` in `src/infrastructure/config.ts`);
/// defaults to `DEFAULT_BUSY_TIMEOUT_MS` when omitted.
#[napi(factory)]
pub fn open_read_write(db_path: String) -> napi::Result<Self> {
pub fn open_read_write(db_path: String, busy_timeout_ms: Option<u32>) -> napi::Result<Self> {
let flags = OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_NO_MUTEX;
Expand All @@ -498,12 +507,13 @@ impl NativeDatabase {
// are not cache-coherent on Windows, leading to SQLITE_CORRUPT (#715).
// Read-only connections keep mmap since they don't share a WAL file
// with a concurrent writer from a different library.
conn.execute_batch(
let busy_timeout_ms = busy_timeout_ms.unwrap_or(DEFAULT_BUSY_TIMEOUT_MS);
conn.execute_batch(&format!(
"PRAGMA journal_mode = WAL; \
PRAGMA synchronous = NORMAL; \
PRAGMA busy_timeout = 5000; \
PRAGMA busy_timeout = {busy_timeout_ms}; \
PRAGMA temp_store = MEMORY;",
)
))
.map_err(|e| napi::Error::from_reason(format!("Failed to set pragmas: {e}")))?;
Ok(Self {
conn: SendWrapper::new(Some(conn)),
Expand All @@ -512,17 +522,22 @@ impl NativeDatabase {
}

/// Open a read-only connection to the database at `db_path`.
///
/// `busy_timeout_ms` mirrors `config.db.busyTimeoutMs` on the TS side
/// (`DEFAULTS.db.busyTimeoutMs` in `src/infrastructure/config.ts`);
/// defaults to `DEFAULT_BUSY_TIMEOUT_MS` when omitted.
#[napi(factory)]
pub fn open_readonly(db_path: String) -> napi::Result<Self> {
pub fn open_readonly(db_path: String, busy_timeout_ms: Option<u32>) -> napi::Result<Self> {
let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = Connection::open_with_flags(&db_path, flags)
.map_err(|e| napi::Error::from_reason(format!("Failed to open DB readonly: {e}")))?;
conn.set_prepared_statement_cache_capacity(64);
conn.execute_batch(
"PRAGMA busy_timeout = 5000; \
let busy_timeout_ms = busy_timeout_ms.unwrap_or(DEFAULT_BUSY_TIMEOUT_MS);
conn.execute_batch(&format!(
"PRAGMA busy_timeout = {busy_timeout_ms}; \
PRAGMA mmap_size = 268435456; \
PRAGMA temp_store = MEMORY;",
)
))
.map_err(|e| napi::Error::from_reason(format!("Failed to set pragmas: {e}")))?;
Ok(Self {
conn: SendWrapper::new(Some(conn)),
Expand Down
14 changes: 9 additions & 5 deletions src/db/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,10 @@ export function resolveBusyTimeoutMs(customDbPath?: string, config?: CodegraphCo
}

/** Open a NativeRepository via rusqlite, throwing DbError if the DB file is missing. */
function openRepoNative(customDbPath?: string): { repo: Repository; close(): void } {
function openRepoNative(
customDbPath: string | undefined,
busyTimeoutMs: number,
): { repo: Repository; close(): void } {
const dbPath = findDbPath(customDbPath);
if (!fs.existsSync(dbPath)) {
throw new DbError(
Expand All @@ -484,7 +487,7 @@ function openRepoNative(customDbPath?: string): { repo: Repository; close(): voi
);
}
const native = getNative();
const ndb = native.NativeDatabase.openReadonly(dbPath);
const ndb = native.NativeDatabase.openReadonly(dbPath, busyTimeoutMs);
try {
warnOnVersionMismatch(() => ndb.getBuildMeta('codegraph_version'));
const repo = new NativeRepository(ndb, dbPath);
Expand Down Expand Up @@ -530,10 +533,11 @@ function wrapInjectedRepo(repo: Repository): { repo: Repository; close(): void }
function tryOpenRepoNative(
customDbPath: string | undefined,
engine: 'native' | 'wasm' | 'auto',
busyTimeoutMs: number,
): { repo: Repository; close(): void } | undefined {
if (engine === 'wasm' || !isNativeAvailable()) return undefined;
try {
return openRepoNative(customDbPath);
return openRepoNative(customDbPath, busyTimeoutMs);
} catch (e) {
// Re-throw user-visible errors (e.g. DB not found) — only silently
// fall back for native-engine failures (e.g. incompatible native binary).
Expand Down Expand Up @@ -583,7 +587,7 @@ export function openRepo(
// This ensures --engine wasm and benchmark workers bypass the native path.
const { engine, busyTimeoutMs } = resolveDbSettings(customDbPath, opts.engine);

const native = tryOpenRepoNative(customDbPath, engine);
const native = tryOpenRepoNative(customDbPath, engine, busyTimeoutMs);
if (native) return native;

return openRepoSqliteFallback(customDbPath, busyTimeoutMs);
Expand Down Expand Up @@ -623,7 +627,7 @@ export function openReadonlyWithNative(
try {
const dbPath = findDbPath(customPath);
const native = getNative();
nativeDb = native.NativeDatabase.openReadonly(dbPath);
nativeDb = native.NativeDatabase.openReadonly(dbPath, busyTimeoutMs);
} catch (e) {
const msg = toErrorMessage(e);
if (isBusyOrLockedError(msg)) {
Expand Down
2 changes: 1 addition & 1 deletion src/domain/graph/builder/stages/native-db-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function reopenNativeDb(ctx: PipelineContext, label: string): void {
const native = loadNative();
if (!native?.NativeDatabase) return;
try {
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath, ctx.config.db.busyTimeoutMs);
} catch (e) {
debug(`reopen nativeDb for ${label} failed: ${toErrorMessage(e)}`);
ctx.nativeDb = undefined;
Expand Down
8 changes: 4 additions & 4 deletions src/domain/graph/builder/stages/native-orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ async function runDataflowVertexPass(
* Used when the Rust addon doesn't include analysis persistence (older addon
* version) or when analysis failed on the Rust side.
*/
async function runPostNativeAnalysis(
export async function runPostNativeAnalysis(
ctx: PipelineContext,
allFileSymbols: Map<string, ExtractorOutput>,
changedFiles: string[] | undefined,
Expand All @@ -579,7 +579,7 @@ async function runPostNativeAnalysis(
const native = loadNative();
if (native?.NativeDatabase) {
try {
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath, ctx.config.db.busyTimeoutMs);
if (ctx.engineOpts) ctx.engineOpts.nativeDb = ctx.nativeDb;
} catch {
ctx.nativeDb = undefined;
Expand Down Expand Up @@ -1950,7 +1950,7 @@ function backfillEdgeTechniquesAfterNativeOrchestrator(
* corruption. On setup failure, falls back to reopening better-sqlite3 and
* leaves ctx.nativeDb undefined so the caller falls through to the JS pipeline.
*/
function openNativeDatabase(ctx: PipelineContext): void {
export function openNativeDatabase(ctx: PipelineContext): void {
if (ctx.nativeDb || !ctx.nativeAvailable) return;
const native = loadNative();
if (!native?.NativeDatabase) return;
Expand All @@ -1960,7 +1960,7 @@ function openNativeDatabase(ctx: PipelineContext): void {
// is kept and transferred to the NativeDbProxy below, not released here.
ctx.db.close();
acquireAdvisoryLock(ctx.dbPath);
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath, ctx.config.db.busyTimeoutMs);
ctx.nativeDb.initSchema();
// Replace ctx.db with a NativeDbProxy so post-native JS fallback
// (structure, analysis) can use it without reopening better-sqlite3.
Expand Down
5 changes: 3 additions & 2 deletions src/features/branch-compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { getDatabase } from '../db/better-sqlite3.js';
import { resolveBusyTimeoutMs } from '../db/index.js';
import { buildGraph } from '../domain/graph/builder.js';
import { kindIcon } from '../domain/queries.js';
import { debug } from '../infrastructure/logger.js';
Expand Down Expand Up @@ -116,11 +117,11 @@ interface RawNodeRow {
}

/** Try opening a NativeDatabase handle for batched fan-in/fan-out metrics. */
function openNativeDbForFanMetrics(dbPath: string): NativeDatabase | undefined {
export function openNativeDbForFanMetrics(dbPath: string): NativeDatabase | undefined {
if (!isNativeAvailable()) return undefined;
try {
const native = getNative();
return native.NativeDatabase.openReadonly(dbPath);
return native.NativeDatabase.openReadonly(dbPath, resolveBusyTimeoutMs(dbPath));
} catch (e) {
debug(`loadSymbolsFromDb: native path failed: ${toErrorMessage(e)}`);
return undefined;
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2390,8 +2390,8 @@ export interface NativeAddon {
extractDataflowAnalysisBatch?(filePaths: string[]): (DataflowResult | null)[];
ParseTreeCache: new () => NativeParseTreeCache;
NativeDatabase: {
openReadWrite(dbPath: string): NativeDatabase;
openReadonly(dbPath: string): NativeDatabase;
openReadWrite(dbPath: string, busyTimeoutMs?: number): NativeDatabase;
openReadonly(dbPath: string, busyTimeoutMs?: number): NativeDatabase;
};
}

Expand Down
172 changes: 172 additions & 0 deletions tests/unit/native-db-busy-timeout-threading.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/**
* Regression tests for issue #1882: the JS call sites that open a
* `NativeDatabase` must pass the resolved `config.db.busyTimeoutMs` through
* as the factory's `busyTimeoutMs` argument, instead of silently relying on
* the Rust-side hardcoded default.
*
* Mocks `infrastructure/native.js` (the same pattern as
* `tests/unit/openRepo-busy.test.ts`) so the assertions are about *what
* argument each call site passes*, independent of whether a native addon is
* actually built for the current platform.
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';

const CUSTOM_BUSY_TIMEOUT_MS = 424242;

const openReadonlyCalls: Array<[string, number | undefined]> = [];
const openReadWriteCalls: Array<[string, number | undefined]> = [];

function makeFakeNativeDb() {
return {
getBuildMeta: () => null,
close: () => {},
initSchema: () => {},
exec: () => {},
};
}

vi.mock('../../src/infrastructure/native.js', () => ({
isNativeAvailable: () => true,
getNative: () => ({
NativeDatabase: {
openReadonly: (dbPath: string, busyTimeoutMs?: number) => {
openReadonlyCalls.push([dbPath, busyTimeoutMs]);
return makeFakeNativeDb();
},
openReadWrite: (dbPath: string, busyTimeoutMs?: number) => {
openReadWriteCalls.push([dbPath, busyTimeoutMs]);
return makeFakeNativeDb();
},
},
}),
loadNative: () => ({
NativeDatabase: {
openReadonly: (dbPath: string, busyTimeoutMs?: number) => {
openReadonlyCalls.push([dbPath, busyTimeoutMs]);
return makeFakeNativeDb();
},
openReadWrite: (dbPath: string, busyTimeoutMs?: number) => {
openReadWriteCalls.push([dbPath, busyTimeoutMs]);
return makeFakeNativeDb();
},
},
}),
}));

import {
closeDb,
initSchema,
openDb,
openReadonlyWithNative,
openRepo,
} from '../../src/db/index.js';
import { PipelineContext } from '../../src/domain/graph/builder/context.js';
import { reopenNativeDb } from '../../src/domain/graph/builder/stages/native-db-lifecycle.js';
import {
openNativeDatabase,
runPostNativeAnalysis,
} from '../../src/domain/graph/builder/stages/native-orchestrator.js';
import { openNativeDbForFanMetrics } from '../../src/features/branch-compare.js';

let tmpDir: string;
let dbPath: string;

beforeAll(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-native-busy-threading-'));
dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const db = openDb(dbPath);
initSchema(db);
closeDb(db);
fs.writeFileSync(
path.join(tmpDir, '.codegraphrc.json'),
JSON.stringify({ db: { busyTimeoutMs: CUSTOM_BUSY_TIMEOUT_MS } }),
);
});

afterAll(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
});

describe('openRepo threads busyTimeoutMs into NativeDatabase.openReadonly', () => {
it('passes the configured busyTimeoutMs to the native factory', () => {
openReadonlyCalls.length = 0;
const { close } = openRepo(dbPath);
close();
expect(openReadonlyCalls).toHaveLength(1);
expect(openReadonlyCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});

describe('openReadonlyWithNative threads busyTimeoutMs into NativeDatabase.openReadonly', () => {
it('passes the configured busyTimeoutMs to the native factory', () => {
openReadonlyCalls.length = 0;
const { close } = openReadonlyWithNative(dbPath);
close();
expect(openReadonlyCalls).toHaveLength(1);
expect(openReadonlyCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});

describe('reopenNativeDb (build pipeline) threads ctx.config.db.busyTimeoutMs into NativeDatabase.openReadWrite', () => {
it('passes ctx.config.db.busyTimeoutMs to the native factory', () => {
openReadWriteCalls.length = 0;
const ctx = new PipelineContext();
ctx.dbPath = dbPath;
ctx.opts = { engine: 'native' };
ctx.config = { db: { busyTimeoutMs: CUSTOM_BUSY_TIMEOUT_MS } } as PipelineContext['config'];

reopenNativeDb(ctx, 'test');

expect(openReadWriteCalls).toHaveLength(1);
expect(openReadWriteCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});
Comment on lines +114 to +126

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 Threading test covers 3 of 6 call sites

The threading test asserts that openRepo, openReadonlyWithNative, and reopenNativeDb all forward busyTimeoutMs. However, three changed call sites are not exercised here: openNativeDatabase (~line 1955 in native-orchestrator.ts), runPostNativeAnalysis (~line 579 in native-orchestrator.ts), and openNativeDbForFanMetrics in branch-compare.ts. A future regression in those paths would go unnoticed by this test suite.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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 — added test cases for all 3 remaining call sites (openNativeDatabase, runPostNativeAnalysis, openNativeDbForFanMetrics) in c90afdf, exporting each function since they were previously module-private. All 6 threading assertions now pass.


describe('openNativeDatabase (build pipeline) threads ctx.config.db.busyTimeoutMs into NativeDatabase.openReadWrite', () => {
it('passes ctx.config.db.busyTimeoutMs to the native factory', () => {
openReadWriteCalls.length = 0;
const ctx = new PipelineContext();
ctx.dbPath = dbPath;
ctx.db = { close: () => {} } as PipelineContext['db'];
ctx.nativeAvailable = true;
ctx.config = { db: { busyTimeoutMs: CUSTOM_BUSY_TIMEOUT_MS } } as PipelineContext['config'];

openNativeDatabase(ctx);

expect(openReadWriteCalls).toHaveLength(1);
expect(openReadWriteCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});

describe('runPostNativeAnalysis (build pipeline) threads ctx.config.db.busyTimeoutMs into NativeDatabase.openReadWrite', () => {
it('passes ctx.config.db.busyTimeoutMs to the native factory', async () => {
openReadWriteCalls.length = 0;
const ctx = new PipelineContext();
ctx.dbPath = dbPath;
ctx.db = openDb(dbPath);
ctx.rootDir = tmpDir;
ctx.opts = { engine: 'native' };
ctx.config = { db: { busyTimeoutMs: CUSTOM_BUSY_TIMEOUT_MS } } as PipelineContext['config'];

try {
await runPostNativeAnalysis(ctx, new Map(), []);
} finally {
closeDb(ctx.db as Parameters<typeof closeDb>[0]);
}

expect(openReadWriteCalls).toHaveLength(1);
expect(openReadWriteCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});

describe('openNativeDbForFanMetrics (branch-compare) threads the configured busyTimeoutMs into NativeDatabase.openReadonly', () => {
it('passes the configured busyTimeoutMs to the native factory', () => {
openReadonlyCalls.length = 0;
openNativeDbForFanMetrics(dbPath);
expect(openReadonlyCalls).toHaveLength(1);
expect(openReadonlyCalls[0]?.[1]).toBe(CUSTOM_BUSY_TIMEOUT_MS);
});
});
Loading
Loading