GitNexus/gitnexus/test/unit/compaction-policy.test.ts
Gergő Magyar 612136cadc
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
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
fix: compact incremental graphs adaptively (#3854)
* fix: rebuild changed graphs in fresh databases

Populated-table writes inflate LadybugDB storage (#3852). Bulk-load
fresh graphs while retaining parse caches, no-ops and logical counts.

Read prior graphs without writes so staging failures preserve their
bytes. Restore compatible vectors and rebuild derived layers and FTS
under the existing checkpoint and publication guards.

Keep the write policy, preservation guards and regressions together
so the replacement has one coherent publication contract.

Closes #3852

* perf: skip FTS builds for empty tables

* fix: align CI with compact graph writes

Validate populated-table FTS coverage and cached full writes while keeping the performance budget unchanged. Compare database bytes without enumerating Buffer keys, and retain native checkpoint failure details.

* perf: use bounded hybrid graph writes

Keep small edits selective and scale the mutation budget with graph size.
Compact accumulated native storage growth without copying every graph on
every edit. Preserve physical receipts across shared-store publication and
native resource limits during recovery.

Align CI assertions with selective writes and populated FTS tables.
Refs #3852

* fix: close hybrid compaction gaps

Count removed rows before selective writes and preserve the shared
graph's compaction receipt when publishing completed vectors.

* test: serialize compaction native suites

* test: declare capped count determinism

* test: mock persisted rows in FTS fixtures

* fix: address hybrid write review (#3854)

Retain unreadable graph bytes before recovery and stop destructive writes
when the real embedding cache probe fails.

Keep small deletions and renames selective, preserve healthy private
graphs through edit/revert cycles, and bound FTS presence probes.

Cover durability, footprint boundaries and vector restoration. Align
mock graph fixtures and fix the pre-existing WAL test's UUID false
positive found by full-suite validation; its nine-test suite now passes.

* test: clarify selective restore fixture (#3854)

* test: isolate recovery CI fixtures (#3854)

Cap embedding generation in the missing-graph recovery fixture so it does
not require optional model packages. Allow cold PowerShell startup in the
OS identity smoke test; retain the five-second production probe limit.

* test: finish review cleanup (#3854)

* test: strengthen graph integrity checks

Hash persisted node and edge properties; clean failed fixtures and gate FTS setup through the test lifecycle.

Refs #3854

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-09 20:57:07 +00:00

151 lines
5.2 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
import {
graphCompactionReason,
incrementalMutationLimit,
incrementalMutationRows,
isGraphCompactionState,
MAX_INCREMENTAL_MUTATION_ROWS,
MAX_INCREMENTAL_WRITES,
} from '../../src/core/incremental/compaction-policy.js';
const mib = 1024 * 1024;
const baseline = { version: 1, compactBytes: 200 * mib, incrementalWrites: 0 };
describe('hybrid compaction policy', () => {
it('scales the mutation budget with graph size for large monorepos', () => {
const graph = createKnowledgeGraph();
expect(incrementalMutationLimit(graph)).toBe(2_000);
for (let i = 0; i < 50_000; i++) {
graph.addNode({
id: `f${i}`,
label: 'Function',
properties: { name: `f${i}`, filePath: i < 2_100 ? 'changed.ts' : 'other.ts' },
});
}
const limit = incrementalMutationLimit(graph);
expect(limit).toBe(2_500);
expect(incrementalMutationRows(graph, new Set(['changed.ts']))).toBe(2_100);
expect(incrementalMutationRows(graph, new Set(['changed.ts']))).toBeLessThan(limit);
expect(incrementalMutationRows(graph, new Set(['other.ts']))).toBe(limit);
for (let i = 1; i <= 10_000; i++) {
graph.addRelationship({
id: `edge${i}`,
sourceId: 'f0',
targetId: `f${i}`,
type: 'CALLS',
confidence: 1,
reason: '',
step: 0,
});
}
expect(graph.relationshipCount).toBe(10_000);
expect(incrementalMutationLimit(graph)).toBe(3_000);
expect(incrementalMutationRows(graph, new Set(['changed.ts']))).toBe(3_000);
});
it('keeps small edits incremental until the growth or update budget is exhausted', () => {
expect(graphCompactionReason(baseline, 250 * mib)).toBeUndefined();
expect(graphCompactionReason(baseline, 300 * mib)).toBeUndefined();
expect(graphCompactionReason(baseline, 300 * mib + 1)).toContain('physical storage grew');
expect(
graphCompactionReason(
{ ...baseline, incrementalWrites: MAX_INCREMENTAL_WRITES - 1 },
baseline.compactBytes,
),
).toBeUndefined();
expect(
graphCompactionReason(
{ ...baseline, incrementalWrites: MAX_INCREMENTAL_WRITES },
baseline.compactBytes,
),
).toContain('incremental writes');
});
it('allows fixed native allocation overhead on small repositories, but still bounds growth', () => {
const small = { ...baseline, compactBytes: 8 * mib };
expect(graphCompactionReason(small, 24 * mib)).toBeUndefined();
expect(graphCompactionReason(small, 24 * mib + 1)).toContain('physical storage grew');
expect(
graphCompactionReason({ ...small, incrementalWrites: MAX_INCREMENTAL_WRITES }, 8 * mib),
).toContain('incremental writes');
});
it.each([
undefined,
null,
{},
{ ...baseline, version: 2 },
{ ...baseline, compactBytes: 0 },
{ ...baseline, compactBytes: NaN },
{ ...baseline, compactBytes: Number.MAX_SAFE_INTEGER + 1 },
{ ...baseline, incrementalWrites: -1 },
{ ...baseline, incrementalWrites: 0.5 },
{ ...baseline, incrementalWrites: '0' },
])('requires a fresh baseline for malformed receipts (%j)', (state) => {
expect(isGraphCompactionState(state)).toBe(false);
expect(graphCompactionReason(state, 200 * mib)).toContain('baseline');
});
it.each([undefined, 0, -1, NaN, Infinity, 1.5])(
'cannot infer safety from an unmeasurable size (%s)',
(bytes) => {
expect(graphCompactionReason(baseline, bytes)).toContain('could not be measured');
},
);
it('counts endpoint mutations across file boundaries without counting unrelated rows', () => {
const graph = createKnowledgeGraph();
for (const [id, filePath] of [
['a', 'changed.ts'],
['b', 'other.ts'],
['c', 'unrelated.ts'],
]) {
graph.addNode({ id, label: 'Function', properties: { name: id, filePath } });
}
graph.addRelationship({
id: 'ab',
sourceId: 'a',
targetId: 'b',
type: 'CALLS',
confidence: 1,
reason: '',
step: 0,
});
graph.addRelationship({
id: 'ba',
sourceId: 'b',
targetId: 'a',
type: 'CALLS',
confidence: 1,
reason: '',
step: 0,
});
graph.addRelationship({
id: 'bc',
sourceId: 'b',
targetId: 'c',
type: 'CALLS',
confidence: 1,
reason: '',
step: 0,
});
expect(incrementalMutationRows(graph, new Set(['changed.ts']))).toBe(3);
expect(incrementalMutationRows(graph, new Set(['changed.ts']), 0)).toBe(0);
expect(incrementalMutationRows(graph, new Set(['changed.ts', 'other.ts']))).toBe(5);
expect(incrementalMutationRows(graph, new Set(['missing.ts']))).toBe(0);
});
it('caps the estimate for one large source file rather than counting only its file fraction', () => {
const graph = createKnowledgeGraph();
for (let i = 0; i < MAX_INCREMENTAL_MUTATION_ROWS + 100; i++) {
graph.addNode({
id: `f${i}`,
label: 'Function',
properties: { name: `f${i}`, filePath: 'large.ts' },
});
}
expect(incrementalMutationRows(graph, new Set(['large.ts']))).toBe(
MAX_INCREMENTAL_MUTATION_ROWS,
);
});
});