GitNexus/gitnexus/test/unit/http-embedding-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

80 lines
2.7 KiB
TypeScript

import { afterEach, expect, it, vi } from 'vitest';
import { getBreaker } from 'gitnexus-shared';
import { __resetBreakerRegistry__ } from 'gitnexus-shared/test-helpers';
import { httpEmbed, httpEmbeddingConcurrency } from '../../src/core/embeddings/http-client.js';
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
vi.unstubAllGlobals();
__resetBreakerRegistry__();
});
it.each([
[undefined, 4],
['', 4],
['1', 1],
['4', 4],
['64', 64],
])('parses HTTP concurrency %s as %i', (value, expected) => {
vi.stubEnv('GITNEXUS_EMBEDDING_CONCURRENCY', value);
expect(httpEmbeddingConcurrency()).toBe(expected);
});
it.each(['0', '65', 'abc', '-1', '1.5', ' 4', '9007199254740992'])(
'rejects invalid HTTP concurrency %s',
(value) => {
vi.stubEnv('GITNEXUS_EMBEDDING_CONCURRENCY', value);
expect(httpEmbeddingConcurrency).toThrow('GITNEXUS_EMBEDDING_CONCURRENCY');
},
);
it('waits for the half-open probe before admitting concurrent HTTP peers', async () => {
vi.useFakeTimers();
vi.stubEnv('GITNEXUS_EMBEDDING_URL', 'http://embedding.test/v1');
vi.stubEnv('GITNEXUS_EMBEDDING_MODEL', 'fixture');
vi.stubEnv('GITNEXUS_EMBEDDING_DIMS', '1');
let now = 0;
const breaker = getBreaker('embeddings-http', { now: () => now });
for (let i = 0; i < 3; i++) breaker.recordFailure();
now = 31_000;
let release!: () => void;
const probe = new Promise<void>((resolve) => {
release = resolve;
});
const fetch = vi.fn(async () => {
await probe;
return new Response(JSON.stringify({ data: [{ embedding: [1] }] }));
});
vi.stubGlobal('fetch', fetch);
const requests = Array.from({ length: 4 }, () => httpEmbed(['input']));
await vi.advanceTimersByTimeAsync(0);
expect(fetch).toHaveBeenCalledTimes(1);
release();
await vi.advanceTimersByTimeAsync(1000);
expect(await Promise.all(requests)).toEqual(
Array.from({ length: 4 }, () => [Float32Array.of(1)]),
);
expect(fetch).toHaveBeenCalledTimes(4);
expect(breaker.getState()).toBe('closed');
});
it('cancels a peer waiting for the half-open probe without sending HTTP work', async () => {
vi.useFakeTimers();
vi.stubEnv('GITNEXUS_EMBEDDING_URL', 'http://embedding.test/v1');
vi.stubEnv('GITNEXUS_EMBEDDING_MODEL', 'fixture');
let now = 0;
const breaker = getBreaker('embeddings-http', { now: () => now });
for (let i = 0; i < 3; i++) breaker.recordFailure();
now = 31_000;
breaker.check();
const fetch = vi.fn();
vi.stubGlobal('fetch', fetch);
const controller = new AbortController();
const request = httpEmbed(['input'], { signal: controller.signal });
const rejected = expect(request).rejects.toThrow('cancelled');
controller.abort();
await rejected;
expect(fetch).not.toHaveBeenCalled();
expect(breaker.isProbeInFlight()).toBe(true);
});