GitNexus/gitnexus/test/integration/relationship-integrity-source-race.test.ts
Gergő Magyar 3f2f3ce18e
fix(graph): validate reference sites and dedupe context (#3845)
* fix(context): dedupe references before limits

Select distinct relationship types and symbols in all seven graph
queries before applying their existing 30-row limits. Repeated call
sites must not hide other callers.

Refs #3500

* fix(graph): validate reference provenance

Check source identities and spans before either writer drops provenance.
Retain full spans so nested calls sharing a start stay distinct. Reject
invalid records without publishing a clean receipt; preserve the prior
published index on failure.

Expose repository-wide ingestion receipts to MCP callers. Legacy,
collapsed, point-only and extracted-buffer provenance stays unverified.
Identical identities keep the existing first-writer-wins evidence policy.

Refs #3500

* fix(graph): leave notebook spans unverified

Notebook captures map JSON rows but retain extracted-code columns. Keep these identities explicitly unverified instead of certifying a span that no single source buffer can validate.

Refs #3500

* feat(graph): log ingestion integrity checks

Record summary counts, bounded debug examples, and actionable rejection diagnostics before provenance is discarded. Document the debug command and verify both graph writers retain the logging contract.

Refs #3500

* refactor(graph): simplify reference validation

Refs #3500

* fix(graph): harden reference integrity checks

Reject conflicting sites across streaming partitions.
Preserve DISTINCT limits with indexed label anchors.
Verify span migrations without weakening benchmark gates.

Refs #3500, #3845.

* fix(graph): validate canonical reference spans

Reject access-kind prefixes and use parser UTF-16 column units for source bounds. Cover both writers with malformed identities and native Unicode parser regressions.

Refs #3500, #3845

* test(graph): verify streamed integrity runs

Force streaming in cold and changed-source cases and assert the emitted manifest. Clarify complete-span identity and successful Cypher response docs.

Refs #3500, #3845

* fix(graph): preserve parsed-source provenance

Keep concurrent source edits unverified, bound streamed identity probes,
and distinguish transient MCP uncertainty from missing receipts.

Refs #3845, #3500

* fix(graph): avoid retaining skipped endpoint IDs

Resolve parser identity before allocating test directories.

Refs #3845, #3500

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-08 20:55:14 +00:00

139 lines
5.4 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js';
import { runtimeParseIdentity } from '../helpers/runtime-parse-identity.js';
import { distWorkerExists } from '../helpers/worker-parse.js';
import { type ParseCache, loadParseCache, saveParseCache } from '../../src/storage/parse-cache.js';
import * as integrityModule from '../../src/core/graph/relationship-integrity.js';
import { _captureLogger } from '../../src/core/logger.js';
import {
getDurableParsedFileDir,
pruneAndSaveDurableParsedFileStore,
} from '../../src/storage/parsedfile-store.js';
const describeIfWorkerBuilt = distWorkerExists() ? describe : describe.skip;
const source =
'export class Service { ping() { return 1; } }\nexport function caller(service: Service) { service.ping(); }\n';
describeIfWorkerBuilt.each([
{ streamGraphEmit: false, cached: false },
{ streamGraphEmit: true, cached: false },
{ streamGraphEmit: false, cached: true },
{ streamGraphEmit: true, cached: true },
])(
'concurrent source edits (streaming=$streamGraphEmit cached=$cached)',
({ streamGraphEmit, cached }) => {
it.each(['truncate', 'lengthen', 'rename', 'delete'] as const)(
'keeps %s unverified on cold and cached parsing',
async (change) => {
const identity = await runtimeParseIdentity();
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-integrity-race-'));
const file = path.join(root, 'sample.ts');
const storage = path.join(root, '.gitnexus');
let cache: ParseCache = {
identity,
entries: new Map(),
usedKeys: new Set(),
storagePath: storage,
writeStoragePath: storage,
onDiskKeys: new Set(),
};
try {
fs.writeFileSync(file, source);
const options = {
skipGraphPhases: true,
workerPoolSize: 1,
parseCache: cache,
streamGraphEmit,
graphEmitCsvDir: path.join(root, 'csv'),
};
if (cached) {
await runPipelineFromRepo(root, () => {}, options);
const keys = await saveParseCache(storage, cache);
await pruneAndSaveDurableParsedFileStore(
getDurableParsedFileDir(storage),
cache.identity.base,
new Set(keys),
);
cache = await loadParseCache(storage, cache.identity, storage);
options.parseCache = cache;
}
let mutated = false;
const result = await runPipelineFromRepo(
root,
(progress) => {
if (progress.phase !== 'scopeResolution' || mutated) return;
mutated = true;
const mutations = {
truncate: () => fs.writeFileSync(file, ''),
lengthen: () => fs.appendFileSync(file, '// edit after parsing\n'),
rename: () => fs.renameSync(file, `${file}.old`),
delete: () => fs.unlinkSync(file),
};
mutations[change]();
},
options,
);
expect(mutated).toBe(true);
expect(result.parseCacheHitFileCount).toBe(cached ? 1 : 0);
expect(result.relationshipIntegrity?.checkedSites).toBe(0);
expect(result.relationshipIntegrity?.unverifiedEdges).toBeGreaterThan(0);
const calls = streamGraphEmit
? fs
.readFileSync(
result.graphEmitManifest!.relsByPair.get('Function|Method')!.csvPath,
'utf8',
)
.split('\n')
.filter((line) => line.includes('CALLS'))
: [...result.graph.iterRelationships()].filter((rel) => rel.type === 'CALLS');
expect(calls).toHaveLength(1);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
},
90_000,
);
},
);
describeIfWorkerBuilt('latched integrity failures', () => {
it('aborts CFG emission without per-file warning floods', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-integrity-cfg-'));
const logs = _captureLogger('debug');
const createCollector = integrityModule.createRelationshipIntegrityCollector;
const injected = vi
.spyOn(integrityModule, 'createRelationshipIntegrityCollector')
.mockImplementation((...args) => {
const collector = createCollector(...args);
return {
...collector,
inspect: (rel, duplicate, conflict) =>
collector.inspect(rel, duplicate, conflict || rel.type === 'CFG'),
};
});
try {
fs.writeFileSync(path.join(root, 'first.ts'), source);
fs.writeFileSync(path.join(root, 'second.ts'), source);
await expect(
runPipelineFromRepo(root, () => {}, {
pdg: true,
skipGraphPhases: true,
workerPoolSize: 1,
}),
).rejects.toThrow(/identity contradicts an existing record/);
expect(
logs.records().filter((record) => record.event === 'graph_reference_rejected'),
).toHaveLength(1);
expect(
logs.records().filter((record) => String(record.msg).includes('CFG emission failed')),
).toHaveLength(0);
} finally {
injected.mockRestore();
logs.restore();
fs.rmSync(root, { recursive: true, force: true });
}
}, 90_000);
});