GitNexus/gitnexus/test/unit/embed-input-ranges-concurrency.test.ts
Gergő Magyar d9d5775cdd
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
perf(embeddings): remove quadratic vector-store scans and speed up the embedding phase (#3874)
* perf(embeddings): remove quadratic vector-store scans and speed up the embedding phase

Per-unit vector-store statements keyed by `{pk:$ids[i]}` were planned as
SCAN_NODE_TABLE -> CROSS_PRODUCT -> FILTER, and MERGE always hash-joined a
full table scan, so every 64-node unit scanned the whole receipt/chunk
tables and a large run was quadratic (#3870). Bind the key through WITH so
LadybugDB uses QUERY_PRIMARY_KEY_LOOKUP, and replace MERGE in beginNodes and
markSelected with a keyed update plus CREATE inside one transaction.

Further embedding-phase speedups, measured on released rc.216 with only the
changed files swapped in:

- Vector rows are passed as one float32 string per row and CAST natively
  instead of a numeric list the Node binding converts element by element
  on the main thread. Float32 values round-trip exactly; only the sign of a
  negative zero is not kept.
- seal() builds the vector index with the whole CPU allowance
  (budget.embedding.indexThreads) rather than the model thread cap.
- Structural field names no longer build a type environment over the whole
  hydrated class; only field types consulted it and embedding text keeps
  names alone, so the generated inputs are unchanged.
- HTTP providers keep a bounded window of requests in flight per unit
  (GITNEXUS_EMBEDDING_CONCURRENCY, default 4, 1 = serial). Results stay in
  input order so chunks reach the store contiguously; local models stay
  serial.

157k nodes / 192k chunks, zero-latency endpoint: embedding 13m45s -> 3m15s,
index build ~3m -> 1m24s. 31k nodes at 40 ms per request: 265s -> 95s.

Refs #3870

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* perf(embeddings): skip the transaction when a unit only creates or only updates

beginNodes and markSelected wrapped their keyed update and create in a
transaction even when only one of the two statements ran, which is the
normal case: a first run only creates and a replayed unit only updates. A
lone statement is already atomic, so only a unit that does both now pays
for BEGIN/COMMIT. Same durability, two fewer native round trips per unit.

Refs #3870

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix: restore concurrent embedding recovery

Count original provider batches, preserve resumable failures, and
serialize half-open admission. Stop unconsumed window work safely.

Refs #3874

Note: pre-existing environment failures in setup.test.ts,
setup-skills.test.ts, and scenario-map/consolidation.test.ts are not
changed by this PR. All 103 tests pass with CODEX_HOME unset and
pinned jscpd available.

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 13:08:17 +00:00

122 lines
4.2 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import { embedInputRanges } from '../../src/core/embeddings/embedding-pipeline.js';
import { HttpEmbeddingError } from '../../src/core/embeddings/http-client.js';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
/** Provider whose requests stay open until the test releases them. */
function heldProvider() {
const open: Array<{ texts: string[]; release: () => void }> = [];
let active = 0;
let peak = 0;
const provider = async (texts: string[]) => {
active++;
peak = Math.max(peak, active);
await new Promise<void>((release) => open.push({ texts, release }));
active--;
return texts.map((text) => Float32Array.of(Number(text)));
};
return { provider, open, peak: () => peak };
}
const texts = Array.from({ length: 10 }, (_, i) => String(i));
describe('embedInputRanges provider concurrency (#3870)', () => {
it.each([
[undefined, 1],
[3, 3],
])('with concurrency %s keeps %i requests in flight', async (concurrency, expected) => {
const held = heldProvider();
const ranges: number[][] = [];
const consumed = (async () => {
for await (const range of embedInputRanges(texts, 2, undefined, held.provider, concurrency))
ranges.push([range.start, range.end]);
})();
await tick();
expect(held.open).toHaveLength(expected);
// Release every request, newest first, until all five sub-batches finish.
for (let released = 0; released < 5; released++) {
await vi.waitFor(() => expect(held.open.length).toBeGreaterThan(0));
held.open.pop()!.release();
await tick();
}
await consumed;
expect(held.peak()).toBe(expected);
// Out-of-order completion never reorders results: a node's chunks must
// reach the vector store contiguously.
expect(ranges).toEqual([
[0, 2],
[2, 4],
[4, 6],
[6, 8],
[8, 10],
]);
});
it('bisects a rejected sub-batch in place while its neighbours proceed', async () => {
let active = 0;
let peak = 0;
const provider = async (batch: string[]) => {
peak = Math.max(peak, ++active);
await tick();
active--;
if (batch.includes('5')) throw new HttpEmbeddingError('input too long', { status: 413 });
return batch.map((text) => Float32Array.of(Number(text)));
};
const results: Array<[number, number, boolean]> = [];
for await (const range of embedInputRanges(texts, 4, undefined, provider, 3))
results.push([range.start, range.end, 'error' in range]);
expect(results).toEqual([
[0, 4, false],
[4, 5, false],
[5, 6, true],
[6, 8, false],
[8, 10, false],
]);
expect(peak).toBe(3);
});
it('aborts window peers before draining when the consumer fails', async () => {
const failure = new Error('vector write failed');
let aborted = 0;
const provider = async (batch: string[], { signal }: { signal?: AbortSignal }) => {
if (batch[0] === '0') return [Float32Array.of(0), Float32Array.of(1)];
await new Promise<void>((_resolve, reject) => {
signal!.addEventListener(
'abort',
() => {
aborted++;
reject(signal!.reason);
},
{ once: true },
);
});
throw new Error('unreachable');
};
const consume = async () => {
for await (const _range of embedInputRanges(texts, 2, undefined, provider, 4)) throw failure;
};
await expect(consume()).rejects.toBe(failure);
expect(aborted).toBe(3);
});
it('settles in-flight requests before surfacing a cancellation', async () => {
const controller = new AbortController();
const reason = new Error('stop');
let settled = 0;
const provider = async (batch: string[]) => {
await tick();
if (batch[0] === '0') controller.abort(reason);
await tick();
settled++;
if (controller.signal.aborted) throw reason;
return batch.map((text) => Float32Array.of(Number(text)));
};
const consume = async () => {
for await (const range of embedInputRanges(texts, 2, controller.signal, provider, 3))
expect(range.start).toBeGreaterThanOrEqual(0);
};
await expect(consume()).rejects.toBe(reason);
expect(settled).toBe(3);
});
});