GitNexus/gitnexus/test/integration/incremental-method-integrity.test.ts
Gergő Magyar cae60c2bd4
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
fix(mcp): reject corrupt query identities and refresh index metadata (#3571)
* fix(mcp): reject corrupt query identities and refresh index metadata

* fix(mcp): preserve reader and search integrity

Keep replaced readers unknown until matching metadata is published.
Defer shared-handle refresh until other consumers release the old graph
to avoid rebuilding connections against the same stale generation.

Propagate identity corruption after both hybrid search lanes settle,
so the sibling cannot query after its database session is released.
Select the regressions for the OS matrix and retain Python coverage
without optional Swift grammars.

Validation: 393 focused tests, nine native generation tests and ten
race executions across five fresh processes pass. Build and source/test
typechecks pass. The early full run passed 26,096 tests and failed eight:
seven reproduce on baseline; the mixed-source publication case passes
in clean reruns. Windows/macOS native execution remains for CI.

Graph analysis maps all edited production symbols; coverage remains
partial for the anonymous FTS test callback, manually reviewed.

Refs #3571

* fix(lbug): bump @ladybugdb/core to 0.21.2 to stop doubled rows after delete and re-copy

LadybugDB 0.21.0 and 0.21.1 return every row of a table that spans more
than one native vector twice once the incremental writeback has DETACH
DELETEd it and a COPY into an earlier table has run. NodeGroup::scan let a
morsel that ended before the group's first live row wrap an unsigned
subtraction and rescan to the end of the group (LadybugDB #1085, fixed in
0.21.2). No primary key error fires. The identity guard from #3442 stops
the run with "unexpected or duplicate ID", so a Swift edit that pulls every
importer into the write set failed on repos with more than 2048 structs.
Only unreleased main was affected: 1.6.12 ships 0.18.3.

Pin 0.21.2 in package.json, update the six @ladybugdb/core entries in the
lockfile, and move coreVersion in the vendored FTS manifest. The FTS
extension stays at 0.21.0 because no v0.21.1 or v0.21.2 artifact is
published; the pairing assertion and its unit tests pass.

Add a regression to the delete-nodes-for-files suite: 2049 structs with
CONTAINS edges are loaded, every file is deleted, the graph is loaded
again, and each id and edge must appear exactly once.

Verification (Linux, Node 22.18):
- lbug-delete-nodes-for-files: 11/11 on 0.21.2. With the 0.21.1 native
  packages swapped in, the new test fails with 4098 rows instead of 2049.
- Reporter recipe end to end on the built CLI: incremental analyze exits 0
  with no duplicate ids on a Swift-heavy fixture and on a 70-file Python
  fixture, with and without FTS. On 0.21.1 the Swift fixture exits 1.
- A 0.21.1-written database opens and reads under 0.21.2.
- prettier, eslint and typecheck:tests are clean on the changed files.
- The full lbug-db project had not finished when this was committed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(fts): say what the Windows warm-session branch covers

On Windows the repair step calls poolClose, which removes the pool entry
before the in-place writer opens. The step therefore checks the backend's
cached capability state, not a live pool connection. The comment now says so
instead of implying the pool stays warm. No behavior change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* revert: take the @ladybugdb/core 0.21.2 bump out of this PR

Reverts 0cdc3dfe3. The bump fixes LadybugDB 0.21.0 and 0.21.1 returning every
row of a large table twice after a delete and re-copy, but on Windows it
crashes the vendored FTS extension, which is still the v0.21.0 build: four of
eight Windows shards failed with exit code 3221225477 (0xC0000005) in tests
that load libfts and build an FTS index. All eight passed on 9d79092ab with
core 0.21.1. A Windows extension is only published for v0.21.0, not for
v0.21.1 or v0.21.2.

The bump moves to its own draft PR (#3578) until a matching Windows
extension exists. This PR returns to its original query-integrity and
index-freshness scope.

Restores gitnexus/package.json, the six @ladybugdb/core entries in
package-lock.json, the coreVersion in vendor/lbug-fts/manifest.json, and
removes the regression test that belongs with the bump. All four files are
identical to origin/main (1b4e3f0a8) after this commit.

Verification:
- git diff origin/main for the four files is empty.
- fts-artifact-coverage and vendored-extension-path unit tests pass (31),
  and assert-publish-fts-coverage reports core 0.21.1 paired with extension
  0.21.0.
- The graph check on the staged revert was partial, because it only deletes
  test code. The forward change was gated clean: 4 files, 6 symbols, all in
  that test, no affected processes.
- Windows CI has not run on this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:06:26 +01:00

192 lines
8.2 KiB
TypeScript

/**
* Public-workflow regression for #3564/#3527. The reporters' private fixtures
* and macOS environments are unavailable; passing this fixture does not
* establish the cause of either report.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { SupportedLanguages } from '../../src/config/supported-languages.js';
import * as adapter from '../../src/core/lbug/lbug-adapter.js';
import { runFullAnalysis } from '../../src/core/run-analyze.js';
import { isLanguageAvailable } from '../../src/core/tree-sitter/parser-loader.js';
import { LocalBackend } from '../../src/mcp/local/local-backend.js';
import { getStoragePaths } from '../../src/storage/repo-manager.js';
import { commitAll, initGitRepo } from '../helpers/temp-git-repo.js';
import { createTempDir } from '../helpers/test-db.js';
type SymbolTuple = {
uid: string;
name: string;
filePath: string;
startLine: number;
endLine: number;
content: string;
};
const FILE_COUNT = 70;
const METHODS_PER_FILE = 64;
const CHANGED_FILE = 'checks/test_batch_0.py';
const SWIFT_PATH = 'Sources/Sentinel.swift';
const SWIFT_SOURCE = 'struct UnrelatedSwiftSentinel {\n let marker: Int = 701\n}\n';
const swiftAvailable = isLanguageAvailable(SupportedLanguages.Swift);
const METHOD_SCAN = `MATCH (n:Method)
RETURN n.id AS uid, n.name AS name, n.filePath AS filePath,
n.startLine AS startLine, n.endLine AS endLine, n.content AS content
ORDER BY uid`;
// The expected rows come from the source fixture, never from graph output or a
// previous database scan. Native spans are zero-based; context displays +1.
function pythonFixture(batch: number, changed = false): { source: string; tuples: SymbolTuple[] } {
const filePath = `checks/test_batch_${batch}.py`;
const className = `Batch${batch}`;
const lines = ['import unittest', '', `class ${className}(unittest.TestCase):`];
const tuples: SymbolTuple[] = [];
for (let method = 0; method < METHODS_PER_FILE; method++) {
const name = `test_sample_${batch}_${method}`;
const body = [` def ${name}(self):`, ` return ${batch * METHODS_PER_FILE + method}`];
if (changed && method === 0) {
body.splice(1, 0, ' updated_value = 9001');
body[2] = ' return updated_value';
}
const startLine = lines.length;
tuples.push({
uid: `Method:${filePath}:${className}.${name}#0`,
name,
filePath,
startLine,
endLine: startLine + body.length - 1,
// Stored symbol content preserves indentation and flattens newlines for FTS.
content: body.join(' '),
});
lines.push(...body, '');
}
return { source: lines.join('\n'), tuples };
}
function expectContext(result: any, expected: SymbolTuple): void {
expect(result).not.toHaveProperty('error');
expect(result.status).toBe('found');
expect(result.symbol).toMatchObject({
...expected,
startLine: expected.startLine + 1,
endLine: expected.endLine + 1,
});
}
describe('Python Method identities across selective incremental writes with an optional Swift control (#3564, #3527)', () => {
it('retains every source tuple across a class-method edit and fresh native/MCP readers', async () => {
const temp = await createTempDir();
let backend: LocalBackend | undefined;
try {
const root = await fs.realpath(temp.dbPath);
const repo = path.join(root, 'method-integrity');
await fs.mkdir(path.join(repo, 'checks'), { recursive: true });
await fs.mkdir(path.join(repo, 'Sources'));
await fs.mkdir(path.join(root, 'user-home'));
vi.stubEnv('HOME', path.join(root, 'user-home'));
vi.stubEnv('USERPROFILE', path.join(root, 'user-home'));
vi.stubEnv('GITNEXUS_HOME', path.join(root, 'home'));
vi.stubEnv('GITNEXUS_STORAGE_PATH', undefined);
vi.stubEnv('GITNEXUS_STORAGE_ROOT', undefined);
vi.stubEnv('GITNEXUS_SHARED_STORE', 'off');
vi.stubEnv('GITNEXUS_CONTENT_RETENTION', 'full');
vi.stubEnv('GITNEXUS_LBUG_EXTENSION_INSTALL', 'load-only');
vi.stubEnv('GITNEXUS_WAL_MANUAL_CHECKPOINT', '1');
await fs.writeFile(path.join(repo, '.gitignore'), '.gitnexus/\n');
if (swiftAvailable) await fs.writeFile(path.join(repo, SWIFT_PATH), SWIFT_SOURCE);
const fixtures = Array.from({ length: FILE_COUNT }, (_, batch) => pythonFixture(batch));
for (const fixture of fixtures) {
await fs.writeFile(path.join(repo, fixture.tuples[0].filePath), fixture.source);
}
initGitRepo(repo);
execFileSync('git', ['config', 'commit.gpgsign', 'false'], { cwd: repo });
commitAll(repo, 'baseline Python methods and unrelated Swift struct');
// This test isolates selective native writes from extension availability.
// FTS corruption and query guards have separate real-native coverage.
const options = { skipAgentsMd: true, skipSkills: true, skipFts: true };
await runFullAnalysis(repo, options, { onProgress: () => {} });
const { lbugPath } = getStoragePaths(repo);
backend = new LocalBackend();
expect(await backend.init()).toBe(true);
const readAll = async (expected: SymbolTuple[]): Promise<void> => {
const ordered = [...expected].sort((a, b) => (a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0));
// The entire Method table exceeds one 2048-row native vector. Reopen
// the database for each scan rather than reusing the writer's view.
await adapter.initLbug(lbugPath, { skipFts: true });
try {
expect(await adapter.executeQuery(METHOD_SCAN)).toEqual(ordered);
if (swiftAvailable)
expect(
await adapter.executeQuery(
`MATCH (n:Struct) RETURN n.id AS uid, n.name AS name, n.filePath AS filePath,
n.startLine AS startLine, n.endLine AS endLine, n.content AS content`,
),
).toEqual([
{
uid: `Struct:${SWIFT_PATH}:UnrelatedSwiftSentinel`,
name: 'UnrelatedSwiftSentinel',
filePath: SWIFT_PATH,
startLine: 0,
endLine: 2,
content: SWIFT_SOURCE.trimEnd().replace(/\n/g, ' '),
},
]);
} finally {
await adapter.closeLbug();
}
// Keep the same backend across both analyses, but release its native
// reader before the in-place writer opens the DB. No mocked rows.
const result = await backend!.callTool('cypher', { repo, statement: METHOD_SCAN });
expect(result).not.toHaveProperty('error');
expect(result.row_count).toBe(FILE_COUNT * METHODS_PER_FILE);
expect(result.markdown).toBe(
[
'| uid | name | filePath | startLine | endLine | content |',
'| --- | --- | --- | --- | --- | --- |',
...ordered.map(
(tuple) =>
`| ${Object.values(tuple)
.map((value) => String(value).replace(/\n/g, ' '))
.join(' | ')} |`,
),
].join('\n'),
);
for (const index of [0, 63, 2048, expected.length - 1]) {
expectContext(
await backend!.callTool('context', {
repo,
uid: expected[index].uid,
include_content: true,
}),
expected[index],
);
}
await backend!.dispose();
};
const before = fixtures.flatMap(({ tuples }) => tuples);
expect(before).toHaveLength(4480);
await readAll(before);
const edited = pythonFixture(0, true);
await fs.writeFile(path.join(repo, CHANGED_FILE), edited.source);
commitAll(repo, 'edit one class method and shift later method spans');
const refreshed = await runFullAnalysis(repo, options, { onProgress: () => {} });
expect(refreshed.incrementalStats).toMatchObject({
changedFiles: 1,
deletedFiles: 0,
writeMode: 'incremental',
});
await readAll([...edited.tuples, ...fixtures.slice(1).flatMap(({ tuples }) => tuples)]);
} finally {
await backend?.dispose();
await adapter.closeLbug();
vi.unstubAllEnvs();
await temp.cleanup();
}
}, 180_000);
});