GitNexus/gitnexus/test/helpers/embedding-restart-runner.mjs
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

111 lines
4.3 KiB
JavaScript

// Exit at JS-visible boundaries after native promises settle. Never kill a
// worker or interrupt a native call; omit cleanup to exercise process recovery.
import fs from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { runPublishedEmbeddingJob } from '../../dist/core/embeddings/embedding-job.js';
import { VectorStore } from '../../dist/core/lbug/vector-store.js';
import { EmbeddingJobJournal } from '../../dist/storage/embedding-job-journal.js';
import { loadMeta, saveMeta } from '../../dist/storage/repo-manager.js';
const [root, boundary] = process.argv.slice(2);
const crash = () => process.exit(73);
const secondUnit = (rows) => rows.some((row) => row.nodeId === 'Function:a.ts:n00064');
const begin = EmbeddingJobJournal.prototype.begin;
EmbeddingJobJournal.prototype.begin = async function (intent) {
if (intent.start.unit === 1 && boundary === 'intent-before') crash();
await begin.call(this, intent);
if (intent.start.unit === 1 && boundary === 'intent-after') crash();
};
for (const method of ['appendBatch', 'checkpointUnit']) {
const original = VectorStore.prototype[method];
VectorStore.prototype[method] = async function (rows) {
const selected = secondUnit(rows);
if (selected && boundary === `${method}-before`) crash();
const result = await original.call(this, rows);
if (selected && boundary === `${method}-after`) crash();
return result;
};
}
const acknowledge = EmbeddingJobJournal.prototype.acknowledge;
EmbeddingJobJournal.prototype.acknowledge = async function (result) {
const selected = this.snapshot().active?.start.unit === 1;
if (selected && boundary === 'cursor-before') crash();
await acknowledge.call(this, result);
if (selected && boundary === 'cursor-after') crash();
};
const seal = VectorStore.prototype.seal;
VectorStore.prototype.seal = async function (...args) {
const result = await seal.apply(this, args);
if (boundary === 'seal-after') crash();
return result;
};
const nodes = Array.from({ length: 130 }, (_, index) => {
const name = `n${String(index).padStart(5, '0')}`;
const body =
index === 64
? Array.from({ length: 40 }, (_, line) => ` const value${line} = "漢😀";`).join('\n')
: ' return 1;';
const content = `export function ${name}() {\n${body}\n}`;
return {
id: `Function:a.ts:${name}`,
name,
label: 'Function',
filePath: 'a.ts',
content,
startLine: 1,
endLine: content.split('\n').length,
};
});
const byId = new Map(nodes.map((node) => [node.id, node]));
const result = await runPublishedEmbeddingJob(
{
metadataDirectory: root,
graphPath: path.join(root, `lbug.generation.${'a'.repeat(32)}`),
resources: {
graphPoolBytes: 16 * 1024 ** 2,
vectorPoolBytes: 64 * 1024 ** 2,
modelBytes: 0,
modelHeapMb: 0,
queueBytes: 16 * 1024 ** 2,
nativeThreads: 1,
indexThreads: 1,
reservedBytes: 96 * 1024 ** 2,
},
config: { threads: 1, subBatchSize: 8, maxInputChars: 256 },
metadata: {
loadMetadata: () => loadMeta(root),
saveMetadata: async (metadata) => {
await saveMeta(root, metadata);
if (metadata.vectorGeneration && boundary === 'pointer-after') crash();
},
},
},
{
identity: () => ({ provider: 'local', model: 'restart-fixture', dimensions: 4 }),
initializeProvider: async () => {},
openSource: async () => ({
async *scan(label) {
if (label !== 'Function') return;
for (const node of nodes)
yield { id: node.id, contentBytes: Buffer.byteLength(node.content), metadataBytes: 1024 };
},
fetch: async (_label, ids) => ids.map((id) => byId.get(id)),
close: async () => {},
}),
provider: async (texts) => {
const inputs = texts.map((text) => {
// Interior slices of the oversized node need not repeat its name.
const node = text.match(/n\d{5}/)?.[0] ?? null;
return { node, hash: createHash('sha256').update(text).digest('hex') };
});
await fs.appendFile(
path.join(root, `${boundary}.inputs.jsonl`),
inputs.map((input) => JSON.stringify(input) + '\n').join(''),
);
return texts.map(() => new Float32Array([1, 0, 0, 0]));
},
},
);
await fs.writeFile(path.join(root, `${boundary}.result.json`), JSON.stringify(result));