mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 01:12:20 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b05ebf6e4a |
+4
-1
@@ -935,7 +935,10 @@ export function formatResult(opName: string, result: unknown): string {
|
||||
lines.push(`Link coverage (entities): ${(h.link_coverage * 100).toFixed(1)}%`);
|
||||
}
|
||||
if (h.timeline_coverage !== undefined) {
|
||||
lines.push(`Timeline coverage (entities): ${(h.timeline_coverage * 100).toFixed(1)}%`);
|
||||
lines.push(`Timeline coverage (entity pages): ${(h.timeline_coverage * 100).toFixed(1)}%`);
|
||||
}
|
||||
if (h.timeline_coverage_score !== undefined) {
|
||||
lines.push(`Timeline density (all pages): ${h.timeline_coverage_score}/15 (whole-brain brain-score component)`);
|
||||
}
|
||||
if (Array.isArray(h.most_connected) && h.most_connected.length > 0) {
|
||||
lines.push('Most connected entities:');
|
||||
|
||||
@@ -5868,12 +5868,12 @@ export async function buildChecks(
|
||||
message: `Only code/test fixture entity pages found (${entityCount}); graph_coverage not applicable`,
|
||||
});
|
||||
} else if (linkCoverage >= 0.5 && timelineCoverage >= 0.5) {
|
||||
checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity link coverage ${linkPct}%, timeline ${timelinePct}%` });
|
||||
checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}%` });
|
||||
} else {
|
||||
checks.push({
|
||||
name: 'graph_coverage',
|
||||
status: 'warn',
|
||||
message: `Entity link coverage ${linkPct}%, timeline ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
|
||||
message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5885,7 +5885,7 @@ export async function buildChecks(
|
||||
const parts = [
|
||||
`embed ${health.embed_coverage_score}/35`,
|
||||
`links ${health.link_density_score}/25`,
|
||||
`timeline ${health.timeline_coverage_score}/15`,
|
||||
`timeline density (all pages) ${health.timeline_coverage_score}/15`,
|
||||
`orphans ${health.no_orphans_score}/15`,
|
||||
`dead-links ${health.no_dead_links_score}/10`,
|
||||
];
|
||||
|
||||
+1
-14
@@ -1,5 +1,5 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature, resolveEmbeddingModelLabel } from '../core/embedding.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
|
||||
import type { ChunkInput } from '../core/types.ts';
|
||||
import { chunkText } from '../core/chunkers/recursive.ts';
|
||||
import { createProgress, type ProgressReporter } from '../core/progress.ts';
|
||||
@@ -581,16 +581,11 @@ async function embedPage(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label each (re)embedded chunk with the model that actually
|
||||
// produced its vector. Preserved chunks (not re-embedded this pass) keep
|
||||
// their existing model so a mixed-model page isn't relabeled wholesale.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index),
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
|
||||
@@ -722,16 +717,12 @@ async function embedAll(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: stamp the resolved embedding model on (re)embedded chunks;
|
||||
// preserve the existing model on chunks left untouched.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
// Preserve ALL chunks, only update embeddings for stale ones
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index) ?? undefined,
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
|
||||
@@ -1021,15 +1012,11 @@ async function embedAllStale(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label the re-embedded (stale) chunks with the resolved
|
||||
// model; preserve the existing model on the non-stale chunks.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput } from './types.ts';
|
||||
import { embedBatchWithBackoff } from '../commands/embed.ts';
|
||||
import { resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
|
||||
import { AbortError } from './abort-check.ts';
|
||||
|
||||
@@ -201,17 +200,11 @@ export async function embedStaleForSource(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label re-embedded chunks with the model that produced the
|
||||
// vector; preserved chunks keep their existing model. Without this,
|
||||
// upsertChunks falls back to DEFAULT_EMBEDDING_MODEL for every chunk
|
||||
// (the same mislabel the embed.ts paths fixed).
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map((c) => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
// Carry through per-chunk metadata. upsertChunks writes these as
|
||||
// EXCLUDED.<col> (not COALESCE), so omitting them here resets image
|
||||
|
||||
@@ -113,21 +113,6 @@ export async function embedBatch(
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the embedding model label (`provider:model`) to stamp onto
|
||||
* `content_chunks.model`, so each chunk records the model that actually
|
||||
* produced its vector instead of the engine's hardcoded default (#1717).
|
||||
* Returns undefined if the gateway is unconfigured; callers then fall back
|
||||
* to the chunk's existing model rather than mislabeling it.
|
||||
*/
|
||||
export function resolveEmbeddingModelLabel(): string | undefined {
|
||||
try {
|
||||
return gatewayGetModel();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Currently-configured embedding model (short form without provider prefix). */
|
||||
export function getEmbeddingModelName(): string {
|
||||
return gatewayGetModel().split(':').slice(1).join(':') || 'text-embedding-3-large';
|
||||
|
||||
+1
-11
@@ -8,7 +8,7 @@ import { chunkText } from './chunkers/recursive.ts';
|
||||
import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';
|
||||
import { findChunkForOffset } from './chunkers/edge-extractor.ts';
|
||||
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature, resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
|
||||
import { slugifyPath, slugifyCodePath, isCodeFilePath } from './sync.ts';
|
||||
import type { ChunkInput, PageInput, PageType } from './types.ts';
|
||||
import { computeEffectiveDate } from './effective-date.ts';
|
||||
@@ -716,12 +716,8 @@ export async function importFromContent(
|
||||
? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))
|
||||
: chunks.map((c) => c.chunk_text);
|
||||
const embeddings = await embedBatch(wrappedTexts);
|
||||
// #1717: label each chunk with the model that actually produced its
|
||||
// vector, not the engine's hardcoded default.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
chunks[i].embedding = embeddings[i];
|
||||
if (embedModelLabel) chunks[i].model = embedModelLabel;
|
||||
// token_count tracks the wrapped string length so cost reporting
|
||||
// reflects what we actually sent to the embedder.
|
||||
chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);
|
||||
@@ -1145,10 +1141,7 @@ export async function importCodeFile(
|
||||
const matched = existingByKey.get(key);
|
||||
if (matched && matched.embedding) {
|
||||
// Reuse the existing embedding verbatim. No API call, no cost.
|
||||
// #1717: carry the existing model label along with the reused vector
|
||||
// so the upsert doesn't relabel it with the engine default.
|
||||
chunks[i]!.embedding = matched.embedding as Float32Array;
|
||||
chunks[i]!.model = matched.model ?? undefined;
|
||||
chunks[i]!.token_count = matched.token_count ?? undefined;
|
||||
} else {
|
||||
needsEmbedIndexes.push(i);
|
||||
@@ -1160,12 +1153,9 @@ export async function importCodeFile(
|
||||
try {
|
||||
const textsToEmbed = needsEmbedIndexes.map((i) => chunks[i]!.chunk_text);
|
||||
const embeddings = await embedBatch(textsToEmbed);
|
||||
// #1717: stamp the model that produced these vectors.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let j = 0; j < needsEmbedIndexes.length; j++) {
|
||||
const i = needsEmbedIndexes[j]!;
|
||||
chunks[i]!.embedding = embeddings[j]!;
|
||||
if (embedModelLabel) chunks[i]!.model = embedModelLabel;
|
||||
chunks[i]!.token_count = Math.ceil(chunks[i]!.chunk_text.length / 4);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Issue #2298 — timeline metric presentation contract.
|
||||
*
|
||||
* Authoritative upstream semantics (src/core/types.ts):
|
||||
* - Metric A `timeline_coverage` (entity-scoped, fraction 0–1):
|
||||
* eligible entity pages WITH a timeline entry / eligible entity pages
|
||||
* -> surfaced by `graph_coverage` check AND `get_health` CLI entity line.
|
||||
* - Metric B `timeline_coverage_score` (whole-brain, 0–15 brain-score component):
|
||||
* all pages WITH a timeline entry / all pages
|
||||
* -> surfaced by `brain_score` component breakdown AND (separately) CLI.
|
||||
*
|
||||
* The two have DIFFERENT numerators/denominators. This PR labels each
|
||||
* explicitly and keeps BOTH the entity CLI line and the whole-brain line.
|
||||
*
|
||||
* Tests (no private EriadorMu data, no production/home DB, no network):
|
||||
* - numeric denominator assertions (Metric A = 50%, Metric B = 4/15)
|
||||
* - doctor rendered-message assertions (exact labels, no ambiguous old label)
|
||||
* - CLI rendered-output assertions (exact lines, guard matrix)
|
||||
* - red/green: same assertions FAIL on origin/master, PASS on this branch
|
||||
*
|
||||
* Scoring formula UNCHANGED. Canonical PGLite fixture via resetPgliteState.
|
||||
*/
|
||||
|
||||
import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { buildChecks } from '../src/commands/doctor.ts';
|
||||
import { formatResult } from '../src/cli.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
async function seedFourPages(eng: PGLiteEngine): Promise<void> {
|
||||
const sql = sqlQueryForEngine(eng);
|
||||
// 2 eligible entity pages, 2 technical/non-entity pages.
|
||||
// Only ONE entity page has a timeline entry; only ONE total page does.
|
||||
await sql`
|
||||
INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
|
||||
VALUES
|
||||
('acme-example', 'default', 'company', 'Acme', '', '{}', 'h1', now(), now()),
|
||||
('alice-example', 'default', 'person', 'Alice', '', '{}', 'h2', now(), now()),
|
||||
('technical-a', 'default', 'note', 'Tech A', '', '{}', 'h3', now(), now()),
|
||||
('technical-b', 'default', 'note', 'Tech B', '', '{}', 'h4', now(), now())
|
||||
`;
|
||||
const companyId = (await sql`SELECT id FROM pages WHERE slug='acme-example'`)[0].id as number;
|
||||
await sql`INSERT INTO timeline_entries (page_id, date, source, summary, detail)
|
||||
VALUES (${companyId}, CURRENT_DATE, 'test', 'milestone', '{}')`;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetPgliteState(engine);
|
||||
});
|
||||
|
||||
describe('issue #2298 — numeric denominator semantics', () => {
|
||||
test('entity timeline coverage = 1/2 = 50% (2 eligible entities, 1 with timeline)', async () => {
|
||||
await seedFourPages(engine);
|
||||
const health = await engine.getHealth();
|
||||
expect(health.timeline_coverage).toBeDefined();
|
||||
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
|
||||
});
|
||||
|
||||
test('whole-brain timeline density = 1/4 -> score 4/15 (4 total pages, 1 with timeline)', async () => {
|
||||
await seedFourPages(engine);
|
||||
const health = await engine.getHealth();
|
||||
expect(health.timeline_coverage_score).toBeDefined();
|
||||
expect(health.timeline_coverage_score).toBe(4);
|
||||
});
|
||||
|
||||
test('the two metrics use independent denominators', async () => {
|
||||
await seedFourPages(engine);
|
||||
const health = await engine.getHealth();
|
||||
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
|
||||
expect(health.timeline_coverage_score ?? 0).toBe(4);
|
||||
// 50% (entity, /2) != 26.7% (whole-brain, /4). Provably distinct.
|
||||
expect(Math.round(((health.timeline_coverage_score ?? 0) / 15) * 100)).not.toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('issue #2298 — doctor rendered-message contract', () => {
|
||||
test('graph_coverage renders entity-scoped label with 50%', async () => {
|
||||
await seedFourPages(engine);
|
||||
const checks = await buildChecks(engine, [], null);
|
||||
const graph = checks.find((c) => c.name === 'graph_coverage');
|
||||
expect(graph, 'graph_coverage check must be present').toBeDefined();
|
||||
expect(graph!.message).toContain('entity timeline coverage 50%');
|
||||
// ambiguous old label must NOT be present
|
||||
expect(graph!.message).not.toMatch(/timeline 50%/);
|
||||
expect(graph!.message).not.toMatch(/timeline \(entity, brain score\)/);
|
||||
});
|
||||
|
||||
test('brain_score renders whole-brain density label 4/15', async () => {
|
||||
await seedFourPages(engine);
|
||||
const checks = await buildChecks(engine, [], null);
|
||||
const brain = checks.find((c) => c.name === 'brain_score');
|
||||
expect(brain, 'brain_score check must be present').toBeDefined();
|
||||
expect(brain!.message).toContain('timeline density (all pages) 4/15');
|
||||
// wrong labels must NOT be present
|
||||
expect(brain!.message).not.toMatch(/timeline 4\/15/);
|
||||
expect(brain!.message).not.toMatch(/timeline \(entity, brain score\)/);
|
||||
// brain-score component must NOT carry the word "entity" (it is whole-brain)
|
||||
const timelinePart = brain!.message.split('timeline density (all pages) 4/15')[0] + 'timeline density (all pages) 4/15';
|
||||
expect(timelinePart).not.toMatch(/entity/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('issue #2298 — CLI get_health rendered-output contract', () => {
|
||||
function fakeHealth(overrides: Record<string, unknown>): any {
|
||||
return {
|
||||
embed_coverage: 1, missing_embeddings: 0, stale_pages: 0, orphan_pages: 0,
|
||||
link_coverage: 1, timeline_coverage: 0.5, timeline_coverage_score: 4,
|
||||
most_connected: [], ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('both entity and whole-brain lines render, no undefined/15', () => {
|
||||
const out = formatResult('get_health', fakeHealth({}));
|
||||
expect(out).toContain('Timeline coverage (entity pages): 50.0%');
|
||||
expect(out).toContain('Timeline density (all pages): 4/15');
|
||||
expect(out).not.toContain('undefined/15');
|
||||
expect(out).not.toContain('Timeline coverage (entities)');
|
||||
expect(out).not.toMatch(/timeline \(entity, brain score\)/);
|
||||
expect(out).not.toMatch(/bare "timeline 4\/15"/);
|
||||
});
|
||||
|
||||
test('guard matrix: entity present, whole-brain absent -> only entity line', () => {
|
||||
const out = formatResult('get_health', fakeHealth({ timeline_coverage_score: undefined }));
|
||||
expect(out).toContain('Timeline coverage (entity pages): 50.0%');
|
||||
expect(out).not.toContain('Timeline density (all pages)');
|
||||
expect(out).not.toContain('undefined/15');
|
||||
});
|
||||
|
||||
test('guard matrix: whole-brain present, entity absent -> only whole-brain line', () => {
|
||||
const out = formatResult('get_health', fakeHealth({ timeline_coverage: undefined }));
|
||||
expect(out).toContain('Timeline density (all pages): 4/15');
|
||||
expect(out).not.toContain('Timeline coverage (entity pages)');
|
||||
expect(out).not.toContain('undefined/15');
|
||||
});
|
||||
|
||||
test('guard matrix: both absent -> neither timeline line, never undefined/15', () => {
|
||||
const out = formatResult('get_health', fakeHealth({ timeline_coverage: undefined, timeline_coverage_score: undefined }));
|
||||
expect(out).not.toContain('Timeline coverage (entity pages)');
|
||||
expect(out).not.toContain('Timeline density (all pages)');
|
||||
expect(out).not.toContain('undefined/15');
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,6 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { embedStaleForSource } from '../src/core/embed-stale.ts';
|
||||
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
|
||||
import type { ChunkInput } from '../src/core/types.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
@@ -277,49 +276,4 @@ describe('embedStaleForSource', () => {
|
||||
// The stale text row actually got its embedding.
|
||||
expect(txtRow.embedded_at).not.toBeNull();
|
||||
});
|
||||
|
||||
// #1717: the backfill path must label re-embedded chunks with the model
|
||||
// that produced the vector, and preserve the existing label on chunks it
|
||||
// did not touch (before the fix, both were reset to the engine default).
|
||||
test('labels re-embedded chunks with the gateway model, preserves untouched labels (#1717)', async () => {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
env: { OPENAI_API_KEY: 'sk-test-embed-stale-1717' },
|
||||
});
|
||||
try {
|
||||
await engine.putPage('notes/model-label', {
|
||||
type: 'note',
|
||||
title: 'model-label',
|
||||
compiled_truth: '# model-label\n\nseeded',
|
||||
});
|
||||
await engine.upsertChunks('notes/model-label', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'already embedded elsewhere',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(1536).fill(0.01),
|
||||
model: 'voyage:voyage-3',
|
||||
token_count: 4,
|
||||
},
|
||||
{
|
||||
chunk_index: 1,
|
||||
chunk_text: 'stale chunk needing embed',
|
||||
chunk_source: 'compiled_truth',
|
||||
token_count: 5,
|
||||
embedding: undefined, // stale
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await embedStaleForSource(engine, 'default', { embedFn: fakeEmbedFn });
|
||||
expect(result.embedded).toBe(1);
|
||||
|
||||
const after = await engine.getChunks('notes/model-label');
|
||||
const preserved = after.find((c) => c.chunk_index === 0)!;
|
||||
const reembedded = after.find((c) => c.chunk_index === 1)!;
|
||||
expect(reembedded.model).toBe('openai:text-embedding-3-large');
|
||||
expect(preserved.model).toBe('voyage:voyage-3');
|
||||
} finally {
|
||||
resetGateway();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,8 +37,6 @@ mock.module('../src/core/embedding.ts', () => ({
|
||||
// setPageEmbeddingSignature / invalidateStaleSignatureEmbeddings resolve to
|
||||
// null via the Proxy default, so the signature value is inert here.
|
||||
currentEmbeddingSignature: () => 'test:model:1536',
|
||||
// #1717: embed paths stamp this label on (re)embedded chunks.
|
||||
resolveEmbeddingModelLabel: () => 'openai:text-embedding-3-large',
|
||||
}));
|
||||
|
||||
// Import AFTER mocking.
|
||||
@@ -805,34 +803,3 @@ describe('embedAllStale --source threading (D7)', () => {
|
||||
expect((firstCallOpts as { sourceId?: string }).sourceId).toBe('media-corpus');
|
||||
});
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that actually produced
|
||||
// each vector, not the gateway/engine default.
|
||||
describe('content_chunks.model labeling (#1717)', () => {
|
||||
test('stamps the resolved embedding model on re-embedded chunks, preserves it on untouched chunks', async () => {
|
||||
let upserted: any[] | undefined;
|
||||
// Chunk 0 is stale (no embedded_at) → gets re-embedded this pass.
|
||||
// Chunk 1 is already embedded with a DIFFERENT model → must be preserved,
|
||||
// not relabeled to the current model.
|
||||
const chunks = [
|
||||
{ chunk_index: 0, chunk_text: 'a', chunk_source: 'compiled_truth', embedded_at: null, model: 'zeroentropyai:zembed-1', token_count: 1 },
|
||||
{ chunk_index: 1, chunk_text: 'b', chunk_source: 'compiled_truth', embedded_at: '2026-01-01', embedding: new Float32Array(1536), model: 'voyage:voyage-3', token_count: 1 },
|
||||
];
|
||||
const engine = mockEngine({
|
||||
getPage: async () => ({ slug: 'notes/x', compiled_truth: 'a', timeline: '', source_id: 'default' }),
|
||||
getChunks: async () => chunks,
|
||||
upsertChunks: async (_slug: string, c: any[]) => { upserted = c; },
|
||||
setPageEmbeddingSignature: async () => null,
|
||||
});
|
||||
|
||||
await runEmbedCore(engine, { slugs: ['notes/x'] });
|
||||
|
||||
expect(upserted).toBeDefined();
|
||||
const byIdx = Object.fromEntries(upserted!.map(c => [c.chunk_index, c]));
|
||||
// Re-embedded chunk carries the model that produced its vector (was
|
||||
// mislabeled with the default before the fix).
|
||||
expect(byIdx[0].model).toBe('openai:text-embedding-3-large');
|
||||
// Untouched chunk keeps its original model — no wholesale relabel.
|
||||
expect(byIdx[1].model).toBe('voyage:voyage-3');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,21 +73,4 @@ describe('importFromContent embedding_signature stamping (F1)', () => {
|
||||
await importFromContent(engine, 'concepts/unstamped', '# Unstamped\n\nbody content.', { noEmbed: true });
|
||||
expect(await signatureOf('concepts/unstamped')).toBeNull();
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that produced the
|
||||
// vector (the configured gateway model), not the engine's hardcoded
|
||||
// default. The gateway here is configured to openai:text-embedding-3-large,
|
||||
// which differs from DEFAULT_EMBEDDING_MODEL — so this fails without the
|
||||
// import-path model stamping.
|
||||
test('inline embed labels content_chunks.model with the configured model (#1717)', async () => {
|
||||
await importFromContent(engine, 'concepts/labeled', '# Labeled\n\nsome body content to chunk and embed.', {});
|
||||
const rows = await engine.executeRaw<{ model: string }>(
|
||||
`SELECT cc.model FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = $1 AND p.source_id = 'default'`,
|
||||
['concepts/labeled'],
|
||||
);
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const r of rows) expect(r.model).toBe('openai:text-embedding-3-large');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user