GitNexus/gitnexus/test/unit/analyze-api.test.ts
Gergő Magyar cc6225d2cb
feat(analyze): make indexing resource-bounded and resumable (#3829)
* docs(plans): add resumable analyze plan

* perf(bench): measure resumable storage primitives

* feat(embeddings): bound and persist work selection

* feat(embeddings): persist resumable vector jobs

Keep graph readers independent of vector writes. Acknowledge units only after complete chunk verification and a native checkpoint.

* feat(embeddings): stream resumable job units

* feat(storage): add generation publication

Publish durable graph generations independently of vector jobs and gate readers on matching identities. Retain the legacy graph inode under a private name so older binaries cannot serve a stale canonical graph. Coordinator integration follows separately.

Refs #3598

* feat(embeddings): coordinate durable jobs

Join published graph selection, durable work, bounded native handles and vector publication behind one inactive controller. Limit optional HTTP response decoding within the job reservation and admit supported large inputs under larger budgets.

Refs #3598

* feat(analyze): pass phase resource allocations

Carry per-run worker heaps and native pools without changing legacy defaults. Hold parser reservations through safe native exit; refuse database reallocation after an unverified close.

* feat(embeddings): reserve sidecar resources

Pin each durable job to an admitted model heap and CPU config. Retain native allocations after caller cancellation until response or process exit, and reject phase handoff when release is unverified.

* feat(status): separate graph and vector readiness

Report embedding debt independently from graph content freshness. Read bounded durable progress without loading native runtimes, gate stale vector capability stamps, and allowlist additive phase counters on public SSE and ops payloads.

* fix(embeddings): recover interrupted job setup

Recover an owned empty native catalog after interrupted bootstrap, and rebuild damaged failure accounting without repeating completed provider work. Preserve foreign artifacts and propagate filesystem errors.

* fix(resources): verify native pool release

Keep failed and concurrent native closes tracked until release succeeds. Refuse another reserved allocation while cleanup is unverified, including failed connection construction. Let graph readers tear down after result-close errors.

* fix(resources): drain graph before phase admission

Wait for session work and verify the prior main graph pool has closed before parser or embedding admission. Recheck cancellation after the drain so cancelled jobs do not read or mutate job metadata.

* docs(plans): revise resumable analyze seams

* perf(bench): measure paired analyze runs

* feat(index): publish logical graph generations

Retain private database files across incremental generations and fence prepared publication against superseding writers. Exit-only producers must exit before publication; interrupted in-place writes remain explicitly dirty.

* feat(index): guard graph process handoff

Wait for actual process exit and reacquire the ordinary slot lock before
publishing the prepared attempt. Recheck placement and the registered
name, and retain graph discoverability after cancellation.

Add a bounded nonterminal worker receipt without serializing the live
graph. Production phase activation remains separate.

* feat(cli): defer success across graph handoff

Finish live-graph skill generation before the child hands off. Transfer
only bounded counters, identity and the pre-run self-commit safety flags;
wait for IPC delivery before returning for native process exit.

Reject missing supervisors and mismatched prepared results before skill
writes. Finalization, self-commit and success remain deferred until the
production supervisor completes embedding; core activation follows the
pending-artifact and resource contracts.

Refs #3598

* feat(embeddings): rebase pending paid artifacts

Separate graph job identity from mutable artifact ownership. Keep paid
compatible groups across source edits using bounded revalidation and
selection pruning; retain one sealed fallback for the active space.

* feat(embeddings): preserve historical coverage

* feat(embeddings): reuse verified legacy vectors

Retain a directly referenced legacy source across pending-artifact
rebases. Stream checkpoint exclusions and build a native metadata index
without copying vectors or retaining corpus-sized JavaScript maps.

Require recorded provider identity and provable complete input groups.
Keep unknown provenance explicit, source artifacts immutable, compatible
relocations free of provider calls, and new inputs in normal batches.

The controller remains inactive until coordinated writer activation.

Refs #3598

* feat(analyze): account for supervised phases

Charge parent memory once per phase. Carry allowlisted progress through
worker IPC and preserve counters across logs without completing the job.

Refs #3598

* fix(storage): retain owned analysis generations

Keep private generation files in place through shared-store preparation
and publication. Retain prepared publications and pending embedding work
across the unlocked process handoff, including work in branch slots.

Refs #3598

* fix(embeddings): share pinned vector readers

Share immutable vector file identities so sibling hard links retain one
native reservation. Keep the handle alive until its final reader closes,
including failed initialization and replacement of another reader's path.

Refs #3598

* feat(storage): share completed vector artifacts

Pin immutable vectors independently in checkout slots and shared graph snapshots. Keep mutable jobs with their owning checkout; resume interrupted adoption without overwriting unverified files.

Refs #3598

* feat(analyze): retain caches across phase handoff

Keep prepared staging during lock reacquisition and share cache
publication between the graph writer and exit continuation. Bound the
filesystem handoff to chunk keys; never copy live cache contents.

Refs #3598

* fix(analyze): retain owned generation routing

Keep prepared and pending work under its original slot lock during shared-store adoption. Preserve private generation filenames during incremental writes without copying the graph.

Drain model and native resources only when graph work actually starts, including FTS repair. Leave the warm no-op path unchanged.

Validated 158 tests, source build, test typecheck, formatting and lint. Complete graph gates cover 29 symbols in two files and the expected coordinator flow. End-to-end embedding activation and performance acceptance remain pending.

* feat(analyze): wire resumable phase execution

Publish verified graphs before embedding and hand off resource ownership
across CLI, watch, auto-sync, and HTTP phases. Keep completed vectors
readable while durable embedding units resume in a separate generation.

Preserve legacy vector reuse, avoid graph rebuilds for dimension changes,
and cover interruption boundaries with fresh-process restart tests.

Refs #3598

* fix(analyze): close recovery and ownership gaps

Retain interrupted private work, clear stale query widths, and keep
native reservations until confirmed worker exit. Keep shared-member
admission gates outside garbage-collected directories for flat and
branch writers. Reject invalid
routes and overlaps, and distinguish validation from uncertain writes.

Make test imports work before build, isolate host-capacity assertions,
and give legacy vector fixtures the production native pool allocation.

Focused regressions, clean-build types, formatting and lint pass.
Graph analysis maps 51 symbols across 21 paths. Two import-only test
paths remain unmapped; direct review and integration tests cover them.
The parent full suite passed 32,084 tests with five failures: two fixed
legacy-vector fixture cases and three recovery cases awaiting isolation.
Final full-suite and performance acceptance remain pending on the draft.

Refs #3598

* perf(embeddings): batch reused vector writes

Avoid a native transaction per reused node while retaining the byte
budget and durable unit boundary. Cover mixed inputs, cancellation,
and replay after read or committed-write failures.

Native regression fails before the fix (65 commits for 64 nodes).
79 focused tests and all three former recovery timeouts pass.
Fresh graph gate: 18 symbols, 2 files, 36 affected flows; complete
mapping. Final whole-command performance acceptance remains pending.

Refs #3598

* fix(analyze): honor explicit worker overrides

Preserve the existing CPU oversubscription override while reserving memory for every requested worker. Automatic concurrency stays CPU-bounded.

Validate on one- and four-CPU hosts: 81 tests pass; the override regressions fail before the fix.

* fix(storage): validate opened artifact files

Validate descriptors before reading bounded receipts and manifests. Use nonblocking opens to reject FIFO substitutions and verify directory entries when O_NOFOLLOW is unavailable. Preserve the metadata cache fast path and guard generation paths explicitly.

Remove the redundant pending-node fallback. Add race, symlink, cleanup, and cache regressions to platform coverage.

* fix(storage): guard the graph path directly

Apply the containment check to the same path passed to lstat. The nested normalization guarded a different expression in CodeQL. path.relative already resolves its inputs, so remove the redundant normalization and retain relative-path behavior.

* fix(embeddings): preserve AST inputs on resume

Carry indexed source policy into bounded resumable jobs and preserve exact-input reuse across sibling edits. Include strategy and retention in job identity; admit source memory before reading.

* chore: run checks for the rebased stack

* refactor(embeddings): simplify reuse plumbing

Name reuse-validation options and share the owned-directory loop.
Preserve callback order, directory sync, and ownership checks.

* test: fix recovery and Windows CI fixtures

Distinguish legacy checkpoints without input provenance from verified source-aware chunks. Check the embed API at its shared-phase boundary and model pathname races without rename-over-open on Windows.

* fix: close resource admission and CI gaps

Keep live sidecars charged after a reap timeout. Let sync and HTTP jobs use automatic host budgets instead of overcommitting to default V8 limits. Explain the incompatible native zero-pool override, clean up failed HTTP fixtures, and run the native vector suites across platforms.

* fix: preserve analysis resource ownership

Pin admitted model settings and retain worker and supervisor reservations.
Recheck canonical directory identity before receipt reads or writes.
Canonicalize the native publication fixture for macOS and Windows.

* test: distinguish parameterized CI cases

* docs: remove implementation plan from PR

* ci: gate resumable analyze performance

* fix(analyze): close recovery and CI gaps

Retain ownership receipts and paid vectors through interrupted work
and cleanup. Restore automatic heap and parser-worker sizing, and
cover publication, cancellation and capacity failures.

Refs #3829, #3598

Note: pre-existing setup.test.ts and setup-skills.test.ts failures
with inherited CODEX_HOME; all 62 tests pass with it unset for the
test process.

* fix(embeddings): normalize graph parent paths

Bind the canonical job root to the same graph path on macOS temp aliases
and Windows short paths. Keep graph identity and owned-directory checks.
Canonicalize the retention fixture and show subprocess stderr on failure.

Validation: 65 focused tests; 26 tests through an aliased TMPDIR; build,
test typecheck, formatting and lint; graph change analysis (4 files).

* fix(embeddings): batch writes and guard recovery

Batch bounded vector and receipt writes to remove per-node native calls
without changing validation, transactions, or durable checkpoints.

Pin publication descriptors before entry validation. Preserve excluded
vector coverage, reject malformed status paths, retry orphan sidecars,
and complete shutdown after child spawn failures.

Validation: 159 focused tests and 89 native/restart tests; build, test
 typecheck, lint and formatting. Refreshed graph analysis maps production
changes; three test files remain unmapped.

* ci: profile fresh analyze overhead

Capture process and parser-worker CPU profiles in a separate CI-only run. Reject profiling with --check so diagnostic overhead never affects the acceptance gate.

* perf(analyze): trim continuation startup work

* fix(analyze): preserve recovery and storage bounds

Keep automatic writer pools page-scaled and restore frontend heap caps.
Adopt a generation recovered during handoff, reclaim sealed artifacts,
and retire compatible legacy sources after migration completes.

Report semantic degradation and omit provider causes from API logs.
Enforce no paid replay in the CI resume benchmark.

* perf(analyze): defer unused parser imports

* fix(workers): retain failed shutdown reservations

* perf: skip unused budget supervisor receipt

* fix: bound rejection history and watch budgets

* perf: batch provider vector writes within units

* fix: harden cleanup and semantic availability

* perf: avoid repeated analysis startup probes

Skip unused automatic-heap parent provenance and reuse one npm version
probe for runner selection and its warning. Keep child/watch identity
capture and manual/test heap overrides. Refs #3829.

* fix: normalize legacy export paths on Windows

Cover Unicode export directories and restore the heap parser comment. Refs #3829.

* test: restore watch resource mock contract

Provide the supervisor reservation used by watch refresh admission. Refs #3829.

* fix: retain watch budgets and bound lookahead

Keep explicit heap reservations across refreshes and limit brace scans to the existing three-line window. Refs #3829.

* fix: stop retries on shutdown and allow empty parse

* refactor: simplify embedding setup and test lists

* perf: batch vector completion hash updates

Keep hash finalization inside the existing transaction and row bounds. Run embedding input-isolation tests in the serial native project.

* fix: address PR #3829 recovery feedback

Preserve terminal worker results, reclaim orphan attempt metadata, retain artifacts with unrecognized space ownership, and correct the cancellation comment.

* perf: retain simple vector completion query

* perf: skip redundant alias identity probes

* perf: avoid Git probes for ordinary checkout roots

* perf: avoid redundant vector transactions

Standalone writes already execute in automatic transactions. Keep multi-query transactions and durable unit checkpoints unchanged.

* docs: clarify cancellation grace period

* fix: finish vector recovery and explicit drops

Preserve paid peers through source-admission aborts and complete legacy retirement after interrupted publication. Explicit drops remove validated vector payloads before their ownership receipts so later runs regenerate them.

Refs #3829

* fix: preserve storage errors during aborts

Only unwrap aborts raised by source admission. A simultaneous native write failure must propagate instead of entering the provider-abort completion path.

Refs #3829

* fix: validate retained analysis artifacts

Reject malformed cache keys before shard writes and retain legacy work
before shared-store adoption. Explicit drops validate legacy ownership
and keep receipts until payload cleanup succeeds. Damaged registered
graphs block stale local hook fallback.

* fix: preserve legacy and preflight contracts

Keep the native-default pool override, retain incomplete legacy seeds
with their owner, and include resource preflight in the worker timeout.

* fix: honor resource and preflight boundaries

Release optional cache space before rejecting an admissible source read.
Start server deadlines before preflight and reject null progress counts.
Pass the native-default pool sentinel through the database opener.

* test: align native and drop contracts

Accept the documented native-default zero sentinel. Verify the rebuilt graph and empty vectors instead of an obsolete escalation log.

Refs #3829

* perf: avoid redundant vector checkpoints

Acknowledge verified WAL commits without rewriting the database per unit.
Keep the final publication checkpoint and prove crash recovery from WAL.
Give publication test cases distinct titles for the CI execution audit.

Refs #3829

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-07 11:27:47 +00:00

615 lines
24 KiB
TypeScript

import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { JobManager } from '../../src/server/analyze-job.js';
import {
startSSEHarness,
terminalFrame,
terminalFrameCount,
type SSEHarness,
} from '../helpers/sse-harness.js';
import { publicRepoId } from '../../src/server/public-repo-id.js';
import {
resolveEmbedRunOutcome,
withMeasuredEmbeddingCount,
type EmbeddingRunResult,
} from '../../src/server/embed-run-outcome.js';
import { mintInterruptedCheckpoint } from '../../src/core/embedding-checkpoint.js';
import {
measurePersistedEmbeddingCount,
persistedEmbeddingCountOrUndefined,
} from '../../src/core/embedding-count.js';
import { loadMeta, saveMeta, type RepoMeta } from '../../src/storage/repo-manager.js';
import { deriveEmbeddingMode } from '../../src/core/embedding-mode.js';
/**
* NOTHING in this file imports `src/server/api.ts` for behavior. That module
* pulls Express, cors, the LadybugDB native adapter and the whole MCP wiring:
* reaching three pure helpers through it cost one 30s TIMEOUT and ~20s/~22s on
* the runs that passed, against a 30s `testTimeout` (#2790 review, finding 9).
* The helpers now live in `src/server/{sse-progress,embed-run-outcome}.ts` and
* `src/core/embedding-{count,checkpoint}.ts`, none of which import a database
* or a server.
*/
describe('analyze API logic', () => {
let manager: JobManager;
beforeEach(() => {
manager = new JobManager();
});
afterEach(() => {
manager.dispose();
});
it('creates a job and returns 202 shape', () => {
const job = manager.createJob({ repoUrl: 'https://github.com/user/repo' });
const response = { jobId: job.id, status: job.status };
expect(response.jobId).toBeTruthy();
expect(response.status).toBe('queued');
});
it('rejects when job already active for different repo', () => {
const job1 = manager.createJob({ repoUrl: 'https://github.com/user/repo1' });
manager.updateJob(job1.id, { status: 'analyzing' });
expect(() => manager.createJob({ repoUrl: 'https://github.com/user/repo2' })).toThrow(
/already in progress/,
);
});
it('returns existing job for same repo URL', () => {
const job1 = manager.createJob({ repoUrl: 'https://github.com/user/repo' });
manager.updateJob(job1.id, { status: 'analyzing' });
const job2 = manager.createJob({ repoUrl: 'https://github.com/user/repo' });
expect(job2.id).toBe(job1.id);
});
it('SSE progress listener receives all events including terminal', () => {
const job = manager.createJob({ repoUrl: 'https://github.com/user/sse-test' });
const events: Array<{ phase: string; percent: number }> = [];
const unsub = manager.onProgress(job.id, (progress) => {
events.push({ phase: progress.phase, percent: progress.percent });
});
manager.updateJob(job.id, {
status: 'analyzing',
progress: { phase: 'parsing', percent: 30, message: 'Parsing' },
});
manager.updateJob(job.id, {
progress: { phase: 'calls', percent: 50, message: 'Tracing calls' },
});
manager.updateJob(job.id, { status: 'complete', repoName: 'sse-test' });
unsub();
expect(events).toEqual([
{ phase: 'parsing', percent: 30 },
{ phase: 'calls', percent: 50 },
{ phase: 'complete', percent: 100 },
]);
});
});
const IDENTITY = { model: 'test-model', dimensions: 384, provider: 'local' };
const CLEAN_RUN: EmbeddingRunResult = {
nodesProcessed: 412,
chunksProcessed: 900,
failedNodeIds: [],
};
/** Progress figures an in-flight checkpoint records. */
const PROGRESS = { nodesProcessed: 4, totalNodes: 12, chunksProcessed: 9 };
/**
* ── #2790: an SSE client must not be told a partial run succeeded ──────────
*
* `runEmbeddingPipeline` emits `phase: 'ready'` / 100% UNCONDITIONALLY before
* returning — including when it dropped nodes to endpoint failures — and
* /api/embed relayed that as a progress phase before it had measured anything
* or decided the outcome. The relay treated a progress PHASE STRING of
* 'complete'/'failed' as terminal, so it wrote `event: complete` with
* `error: undefined`, called `res.end()` and unsubscribed; the route's later
* `updateJob({status:'failed'})` went into a stream with no listener. The web
* client fired `onComplete` and showed "ready" while a `GET /api/embed/:jobId`
* poller saw `failed` — the two consumers of one job disagreeing about whether
* the data is complete, and a regression against the pre-#2790 behavior where
* the pipeline threw and the client received the failure.
*
* These tests drive the REAL relay over a REAL HTTP server (same harness as
* server-sse-payload.test.ts) and subscribe BEFORE the misleading event is
* emitted — subscribing after it is exactly why the previous version of this
* suite passed while the bug was live.
*/
describe('mountSSEProgress terminality (#2790)', () => {
let harness: SSEHarness;
let manager: JobManager;
let baseUrl = '';
beforeEach(async () => {
// Mirrors both production mounts in createServer().
harness = await startSSEHarness('/api/embed/:jobId/progress');
manager = harness.manager;
baseUrl = harness.baseUrl;
});
afterEach(() => harness.close());
it('a partial run reaches the client as a failure, not a success', async () => {
const job = manager.createJob({ repoPath: '/ws/embed-partial' });
manager.updateJob(job.id, {
repoName: 'embed-partial',
status: 'analyzing',
progress: { phase: 'embedding', percent: 40, message: 'Embedding nodes (40%)...' },
});
// The client is connected and listening BEFORE anything terminal-looking is
// emitted. `fetch` resolves once headers arrive, and the handler subscribes
// synchronously before that (see server-sse-payload.test.ts).
const response = await fetch(`${baseUrl}/api/embed/${job.id}/progress`);
// A progress event that CLAIMS to be terminal. Production now maps the
// pipeline's `ready` to 'finalizing' instead, but a phase string must not be
// able to end the stream no matter who sends it — that is the invariant.
manager.updateJob(job.id, {
progress: { phase: 'complete', percent: 100, message: 'Embeddings complete' },
});
// Only now does the route learn the run dropped nodes.
const outcome = resolveEmbedRunOutcome(IDENTITY, {
nodesProcessed: 10,
chunksProcessed: 24,
failedNodeIds: ['node-a', 'node-b'],
});
manager.updateJob(job.id, {
status: 'failed',
error: outcome.error,
partial: outcome.partial,
progress: { phase: 'failed', percent: 100, message: String(outcome.error) },
});
const body = await response.text();
expect(body).not.toContain('event: complete');
expect(body).not.toContain('/ws/embed-partial');
expect(terminalFrameCount(body)).toBe(1);
expect(terminalFrame(body, 'failed')).toMatchObject({
repoName: 'embed-partial',
error: expect.stringContaining('finished partially') as unknown as string,
// The distinction a UI needs to offer "retry 2 nodes" instead of a bare
// red chip — carried without adding a `status` union member.
partial: { kind: 'embedding-partial', pendingNodeCount: 2, nodesProcessed: 10 },
});
});
it('a clean run produces exactly one terminal complete event', async () => {
const job = manager.createJob({ repoPath: '/ws/embed-clean' });
manager.updateJob(job.id, {
repoName: 'embed-clean',
status: 'analyzing',
progress: { phase: 'embedding', percent: 40, message: 'Embedding nodes (40%)...' },
});
const response = await fetch(`${baseUrl}/api/embed/${job.id}/progress`);
// What the route actually emits between the pipeline returning and the
// outcome being known.
manager.updateJob(job.id, {
progress: { phase: 'finalizing', percent: 100, message: 'Finalizing embeddings...' },
});
manager.updateJob(job.id, {
status: 'complete',
progress: { phase: 'complete', percent: 100, message: 'Embeddings complete' },
});
const body = await response.text();
expect(body).not.toContain('event: failed');
// Exactly one — the status update carries a `progress` too, and #2264's
// single-emit rule is what keeps that from double-writing the terminal frame.
expect(terminalFrameCount(body)).toBe(1);
// Public frame: display name + opaque repoId, never the analyzed path.
expect(terminalFrame(body, 'complete')).toEqual({
repoName: 'embed-clean',
repoId: publicRepoId('/ws/embed-clean'),
});
// The 'finalizing' frame was relayed as ordinary progress, not swallowed.
expect(body).toContain('"phase":"finalizing"');
});
it('the analyze path still closes on its own terminal update', async () => {
// /api/analyze mounts the same relay. Its worker reports phases like
// 'parsing' and 'done' (never 'complete'), so the fix must not leave that
// stream open — it closes when the job's STATUS becomes terminal.
const job = manager.createJob({ repoPath: '/ws/reels' });
manager.updateJob(job.id, {
status: 'analyzing',
progress: { phase: 'parsing', percent: 30, message: 'Parsing' },
});
const response = await fetch(`${baseUrl}/api/embed/${job.id}/progress`);
manager.updateJob(job.id, {
progress: { phase: 'done', percent: 100, message: 'Done' },
});
manager.updateJob(job.id, { status: 'complete', repoName: 'reels' });
const body = await response.text();
expect(terminalFrameCount(body)).toBe(1);
expect(terminalFrame(body, 'complete')).toEqual({
repoName: 'reels',
repoId: publicRepoId('/ws/reels'),
});
});
it('a job that finished before the client connected replays its outcome', async () => {
const job = manager.createJob({ repoPath: '/ws/embed-late' });
const outcome = resolveEmbedRunOutcome(IDENTITY, {
nodesProcessed: 3,
chunksProcessed: 9,
failedNodeIds: ['node-a'],
});
manager.updateJob(job.id, {
status: 'failed',
repoName: 'embed-late',
error: outcome.error,
partial: outcome.partial,
});
const body = await (await fetch(`${baseUrl}/api/embed/${job.id}/progress`)).text();
expect(terminalFrameCount(body)).toBe(1);
expect(terminalFrame(body, 'failed')).toMatchObject({
error: expect.stringContaining('finished partially') as unknown as string,
partial: { kind: 'embedding-partial', pendingNodeCount: 1, nodesProcessed: 3 },
});
});
});
/**
* ── #2790: POST /api/embed must not report unqualified success ─────────
*
* The pipeline no longer throws when a sub-batch loses its endpoint — it
* deletes the affected nodes' rows and names them in `failedNodeIds`. The route
* discarded that receipt: it cleared `embeddingCheckpoint` and marked the job
* 'complete', so a partial run looked identical to a clean one and the dropped
* nodes were never retried (pre-#2790 the pipeline threw and the catch marked
* the job failed).
*/
describe('resolveEmbedRunOutcome (#2790)', () => {
it('clears the checkpoint and reports no error on a clean, measured run', () => {
const outcome = resolveEmbedRunOutcome(IDENTITY, CLEAN_RUN, { measuredEmbeddings: 412 });
expect(outcome.checkpoint).toBeUndefined();
expect(outcome.error).toBeUndefined();
expect(outcome.partial).toBeUndefined();
});
it('retains the checkpoint with the dropped ids and reports an error on a partial run', () => {
const outcome = resolveEmbedRunOutcome(IDENTITY, {
nodesProcessed: 10,
chunksProcessed: 24,
failedNodeIds: ['node-a', 'node-b'],
});
// The record of what failed survives — this is the pending set the next
// run's `forceReembedNodeIds` re-embeds.
expect(outcome.checkpoint).toMatchObject({
pendingNodeIds: ['node-a', 'node-b'],
nodesProcessed: 10,
totalNodes: 12,
chunksProcessed: 24,
model: 'test-model',
dimensions: 384,
provider: 'local',
// The run COMPLETED: these nodes provably hold zero rows, so a later
// identity mismatch may drop the set with a warning instead of wedging
// every subsequent run (repo-manager.ts).
kind: 'partial',
});
expect(outcome.error).toMatch(/2 node\(s\)/);
expect(outcome.partial).toEqual({
kind: 'embedding-partial',
pendingNodeCount: 2,
nodesProcessed: 10,
});
});
it('stamps no attempt count on a fresh partial run', () => {
const outcome = resolveEmbedRunOutcome(
IDENTITY,
{ nodesProcessed: 10, chunksProcessed: 24, failedNodeIds: ['node-a'] },
// Resumed from an in-flight marker, not a partial one.
{ resumedFrom: mintInterruptedCheckpoint(IDENTITY, PROGRESS, ['node-a']) },
);
expect(outcome.checkpoint).toMatchObject({ kind: 'partial' });
expect(outcome.checkpoint?.attempts).toBeUndefined();
});
it('advances the attempt count only when a resumed pending node fails again', () => {
const resumedFrom: RepoMeta['embeddingCheckpoint'] = {
at: new Date(0).toISOString(),
nodesProcessed: 10,
totalNodes: 12,
chunksProcessed: 24,
...IDENTITY,
kind: 'partial',
attempts: 1,
pendingNodeIds: ['node-a', 'node-b'],
};
// Same node failed again → the retry is not converging; the budget advances.
expect(
resolveEmbedRunOutcome(
IDENTITY,
{ nodesProcessed: 11, chunksProcessed: 26, failedNodeIds: ['node-a'] },
{ resumedFrom },
).checkpoint,
).toMatchObject({ kind: 'partial', attempts: 2 });
// The resumed set cleared and DIFFERENT nodes were lost → a fresh partial,
// so the budget resets. The bound exists for a node the endpoint rejects
// deterministically, not for an endpoint that is merely flaky.
expect(
resolveEmbedRunOutcome(
IDENTITY,
{ nodesProcessed: 11, chunksProcessed: 26, failedNodeIds: ['node-z'] },
{ resumedFrom },
).checkpoint?.attempts,
).toBeUndefined();
});
});
describe('the mid-run marker /api/embed writes (mintInterruptedCheckpoint, #2790)', () => {
it('stamps interrupted, so resume regenerates a possibly half-written window', () => {
const checkpoint = mintInterruptedCheckpoint(IDENTITY, PROGRESS, ['node-a', 'node-b']);
expect(checkpoint).toMatchObject({
kind: 'interrupted',
nodesProcessed: 4,
totalNodes: 12,
chunksProcessed: 9,
model: 'test-model',
dimensions: 384,
provider: 'local',
pendingNodeIds: ['node-a', 'node-b'],
});
// `attempts` bounds retries of a 'partial' set; an in-flight marker has no
// such budget because its rows may exist.
expect(checkpoint.attempts).toBeUndefined();
});
});
/**
* ── The /api/embed count omission (silent embedding loss) ──────────────
*
* The route generated embeddings and wrote `embeddingCheckpoint`, but never
* `stats.embeddings`. A repo embedded purely through the server therefore kept
* whatever count the last CLI `analyze` stamped — `0` for a repo analyzed
* without embeddings. The next CLI run reads that as `existingEmbeddingCount`,
* `deriveEmbeddingMode` sees `hasExisting: false` → `shouldLoadCache: false`,
* and `gitnexus analyze --force` wipes the database with no cache load: every
* server-generated embedding is destroyed with no warning.
*
* The route body is an inline closure inside `createServer`, so its finalize
* sequence is replayed here over the SAME helpers the route calls, with real
* meta.json I/O and the real `deriveEmbeddingMode`. The consequence is what
* these tests pin, not the field.
*/
describe('POST /api/embed records the embedding count it measured', () => {
let metaDir: string;
let seeded: RepoMeta;
beforeEach(async () => {
metaDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-embed-count-'));
});
afterEach(async () => {
await fs.rm(metaDir, { recursive: true, force: true });
});
/** What a CLI `analyze` (plus any mid-run checkpoint) leaves on disk. */
const seedMeta = async (
embeddings: number | undefined,
embeddingCheckpoint?: RepoMeta['embeddingCheckpoint'],
): Promise<void> => {
seeded = {
repoPath: '/repo/embed-count',
lastCommit: 'abc123',
indexedAt: new Date(0).toISOString(),
stats: { nodes: 500, ...(embeddings === undefined ? {} : { embeddings }) },
embeddingCheckpoint,
};
await saveMeta(metaDir, seeded);
};
const rowsWith = (cnt: unknown) => async () => [{ cnt } as Record<string, unknown>];
/** The route's finalize sequence: measure → re-read meta → resolve → write. */
const finalizeEmbedRun = async (
runQuery: (cypher: string) => Promise<Array<Record<string, unknown>> | undefined>,
pipelineResult: EmbeddingRunResult,
): Promise<RepoMeta | null> => {
const measured = await measurePersistedEmbeddingCount(runQuery);
const finalMeta = (await loadMeta(metaDir)) ?? seeded;
const outcome = resolveEmbedRunOutcome(IDENTITY, pipelineResult, {
measuredEmbeddings: persistedEmbeddingCountOrUndefined(measured),
onDisk: finalMeta,
});
await saveMeta(
metaDir,
withMeasuredEmbeddingCount(
{ ...finalMeta, embeddingCheckpoint: outcome.checkpoint },
measured,
),
);
return loadMeta(metaDir);
};
const embeddingCountOf = (meta: RepoMeta | null): number => meta?.stats?.embeddings ?? 0;
it('writes the measured count into meta on a clean run, without disturbing the other stats', async () => {
await seedMeta(0);
const asked: string[] = [];
const written = await finalizeEmbedRun(async (cypher) => {
asked.push(cypher);
return [{ cnt: 412 }];
}, CLEAN_RUN);
expect(written).toMatchObject({ stats: { nodes: 500, embeddings: 412 } });
// A clean, MEASURED run clears the checkpoint (#2790 contract).
expect(written?.embeddingCheckpoint).toBeUndefined();
// Measured, not restated: the count comes from the live embedding table.
expect(asked).toEqual([expect.stringMatching(/MATCH \(e:\w+\) RETURN count\(e\) AS cnt/)]);
});
it('is what makes the next CLI run preserve instead of wipe', async () => {
await seedMeta(0);
// Pre-fix state: the server embedded 412 nodes but meta still says 0.
const stale = embeddingCountOf(await loadMeta(metaDir));
expect(stale).toBe(0);
expect(deriveEmbeddingMode({ force: true }, stale)).toMatchObject({
// `--force` rebuilds without loading the embedding cache → the 412
// server-generated vectors are destroyed.
shouldLoadCache: false,
preserveExistingEmbeddings: false,
});
const written = await finalizeEmbedRun(rowsWith(412), CLEAN_RUN);
const honest = embeddingCountOf(written);
expect(honest).toBe(412);
// Post-fix: `--force` loads the cache and regenerates on top of it rather
// than discarding the index. (`preserveExistingEmbeddings` is false here by
// design — `--force` upgrades to `forceRegenerateEmbeddings`; the wipe
// protection is `shouldLoadCache`.)
expect(deriveEmbeddingMode({ force: true }, honest)).toMatchObject({
shouldLoadCache: true,
forceRegenerateEmbeddings: true,
});
// A routine `analyze` preserves them outright.
expect(deriveEmbeddingMode({}, honest)).toMatchObject({
shouldLoadCache: true,
preserveExistingEmbeddings: true,
});
});
it('treats an unanswerable count query as unknown rather than 0', async () => {
// The query throws for reasons unrelated to how many rows were written.
await expect(
measurePersistedEmbeddingCount(async () => {
throw new Error('Connection closed');
}),
).resolves.toMatchObject({ kind: 'unknown', reason: 'Connection closed' });
// No row / no cell: an empty table would still answer with a 0.
await expect(measurePersistedEmbeddingCount(async () => [])).resolves.toMatchObject({
kind: 'unknown',
});
await expect(measurePersistedEmbeddingCount(async () => undefined)).resolves.toMatchObject({
kind: 'unknown',
});
// Non-numeric cell — same class of unknown.
await expect(measurePersistedEmbeddingCount(rowsWith('many'))).resolves.toMatchObject({
kind: 'unknown',
});
// A real zero is still a real answer.
await expect(measurePersistedEmbeddingCount(rowsWith(0))).resolves.toEqual({
kind: 'measured',
count: 0,
});
});
it('leaves the previous count alone when the measurement fails, never writing a fabricated 0', async () => {
await seedMeta(137);
const written = await finalizeEmbedRun(async () => {
throw new Error('Connection closed');
}, CLEAN_RUN);
expect(written).toMatchObject({ stats: { embeddings: 137 } });
// The dangerous direction is wrong-LOW: a fabricated 0 here would arm the
// wipe the test above describes.
expect(deriveEmbeddingMode({ force: true }, embeddingCountOf(written))).toMatchObject({
shouldLoadCache: true,
});
});
it('keeps the recovery marker when a clean run cannot verify its own count', async () => {
// The state that arms the silent wipe: meta records 0 embeddings (a repo
// analyzed without them, embedded through the server), the run succeeded,
// and the count query cannot answer — so no honest count can be stamped.
const midRunMarker = mintInterruptedCheckpoint(IDENTITY, PROGRESS, ['node-a']);
await seedMeta(0, midRunMarker);
const written = await finalizeEmbedRun(async () => {
throw new Error('Connection closed');
}, CLEAN_RUN);
// No fabricated value: neither a 0 nor a NaN/null lands in meta.
expect(written).toMatchObject({ stats: { nodes: 500, embeddings: 0 } });
// …and the marker this run wrote SURVIVES, so something on disk still
// records that embeddings were produced. Clearing it here would leave the
// index with zero evidence of its own embeddings.
expect(written?.embeddingCheckpoint).toMatchObject({
kind: 'interrupted',
pendingNodeIds: ['node-a'],
});
});
it('still clears the marker on an unverifiable run once meta records embeddings', async () => {
// Same unmeasurable run, but the recorded count already proves the index is
// accounted for — nothing needs preserving, so the clean-run contract wins.
await seedMeta(412, mintInterruptedCheckpoint(IDENTITY, PROGRESS, ['node-a']));
const written = await finalizeEmbedRun(async () => {
throw new Error('Connection closed');
}, CLEAN_RUN);
expect(written).toMatchObject({ stats: { embeddings: 412 } });
expect(written?.embeddingCheckpoint).toBeUndefined();
});
it('records the honest count on a partial run, alongside the pending checkpoint', async () => {
await seedMeta(0);
const written = await finalizeEmbedRun(rowsWith(300), {
nodesProcessed: 300,
chunksProcessed: 700,
failedNodeIds: ['node-a', 'node-b'],
});
// A partial index that is honest about itself survives the next run: the
// count keeps `--force` from wiping it, the checkpoint re-embeds the rest.
expect(written).toMatchObject({
stats: { embeddings: 300 },
embeddingCheckpoint: {
pendingNodeIds: ['node-a', 'node-b'],
nodesProcessed: 300,
kind: 'partial',
},
});
expect(deriveEmbeddingMode({ force: true }, embeddingCountOf(written))).toMatchObject({
shouldLoadCache: true,
});
});
});
// The shared phase now owns checkpoint/count publication. Its runtime contract
// is covered by analysis-embedding-phase.test.ts and analysis-embedding-flow.test.ts;
// api-fts-mode.test.ts drives this route's progress, failure and completion wiring.
describe('HTTP repo catalog validation', () => {
const readSource = () =>
fs.readFile(path.join(__dirname, '..', '..', 'src', 'server', 'api.ts'), 'utf-8');
it('lists and resolves repos with validate: true, and maps StorageRequirementError', async () => {
const source = await readSource();
expect(source).toMatch(/const repos = await listRegisteredRepos\(\{\s*validate:\s*true\s*\}\)/);
expect(source).toMatch(
/const freshRepos = await listRegisteredRepos\(\{\s*validate:\s*options\.validateStorage !== false,\s*\}\)/,
);
expect(source).toMatch(
/app\.get\('\/api\/repos'[\s\S]*listRegisteredRepos\(\{\s*validate:\s*true\s*\}\)/,
);
expect(source).toMatch(/sendStorageRequirementHttp\(err, res\)/);
expect(source).toMatch(/storageRequirementToHttp\(err\)/);
expect(source).toMatch(/code: 'index-unavailable'/);
});
});