GitNexus/gitnexus/test/unit/ensure-initialized-reinit-watermark.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

148 lines
6.6 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
// tri-review NEW-7: `lastObservedIndexedAt`/`lastObservedFtsStatus` used to be
// advanced BEFORE `initLbug` was awaited, unlike `lastObservedDbIdentity`
// (which is only advanced once `initLbug` confirms the pool rolled over). If
// `initLbug` threw, the watermark had already been latched to the new value —
// permanently hiding a failed reinit from every later staleness check, since
// a subsequent comparison against that same watermark would see no change.
// This isolates the fix: a poolKey with `identityChanged` always false (a
// nonexistent lbugPath — no backstop from the file-identity signal) must
// still retry after a transient `initLbug` failure.
const initLbugMock = vi.fn();
vi.mock('../../src/core/lbug/pool-adapter.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/core/lbug/pool-adapter.js')>();
return {
...actual,
initLbug: (...args: any[]) => initLbugMock(...args),
isLbugReady: vi.fn().mockReturnValue(true),
};
});
const loadMetaMock = vi.fn();
vi.mock('../../src/storage/repo-manager.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/storage/repo-manager.js')>();
return {
...actual,
loadMeta: (...args: any[]) => loadMetaMock(...args),
};
});
import { LocalBackend } from '../../src/mcp/local/local-backend.js';
describe('ensureInitialized reinit watermark (tri-review NEW-7)', () => {
const poolKey = '/tmp/nonexistent-repo/.gitnexus/lbug';
const repoHandle = { id: 'r1', name: 'r1', lbugPath: poolKey, indexedAt: 'v0' } as any;
let backend: any;
beforeEach(() => {
vi.clearAllMocks();
backend = new LocalBackend() as any;
// Seed the "warm, already initialized" precondition ensureInitialized
// requires to reach the staleness-check branch at all.
backend.initializedRepos.add(poolKey);
});
it('keeps checkout branches separate for concurrent callers of one branch-neutral pool', async () => {
loadMetaMock.mockResolvedValue({ indexedAt: 'shared-v1', lastCommit: 'shared-commit' });
initLbugMock.mockResolvedValue(true);
const left = { ...repoHandle, branch: 'left', lastCommit: 'shared-commit' };
const right = { ...repoHandle, branch: 'right', lastCommit: 'shared-commit' };
await Promise.all([backend.ensureInitialized(left), backend.ensureInitialized(right)]);
expect(left.branch).toBe('left');
expect(right.branch).toBe('right');
expect(left.indexedAt).toBe('shared-v1');
expect(right.indexedAt).toBe('shared-v1');
});
it('does not latch the fts-status watermark when initLbug throws, so the next staleness check retries', async () => {
loadMetaMock.mockResolvedValue({
indexedAt: 'v1',
capabilities: { fts: { status: 'available' } },
});
initLbugMock.mockRejectedValueOnce(new Error('lock timeout'));
await expect(backend.ensureInitialized(repoHandle)).rejects.toThrow('lock timeout');
// The failed reinit must NOT have advanced either watermark — a nonexistent
// lbugPath means dbIdentity never changes, so there is no other signal to
// fall back on for a retry.
expect(backend.lastObservedPoolState.get(poolKey)?.ftsStatus).toBeUndefined();
expect(backend.lastObservedPoolState.get(poolKey)?.indexedAt).toBeUndefined();
// Second staleness check with initLbug now succeeding.
initLbugMock.mockResolvedValueOnce(false); // "no real reopen needed" — still a completed call
await expect(backend.ensureInitialized(repoHandle)).resolves.toBeUndefined();
// The retry succeeded and the watermark is now current — proving the
// failed first attempt did not permanently suppress detection.
expect(backend.lastObservedPoolState.get(poolKey)?.ftsStatus).toBe('available');
expect(backend.lastObservedPoolState.get(poolKey)?.indexedAt).toBe('v1');
expect(initLbugMock).toHaveBeenCalledTimes(2);
});
});
describe('ensureInitialized ftsCapsChanged trigger, isolated from identityChanged (tri-review Residual-4)', () => {
// The only existing coverage for this reinit trigger is the integration
// test in fts-repair-warm-session.test.ts, where a REAL --repair-fts run
// also mutates the lbug file — so identityChanged is confounded with
// ftsCapsChanged there, and it's impossible to tell from that test alone
// whether ftsCapsChanged is actually load-bearing. This isolates it: a
// nonexistent lbugPath means statDbIdentity always resolves null, so
// identityChanged is provably false on every check — the ONLY way a reinit
// can fire here is via ftsCapsChanged (indexedAt is held constant too, so
// stampChanged is also false).
const poolKey = '/tmp/nonexistent-repo-caps-only/.gitnexus/lbug';
const repoHandle = { id: 'r2', name: 'r2', lbugPath: poolKey, indexedAt: 'same' } as any;
let backend: any;
beforeEach(() => {
vi.clearAllMocks();
backend = new LocalBackend() as any;
backend.initializedRepos.add(poolKey);
});
it('fires a reinit on a capabilities.fts.status change alone, with indexedAt and dbIdentity both unchanged', async () => {
// Seed a baseline observed state: same indexedAt the next loadMeta will
// report, a DIFFERENT ftsStatus, and dbIdentity null (matches what
// statDbIdentity will keep returning for this nonexistent path).
backend.lastObservedPoolState.set(poolKey, {
indexedAt: 'same',
ftsStatus: 'unavailable',
dbIdentity: null,
});
loadMetaMock.mockResolvedValue({
indexedAt: 'same', // unchanged — stampChanged must be false
capabilities: { fts: { status: 'available' } }, // changed — the only live signal
});
initLbugMock.mockResolvedValueOnce(true);
await backend.ensureInitialized(repoHandle);
// A reinit only happens inside the `if (stampChanged || identityChanged
// || ftsCapsChanged)` branch — initLbug being called at all here proves
// ftsCapsChanged fired, since the other two provably could not have.
expect(initLbugMock).toHaveBeenCalledTimes(1);
expect(backend.lastObservedPoolState.get(poolKey)?.ftsStatus).toBe('available');
});
it('does NOT fire a reinit when nothing observable changed (negative control)', async () => {
backend.lastObservedPoolState.set(poolKey, {
indexedAt: 'same',
ftsStatus: 'available',
dbIdentity: null,
});
loadMetaMock.mockResolvedValue({
indexedAt: 'same',
capabilities: { fts: { status: 'available' } }, // same as observed
});
await backend.ensureInitialized(repoHandle);
expect(initLbugMock).not.toHaveBeenCalled();
});
});