GitNexus/gitnexus/test/integration/lbug-core-adapter.test.ts
Abhigyan Patwari 60c93d7d4a
feat: upgrade @ladybugdb/core to 0.15.2 and remove segfault workarounds (#374)
* feat: upgrade @ladybugdb/core to 0.15.2 and remove segfault workarounds

The upstream fix (ladybug-nodejs#1) resolves the child QueryResult lifetime
segfault, making .close() safe on all platforms. This removes 6 workaround
sites:

- Remove `dangerouslyIgnoreUnhandledErrors` from vitest config
- Remove platform-conditional .close() guards in global-setup and test helper
- Delete test/setup.ts (process._getActiveHandles unref hack)
- Replace no-op cleanup in test-indexed-db.ts with real adapter close
- Fix pool adapter closeOne() to properly close connections with shared
  Database refcount guard and orphaned connection handling in checkin()
- Update segfault-related comments across the codebase

Also bumps @ladybugdb/wasm-core to ^0.15.2 in gitnexus-web for consistency.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: keep dangerouslyIgnoreUnhandledErrors for macOS N-API exit crash

The N-API destructor ordering crash during worker fork exit on macOS is
independent of the QueryResult lifetime fix in 0.15.2. Tests pass, but
the exit triggers a crash. Keep the flag with an updated comment
explaining the actual cause. Can be removed once LadybugDB fixes all
destructor ordering issues upstream.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ci: unify test run for single-pass coverage

- Update `npm test` to run all tests (unit + integration + lbug-db)
  via `vitest run` instead of `vitest run test/unit`
- Add `test:unit` script for running unit tests only
- Remove `ci-integration.yml` — the per-file lbug-db process isolation
  is no longer needed with `dangerouslyIgnoreUnhandledErrors` and
  `fileParallelism: false` handling fork exit issues
- Update `ci-unit-tests.yml` to run all tests with build + coverage
- Simplify `ci.yml` gate (two jobs: quality + tests)
- Simplify `ci-report.yml` (single coverage artifact, no merge step)

* fix: update cli-commands test for renamed test:all → test:unit script

* fix: set USERPROFILE in setup-skills test for Windows compatibility

os.homedir() checks USERPROFILE on Windows, not HOME.

* fix: add isolate: false to lbug-db project to prevent fork crashes

On macOS, N-API destructors crash fork workers on exit. With
isolate: true (default), vitest recycles the fork between files,
triggering the crash after each file. After several crashes, the
remaining lbug-db files never execute.

isolate: false keeps all 8 lbug-db files in a single fork — the
fork only exits once after all files complete, and that single exit
crash is caught by dangerouslyIgnoreUnhandledErrors.

* fix: add unique sequence.groupOrder to vitest projects

Vitest v4 requires unique groupOrder when projects have different
maxWorkers (lbug-db has fileParallelism: false → maxWorkers: 1).

* fix: await async close() in global-setup and remove isolate: false

global-setup.ts called conn.close() and db.close() without await —
these return Promise<void> in @ladybugdb/core 0.15.2.  The setup
function returned before the DB was fully closed, so vitest forks
hit a stale file lock when opening the same DB path, crashing the
lbug-db worker before any test ran.

isolate: false caused native state corruption after 2-3 open/close
cycles in the same fork (vitest-specific, not reproducible in plain
Node.js).  Without it, each file gets its own module scope and the
N-API destructor crash at fork exit is caught by
dangerouslyIgnoreUnhandledErrors.

Also fixes fire-and-forget close() calls in the pool adapter —
try/catch around an async close() never catches rejections; changed
to .catch(() => {}) for proper unhandled-rejection prevention.

Before: 0/8 lbug-db files ran on macOS CI (fork crash).
After:  8/8 pass, 84 files, 3077 tests, zero errors.

* fix: update project index references in AGENTS.md and CLAUDE.md to reflect correct symbol counts and relationships

* feat: enhance lbug adapter with external database support and write operation validation

* feat: create ci-tests workflow for comprehensive test coverage across platforms

* ci: move PR report inline to ci.yml, delete ci-report.yml

The old ci-report.yml used workflow_run which always runs code from
the default branch (main). This meant the PR comment used main's
stale report template that still referenced the old unit/integration
split architecture — causing "Merge coverage reports" failures.

Moving the report inline to ci.yml means it runs from the PR branch
and uses the current report template. The report now shows:
- per-platform status (Ubuntu/Windows/macOS columns)
- unified test counts from the single vitest run
- coverage with base branch (main) delta comparison
- commit SHA for traceability

Also removes the save-pr-meta job since the report no longer needs
a separate workflow_run trigger.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergo Magyar <gergomagyar@icloud.com>
2026-03-19 08:25:43 +00:00

137 lines
5.7 KiB
TypeScript

/**
* P0 Integration Tests: Core LadybugDB Adapter
*
* Tests: loadGraphToLbug CSV round-trip, createFTSIndex, getLbugStats.
*
* IMPORTANT: All core adapter tests share ONE coreHandle and ONE coreInitLbug
* call because the core adapter is a module-level singleton. Calling
* coreInitLbug with a different path closes the previous native DB handle
* and opens a new one — sharing a single handle avoids unnecessary churn.
*/
import { describe, it, expect } from 'vitest';
import fs from 'fs/promises';
import path from 'path';
import { withTestLbugDB } from '../helpers/test-indexed-db.js';
// ─── Core LadybugDB Adapter ─────────────────────────────────────────────
withTestLbugDB('core-adapter', (handle) => {
describe('core adapter', () => {
it('loadGraphToLbug: loads a minimal graph and node counts match', async () => {
const { executeQuery: coreExecuteQuery } = await import('../../src/core/lbug/lbug-adapter.js');
// createMinimalTestGraph has 2 File, 2 Function, 1 Class, 1 Folder = 6 nodes
const fileRows = await coreExecuteQuery('MATCH (n:File) RETURN n.id AS id');
expect(fileRows).toHaveLength(2);
const funcRows = await coreExecuteQuery('MATCH (n:Function) RETURN n.id AS id');
expect(funcRows).toHaveLength(2);
const classRows = await coreExecuteQuery('MATCH (n:Class) RETURN n.id AS id');
expect(classRows).toHaveLength(1);
const folderRows = await coreExecuteQuery('MATCH (n:Folder) RETURN n.id AS id');
expect(folderRows).toHaveLength(1);
});
it('createFTSIndex: creates FTS index on Function table without error', async () => {
const { createFTSIndex } = await import('../../src/core/lbug/lbug-adapter.js');
await expect(
createFTSIndex('Function', 'function_fts', ['name', 'content']),
).resolves.toBeUndefined();
});
it('getLbugStats: returns correct node and edge counts for seeded data', async () => {
const { getLbugStats } = await import('../../src/core/lbug/lbug-adapter.js');
const stats = await getLbugStats();
// createMinimalTestGraph: 6 nodes (2 File, 2 Function, 1 Class, 1 Folder)
expect(stats.nodes).toBe(6);
// 4 relationships (2 CALLS, 2 CONTAINS)
expect(stats.edges).toBe(4);
});
describe('unhappy path', () => {
it('throws on malformed Cypher query', async () => {
const { executeQuery } = await import('../../src/core/lbug/lbug-adapter.js');
// Deliberately broken syntax: MATCH without a pattern clause
await expect(executeQuery('MATCH RETURN 1')).rejects.toThrow();
});
it('returns empty results for query matching no nodes', async () => {
const { executeQuery } = await import('../../src/core/lbug/lbug-adapter.js');
// Valid Cypher, but the id will never exist in the seeded graph
const rows = await executeQuery(
"MATCH (n:Function) WHERE n.id = '__nonexistent_id__' RETURN n.id AS id",
);
expect(rows).toHaveLength(0);
});
it('handles query with non-existent table/node label', async () => {
const { executeQuery } = await import('../../src/core/lbug/lbug-adapter.js');
// LadybugDB throws when the node table does not exist in the schema
await expect(
executeQuery('MATCH (n:GhostTable) RETURN n'),
).rejects.toThrow();
});
});
describe('error handling', () => {
it('createFTSIndex handles already-existing index gracefully', async () => {
const { createFTSIndex } = await import('../../src/core/lbug/lbug-adapter.js');
// First call creates the index (may already exist from earlier test)
await createFTSIndex('Function', 'function_fts_dup', ['name', 'content']);
// Second call with same params should NOT throw — createFTSIndex catches "already exists"
await expect(
createFTSIndex('Function', 'function_fts_dup', ['name', 'content']),
).resolves.toBeUndefined();
});
it('getLbugStats returns valid counts', async () => {
const { getLbugStats } = await import('../../src/core/lbug/lbug-adapter.js');
// getLbugStats NEVER throws — it has silent catch blocks per table
const stats = await getLbugStats();
expect(typeof stats.nodes).toBe('number');
expect(typeof stats.edges).toBe('number');
expect(stats.nodes).toBeGreaterThanOrEqual(0);
expect(stats.edges).toBeGreaterThanOrEqual(0);
});
it('executeQuery with empty string rejects', async () => {
const { executeQuery } = await import('../../src/core/lbug/lbug-adapter.js');
// LadybugDB throws on empty query string
await expect(executeQuery('')).rejects.toThrow();
});
it('deleteNodesForFile with non-existent path returns zero deleted', async () => {
const { deleteNodesForFile } = await import('../../src/core/lbug/lbug-adapter.js');
// deleteNodesForFile has per-query try/catch, returns {deletedNodes: 0} for missing paths
const result = await deleteNodesForFile('/absolutely/nonexistent/path/file.ts');
expect(result).toEqual({ deletedNodes: 0 });
});
});
});
}, {
afterSetup: async (handle) => {
// Load a minimal graph via CSV round-trip (core adapter is already initialized by wrapper)
const { loadGraphToLbug } = await import('../../src/core/lbug/lbug-adapter.js');
const { createMinimalTestGraph } = await import('../helpers/test-graph.js');
const graph = createMinimalTestGraph();
const storagePath = path.join(handle.tmpHandle.dbPath, 'storage');
await fs.mkdir(storagePath, { recursive: true });
await loadGraphToLbug(graph, '/test/repo', storagePath);
},
});