GitNexus/gitnexus/test/unit/local-embedding-model.test.ts
samuel mbabhazi e3e50be954
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
feat(embeddings): select the local model with GITNEXUS_EMBEDDING_MODEL_ID (#3802)
* feat(embeddings): select the local model with GITNEXUS_EMBEDDING_MODEL_ID

The in-process embedder always loaded Snowflake/snowflake-arctic-embed-xs.
GITNEXUS_EMBEDDING_MODEL_ID now names another transformers.js model, and a
custom model takes its vector width from GITNEXUS_EMBEDDING_DIMS, the value
the vector column is already created with.

- A custom model joins the embedding content hash, so switching models
  re-embeds every node instead of reusing vectors from the previous model.
  Default-model hashes are unchanged.
- A custom model whose vectors have another width stops the run on the first
  sub-batch with the value to set, printed without a stack dump.
- Unset, every path behaves as before: the default model keeps 384
  dimensions and no width check, whatever GITNEXUS_EMBEDDING_DIMS says.

Refs #628

* fix(embeddings): document safe model switches

Require forced embedding generation when switching local models:
unchanged source can otherwise retain vectors from the old model.
Verify replacement and reuse through real analysis and LadybugDB.

Refs #3802

* test(embeddings): isolate model config cases

Preserve inherited model IDs and verify one error message with no
stack output. Correct the MCP comment for custom local dimensions.

Refs #3802

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-03 12:14:49 +00:00

113 lines
4.3 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { contentHashForNode } from '../../src/core/embeddings/embedding-pipeline.js';
import { DEFAULT_EMBEDDING_CONFIG, type EmbeddableNode } from '../../src/core/embeddings/types.js';
const sidecarEmbedBatchMock = vi.hoisted(() => vi.fn());
vi.mock('../../src/core/embeddings/embedding-sidecar-client.js', () => ({
ensureEmbeddingSidecar: vi.fn(),
getSidecarDevice: () => 'cpu',
reapEmbeddingSidecarAndWait: vi.fn(),
sidecarEmbedBatch: (...args: unknown[]) => sidecarEmbedBatchMock(...args),
}));
vi.mock('../../src/core/embeddings/runtime-support.js', () => ({
assessLocalEmbeddingRuntime: () => ({ status: 'ready' }),
getLocalEmbeddingRuntimeBlocker: () => null,
}));
const { embedBatch, embedText, getEmbeddingDimensions } =
await import('../../src/core/embeddings/embedder.js');
const { resolveEmbeddingIdentity } =
await import('../../src/core/embeddings/embedding-identity.js');
const ENV_KEYS = [
'GITNEXUS_EMBEDDING_MODEL_ID',
'GITNEXUS_EMBEDDING_DIMS',
'GITNEXUS_EMBEDDING_URL',
'GITNEXUS_EMBEDDING_MODEL',
] as const;
const savedEnv: Record<string, string | undefined> = {};
const vectors = (count: number, width: number): Float32Array[] =>
Array.from({ length: count }, () => new Float32Array(width));
beforeEach(() => {
for (const key of ENV_KEYS) {
savedEnv[key] = process.env[key];
delete process.env[key];
}
sidecarEmbedBatchMock.mockReset();
});
afterEach(() => {
for (const key of ENV_KEYS) {
if (savedEnv[key] === undefined) delete process.env[key];
else process.env[key] = savedEnv[key];
}
});
describe('local embedding model selection', () => {
it('keeps the default model at 384 dimensions even when GITNEXUS_EMBEDDING_DIMS is set', () => {
process.env.GITNEXUS_EMBEDDING_DIMS = '1024';
expect(getEmbeddingDimensions()).toBe(DEFAULT_EMBEDDING_CONFIG.dimensions);
});
it('takes the vector width of a custom model from GITNEXUS_EMBEDDING_DIMS', () => {
process.env.GITNEXUS_EMBEDDING_MODEL_ID = 'Xenova/bge-base-en-v1.5';
expect(getEmbeddingDimensions()).toBe(384);
process.env.GITNEXUS_EMBEDDING_DIMS = '768';
expect(getEmbeddingDimensions()).toBe(768);
process.env.GITNEXUS_EMBEDDING_DIMS = '768x';
expect(() => getEmbeddingDimensions()).toThrow(
'GITNEXUS_EMBEDDING_DIMS must be a positive integer',
);
});
it('records the custom model and its width in the embedding identity', () => {
process.env.GITNEXUS_EMBEDDING_MODEL_ID = 'Xenova/bge-base-en-v1.5';
process.env.GITNEXUS_EMBEDDING_DIMS = '768';
expect(resolveEmbeddingIdentity()).toEqual({
model: 'Xenova/bge-base-en-v1.5',
dimensions: 768,
provider: 'local',
});
});
it('rejects local vectors whose width differs from the configured dimensions', async () => {
process.env.GITNEXUS_EMBEDDING_MODEL_ID = 'Xenova/bge-base-en-v1.5';
sidecarEmbedBatchMock.mockResolvedValue(vectors(2, 768));
await expect(embedBatch(['a', 'b'])).rejects.toThrow(
'local model Xenova/bge-base-en-v1.5 returned 768d vectors, but expected 384d. ' +
'Set GITNEXUS_EMBEDDING_DIMS=768',
);
sidecarEmbedBatchMock.mockResolvedValue(vectors(1, 768));
await expect(embedText('a')).rejects.toThrow('Set GITNEXUS_EMBEDDING_DIMS=768');
});
it('returns local vectors that match the configured dimensions', async () => {
process.env.GITNEXUS_EMBEDDING_MODEL_ID = 'Xenova/bge-base-en-v1.5';
process.env.GITNEXUS_EMBEDDING_DIMS = '768';
sidecarEmbedBatchMock.mockResolvedValue(vectors(2, 768));
const result = await embedBatch(['a', 'b']);
expect(result.map((vec) => vec.length)).toEqual([768, 768]);
});
it('changes the content hash for a custom model only', () => {
const node: EmbeddableNode = {
id: 'Function:foo:src/main.ts',
name: 'foo',
label: 'Function',
filePath: 'src/main.ts',
content: 'function foo() { return 1; }',
};
const base = contentHashForNode(node);
expect(contentHashForNode(node, { modelId: DEFAULT_EMBEDDING_CONFIG.modelId })).toBe(base);
const custom = contentHashForNode(node, { modelId: 'Xenova/bge-base-en-v1.5' });
expect(custom).not.toBe(base);
expect(contentHashForNode(node, { modelId: 'Xenova/bge-small-en-v1.5' })).not.toBe(custom);
});
});