mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 17:32:37 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3487e4b255 | ||
|
|
159ddc3249 |
@@ -820,10 +820,6 @@ export async function doctorReportRemote(engine: BrainEngine): Promise<DoctorRep
|
||||
// v0.42.x (#1794, 4A): pool-budget nudge when GBRAIN_MAX_CONNECTIONS is set.
|
||||
checks.push(await checkPoolBudget(engine));
|
||||
|
||||
// #2552: warn when an explicit embed-concurrency override fans out against
|
||||
// a local single-slot embedding endpoint (silent backfill starvation).
|
||||
checks.push(await checkEmbedConcurrency());
|
||||
|
||||
// v0.42.7 (#1696): link-extraction lag. Strictly SQL (single indexed COUNT),
|
||||
// safe on the thin-client/remote path — remote operators on checkout-less
|
||||
// Postgres brains are exactly who can't otherwise see the extraction backlog.
|
||||
@@ -3819,61 +3815,6 @@ export function computePoolBudgetCheck(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* #2552: warn when an explicit GBRAIN_EMBED_CONCURRENCY override fans out
|
||||
* against a local single-slot embedding endpoint (Ollama / llama-server /
|
||||
* localhost base URL). Requests serialize on the one loaded model, so N
|
||||
* parallel pages multiply latency xN and can exceed the fetch timeout with
|
||||
* no surfaced error — the backfill silently starves. (When the env var is
|
||||
* unset, embed auto-caps at LOCAL_EMBED_CONCURRENCY_CAP and this check
|
||||
* reports ok.) Pure; exported for tests.
|
||||
*/
|
||||
export function computeEmbedConcurrencyCheck(
|
||||
isLocalEndpoint: boolean,
|
||||
envValue: string | undefined,
|
||||
localCap: number,
|
||||
): Check {
|
||||
const name = 'embed_concurrency';
|
||||
if (!isLocalEndpoint) {
|
||||
return { name, status: 'ok', message: 'Embedding endpoint is not a local inference server — cloud concurrency defaults apply.' };
|
||||
}
|
||||
const parsed = envValue ? parseInt(envValue, 10) : NaN;
|
||||
if (envValue && Number.isFinite(parsed) && parsed > localCap) {
|
||||
return {
|
||||
name,
|
||||
status: 'warn',
|
||||
message:
|
||||
`GBRAIN_EMBED_CONCURRENCY=${parsed} against a local embedding endpoint. ` +
|
||||
`Local inference servers serialize requests, so ${parsed} parallel pages multiply ` +
|
||||
`latency x${parsed} and can exceed the fetch timeout — the embed backfill stalls ` +
|
||||
`with no error. Unset GBRAIN_EMBED_CONCURRENCY (auto-caps at ${localCap}) or set it <= ${localCap}.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
name,
|
||||
status: 'ok',
|
||||
message: `Local embedding endpoint detected; embed concurrency capped at ${envValue ? parsed : localCap}.`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Thin gateway/env wrapper over `computeEmbedConcurrencyCheck`. */
|
||||
export async function checkEmbedConcurrency(): Promise<Check> {
|
||||
try {
|
||||
const { isLocalEmbeddingEndpoint, LOCAL_EMBED_CONCURRENCY_CAP } = await import('../core/ai/gateway.ts');
|
||||
return computeEmbedConcurrencyCheck(
|
||||
isLocalEmbeddingEndpoint(),
|
||||
process.env.GBRAIN_EMBED_CONCURRENCY,
|
||||
LOCAL_EMBED_CONCURRENCY_CAP,
|
||||
);
|
||||
} catch (err) {
|
||||
return {
|
||||
name: 'embed_concurrency',
|
||||
status: 'ok',
|
||||
message: `Skipped (${err instanceof Error ? err.message : String(err)})`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Thin env/engine wrapper over `computePoolBudgetCheck`. */
|
||||
export async function checkPoolBudget(_engine: BrainEngine): Promise<Check> {
|
||||
try {
|
||||
|
||||
+51
-43
@@ -1,7 +1,7 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
|
||||
import { isLocalEmbeddingEndpoint, LOCAL_EMBED_CONCURRENCY_CAP } from '../core/ai/gateway.ts';
|
||||
import type { ChunkInput } from '../core/types.ts';
|
||||
import type { ChunkInput, ResolvedColumn } from '../core/types.ts';
|
||||
import { resolveWriteColumnForEngine } from '../core/search/embedding-column.ts';
|
||||
import { chunkText } from '../core/chunkers/recursive.ts';
|
||||
import { createProgress, type ProgressReporter } from '../core/progress.ts';
|
||||
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
|
||||
@@ -177,31 +177,6 @@ export class EmbeddingDimMismatchError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #2552: resolve the bulk-embed worker count. Env override or the
|
||||
* cloud-tuned default of 20 — but when the operator did NOT set
|
||||
* GBRAIN_EMBED_CONCURRENCY and the embedding endpoint is a local inference
|
||||
* server (Ollama / llama-server / localhost base URL), cap at
|
||||
* LOCAL_EMBED_CONCURRENCY_CAP: 20 parallel pages against a single-slot
|
||||
* server serialize on the one loaded model, multiply latency x20 past the
|
||||
* fetch timeout, and starve the backfill with no surfaced error. An
|
||||
* explicit env value always wins (`gbrain doctor` warns instead).
|
||||
* Pacing only ever LOWERS concurrency (Codex P2).
|
||||
*/
|
||||
export function resolveEmbedConcurrency(paceMaxConcurrency?: number): number {
|
||||
const envSet = !!process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
const base = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);
|
||||
let resolved = base;
|
||||
if (!envSet && isLocalEmbeddingEndpoint() && base > LOCAL_EMBED_CONCURRENCY_CAP) {
|
||||
resolved = LOCAL_EMBED_CONCURRENCY_CAP;
|
||||
serr(
|
||||
`[embed] local embedding endpoint detected — capping concurrency at ` +
|
||||
`${LOCAL_EMBED_CONCURRENCY_CAP} (set GBRAIN_EMBED_CONCURRENCY to override)`,
|
||||
);
|
||||
}
|
||||
return paceMaxConcurrency ? Math.min(resolved, paceMaxConcurrency) : resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-flight check: read the actual schema column dim and compare to the
|
||||
* gateway's resolved dim. Throws `EmbeddingDimMismatchError` on mismatch
|
||||
@@ -209,8 +184,13 @@ export function resolveEmbedConcurrency(paceMaxConcurrency?: number): number {
|
||||
* fresh-install bug class at the very first invocation instead of letting
|
||||
* the worker pool hammer N pages with raw 22000 errors.
|
||||
*/
|
||||
async function preflightDimMismatch(engine: BrainEngine, dryRun: boolean): Promise<void> {
|
||||
async function preflightDimMismatch(engine: BrainEngine, dryRun: boolean, embeddingColumn?: ResolvedColumn): Promise<void> {
|
||||
if (dryRun) return; // dry-run never embeds, no risk
|
||||
// #1262: an alt-column brain writes to `embeddingColumn`, not the legacy
|
||||
// `embedding` column — the legacy column's dims are irrelevant, and the
|
||||
// registry entry (validated at resolve time) pins the target's dims. Only
|
||||
// the legacy default path needs the schema-vs-gateway dim comparison.
|
||||
if (embeddingColumn && embeddingColumn.name !== 'embedding') return;
|
||||
const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
|
||||
const { getEmbeddingDimensions, getEmbeddingModel } = await import('../core/ai/gateway.ts');
|
||||
let existing;
|
||||
@@ -264,7 +244,12 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
|
||||
// v0.37.11.0 (Lane D.2): pre-flight dim-mismatch check. Catches the headline
|
||||
// fresh-install bug class before the worker pool spends 20 parallel calls
|
||||
// hitting raw Postgres dimension errors.
|
||||
await preflightDimMismatch(engine, !!opts.dryRun);
|
||||
// #1262: resolve the write-side embedding column ONCE at the boundary
|
||||
// (merged config + gateway model) and thread the descriptor through every
|
||||
// upsertChunks / stale-scan below. undefined => legacy `embedding` column.
|
||||
const embeddingColumn = await resolveWriteColumnForEngine(engine);
|
||||
|
||||
await preflightDimMismatch(engine, !!opts.dryRun, embeddingColumn);
|
||||
|
||||
const result: EmbedResult = {
|
||||
embedded: 0,
|
||||
@@ -279,7 +264,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
|
||||
for (const s of opts.slugs) {
|
||||
if (isAborted(opts.signal)) break; // #1737: stop the per-slug loop on abort
|
||||
try {
|
||||
await embedPage(engine, s, !!opts.dryRun, result, opts.sourceId, opts.signal);
|
||||
await embedPage(engine, s, !!opts.dryRun, result, opts.sourceId, opts.signal, embeddingColumn);
|
||||
} catch (e: unknown) {
|
||||
serr(` Error embedding ${s}: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
@@ -373,7 +358,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
|
||||
catchUp: opts.catchUp,
|
||||
pacer,
|
||||
paceMaxConcurrency,
|
||||
}, opts.signal);
|
||||
}, opts.signal, embeddingColumn);
|
||||
} finally {
|
||||
// E1: surface pacing telemetry (human + structured) when pacing was on.
|
||||
const snap = pacer.snapshot();
|
||||
@@ -402,7 +387,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
|
||||
return result;
|
||||
}
|
||||
if (opts.slug) {
|
||||
await embedPage(engine, opts.slug, !!opts.dryRun, result, opts.sourceId, opts.signal);
|
||||
await embedPage(engine, opts.slug, !!opts.dryRun, result, opts.sourceId, opts.signal, embeddingColumn);
|
||||
return result;
|
||||
}
|
||||
throw new Error('No embed target specified. Pass { slug }, { slugs }, { all }, or { stale }.');
|
||||
@@ -547,8 +532,13 @@ async function embedPage(
|
||||
result: EmbedResult,
|
||||
sourceId?: string,
|
||||
signal?: AbortSignal,
|
||||
embeddingColumn?: ResolvedColumn,
|
||||
) {
|
||||
const opts = sourceId ? { sourceId } : undefined;
|
||||
// #1262: write-side descriptor rides only on WRITE calls (upsertChunks).
|
||||
const chunkOpts = (sourceId || embeddingColumn)
|
||||
? { ...(sourceId && { sourceId }), ...(embeddingColumn && { embeddingColumn }) }
|
||||
: undefined;
|
||||
const page = await engine.getPage(slug, opts);
|
||||
if (!page) {
|
||||
throw new Error(`Page not found: ${slug}`);
|
||||
@@ -580,7 +570,7 @@ async function embedPage(
|
||||
}
|
||||
|
||||
if (inputs.length > 0) {
|
||||
await engine.upsertChunks(slug, inputs, opts);
|
||||
await engine.upsertChunks(slug, inputs, chunkOpts);
|
||||
chunks = await engine.getChunks(slug, opts);
|
||||
}
|
||||
}
|
||||
@@ -615,7 +605,7 @@ async function embedPage(
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
|
||||
await engine.upsertChunks(slug, updated, opts);
|
||||
await engine.upsertChunks(slug, updated, chunkOpts);
|
||||
// v0.41.31: stamp provenance so a later model/dims swap is detectable as
|
||||
// stale. embedPage is the per-slug path used by `gbrain embed <slug>` AND
|
||||
// by `gbrain sync`'s post-import embed step (runEmbedCore({slugs})).
|
||||
@@ -648,6 +638,7 @@ async function embedAll(
|
||||
paceMaxConcurrency?: number;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
embeddingColumn?: ResolvedColumn,
|
||||
) {
|
||||
// v0.41.31: current embedding provenance signature. Stamped onto pages
|
||||
// when their chunks are (re)embedded so a later model/dimension swap is
|
||||
@@ -670,7 +661,7 @@ async function embedAll(
|
||||
// D7: thread sourceId so `gbrain embed --stale --source X` actually scopes.
|
||||
// v0.41.18.0 (A13): thread batchSize/priority/catchUp into the stale path.
|
||||
// #1737: thread the external abort signal so the cycle embed phase bails.
|
||||
return await embedAllStale(engine, sourceId, dryRun, result, onProgress, staleOpts, signature, signal);
|
||||
return await embedAllStale(engine, sourceId, dryRun, result, onProgress, staleOpts, signature, signal, embeddingColumn);
|
||||
}
|
||||
|
||||
// --all path: pacer (no-op when off). E-1: lower the worker count to the
|
||||
@@ -703,8 +694,10 @@ async function embedAll(
|
||||
// Paced runs lower this to the resolved cap (the real lever vs pooler-slot
|
||||
// starvation); unpaced keeps the env/default 20. Codex P2: only ever LOWER —
|
||||
// never raise above an operator's existing env cap.
|
||||
// #2552: local endpoints auto-cap — see resolveEmbedConcurrency.
|
||||
const CONCURRENCY = resolveEmbedConcurrency(staleOpts?.paceMaxConcurrency);
|
||||
const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);
|
||||
const CONCURRENCY = staleOpts?.paceMaxConcurrency
|
||||
? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)
|
||||
: BASE_CONCURRENCY;
|
||||
|
||||
async function embedOnePage(page: typeof pages[number]) {
|
||||
// #1737: bail before doing any work for this page if the run was aborted.
|
||||
@@ -749,7 +742,10 @@ async function embedAll(
|
||||
embedding: embeddingMap.get(c.chunk_index) ?? undefined,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, {
|
||||
...(pageSourceId && { sourceId: pageSourceId }),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}));
|
||||
// v0.41.31: stamp embedding provenance so a later model swap is
|
||||
// detectable as stale.
|
||||
await observed(pacer, () =>
|
||||
@@ -829,10 +825,16 @@ async function embedAllStale(
|
||||
},
|
||||
signature?: string,
|
||||
externalSignal?: AbortSignal,
|
||||
embeddingColumn?: ResolvedColumn,
|
||||
) {
|
||||
// D7: thread sourceId so source-scoped runs only count + visit
|
||||
// that source's NULL embeddings.
|
||||
const sourceOpt = sourceId ? { sourceId } : undefined;
|
||||
// #1262: the stale predicate follows the write-side column — without it an
|
||||
// alt-column brain would perpetually re-select (and re-pay for) chunks whose
|
||||
// target column is already populated.
|
||||
const sourceOpt = (sourceId || embeddingColumn)
|
||||
? { ...(sourceId && { sourceId }), ...(embeddingColumn && { embeddingColumn }) }
|
||||
: undefined;
|
||||
|
||||
// v0.41.31: re-embed pages whose embedding_signature drifted (model/dims
|
||||
// swap). dry-run must NOT mutate, so it counts signature-stale via the
|
||||
@@ -879,8 +881,10 @@ async function embedAllStale(
|
||||
// Paced runs lower concurrency to the resolved cap (E-1: worker count IS the
|
||||
// lever on this single pool, no separate permit). Codex P2: pacing only ever
|
||||
// LOWERS concurrency — never raise above an operator's existing env cap.
|
||||
// #2552: local endpoints auto-cap — see resolveEmbedConcurrency.
|
||||
const CONCURRENCY = resolveEmbedConcurrency(staleOpts?.paceMaxConcurrency);
|
||||
const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);
|
||||
const CONCURRENCY = staleOpts?.paceMaxConcurrency
|
||||
? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)
|
||||
: BASE_CONCURRENCY;
|
||||
const pacer = staleOpts?.pacer ?? createNoopPacer();
|
||||
|
||||
// D3 + D3a + D8: wall-clock budget. 30 min default; env override.
|
||||
@@ -989,6 +993,7 @@ async function embedAllStale(
|
||||
afterUpdatedAt,
|
||||
}),
|
||||
...(sourceId && { sourceId }),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}),
|
||||
);
|
||||
if (batch.length === 0) {
|
||||
@@ -1041,7 +1046,10 @@ async function embedAllStale(
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, {
|
||||
sourceId: keySourceId,
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}));
|
||||
// v0.41.31: stamp provenance after the page's chunks are embedded —
|
||||
// but only when EVERY chunk was stale (fully re-embedded this pass).
|
||||
// A partially-stale page keeps preserved chunks of unknown/old
|
||||
@@ -1112,7 +1120,7 @@ async function embedAllStale(
|
||||
// as a clean run — re-running won't help until the underlying failure is fixed.
|
||||
if (staleOpts?.catchUp && !effectiveSignal.aborted && embedFailures > 0) {
|
||||
const remaining = await engine.countStaleChunks(
|
||||
signature ? { signature, ...(sourceId ? { sourceId } : {}) } : (sourceId ? { sourceId } : undefined),
|
||||
signature ? { signature, ...sourceOpt } : sourceOpt,
|
||||
);
|
||||
if (remaining > 0) {
|
||||
serr(`\n [embed] catch-up finished but ${remaining} chunk(s) remain stale after ${embedFailures} embed failure(s). These are not embeddable as-is; re-running won't clear them until the underlying error is resolved.`);
|
||||
|
||||
@@ -576,9 +576,16 @@ async function runInlineCostGate(
|
||||
|
||||
// Stale backlog: cheap single SQL; fail-open to 0 so a transient DB hiccup
|
||||
// never blocks the sync. Signature-aware (model/dims swap surfaces here).
|
||||
// #1262: follow the write-side embedding column — otherwise an alt-column
|
||||
// brain's fully-embedded corpus counts as phantom backlog on every gate.
|
||||
let staleChars = 0;
|
||||
try {
|
||||
staleChars = await engine.sumStaleChunkChars({ signature: currentEmbeddingSignature() });
|
||||
const { resolveWriteColumnForEngine } = await import('../core/search/embedding-column.ts');
|
||||
const embeddingColumn = await resolveWriteColumnForEngine(engine);
|
||||
staleChars = await engine.sumStaleChunkChars({
|
||||
signature: currentEmbeddingSignature(),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
});
|
||||
} catch {
|
||||
staleChars = 0;
|
||||
}
|
||||
|
||||
@@ -683,33 +683,6 @@ export function getEmbeddingDimensions(): number {
|
||||
return requireConfig().embedding_dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;
|
||||
}
|
||||
|
||||
/**
|
||||
* #2552: cap for parallel bulk-embed workers against a local inference
|
||||
* server. A single-slot Ollama/llama-server serializes requests, so the
|
||||
* cloud-tuned 20-worker fan-out multiplies latency x20 and blows past the
|
||||
* fetch timeout with no surfaced error (the backfill silently starves).
|
||||
*/
|
||||
export const LOCAL_EMBED_CONCURRENCY_CAP = 2;
|
||||
|
||||
/**
|
||||
* #2552: true when the configured embedding model routes to a local
|
||||
* inference server — the `ollama` / `llama-server` recipes, or any recipe
|
||||
* whose base URL was explicitly pointed at localhost. Bulk callers use this
|
||||
* to pick CPU-safe concurrency defaults; `gbrain doctor` uses it to warn
|
||||
* about an explicit cloud-sized override. Fail-open: unconfigured or
|
||||
* unresolvable gateway → false (cloud behavior, the historical default).
|
||||
*/
|
||||
export function isLocalEmbeddingEndpoint(): boolean {
|
||||
try {
|
||||
const { recipe } = resolveRecipe(getEmbeddingModel());
|
||||
if (recipe.id === 'ollama' || recipe.id === 'llama-server') return true;
|
||||
const base = requireConfig().base_urls?.[recipe.id] ?? '';
|
||||
return /\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(base);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.28.11: returns the configured multimodal embedding model when set,
|
||||
* or undefined if the brain falls back to `embedding_model` for multimodal
|
||||
|
||||
@@ -29,17 +29,9 @@ export const ollama: Recipe = {
|
||||
trust_custom_dims: true, // #2271: local models carry varied native dims
|
||||
cost_per_1m_tokens_usd: 0,
|
||||
price_last_verified: '2026-04-20',
|
||||
// #2552: Ollama's true batch capacity depends on the locally loaded
|
||||
// model + OLLAMA_NUM_PARALLEL, but the previous `no_batch_cap: true`
|
||||
// meant a whole page went out in ONE request — on a CPU-only box that
|
||||
// multiplies latency past the fetch timeout and the backfill starves
|
||||
// with no surfaced error. Ollama doesn't return a recognizable
|
||||
// token-limit error either, so the recursive-halving safety net never
|
||||
// fires; a conservative static pre-split cap is the only guard.
|
||||
// 4096 tokens x 2 chars/token ~= 8K chars per request (code-dense
|
||||
// pages run ~2 chars/token, not the tiktoken-ish 4).
|
||||
max_batch_tokens: 4096,
|
||||
chars_per_token: 2,
|
||||
// Ollama's batch capacity depends on the locally loaded model + the
|
||||
// OLLAMA_NUM_PARALLEL config; no static cap to declare. v0.32 (#779).
|
||||
no_batch_cap: true,
|
||||
},
|
||||
},
|
||||
setup_hint: 'Install Ollama from https://ollama.ai, then `ollama pull nomic-embed-text` and `ollama serve`.',
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
type SynopsisFailureKind,
|
||||
} from './audit-synopsis.ts';
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import { resolveWriteColumnForEngine } from './search/embedding-column.ts';
|
||||
import type { ChunkInput, CRMode, Page } from './types.ts';
|
||||
import type { SourceRow } from './sources-ops.ts';
|
||||
|
||||
@@ -286,9 +287,13 @@ export async function reembedPageWithContextualRetrieval(
|
||||
|
||||
// ── PHASE 2: single DB transaction ───────────────────────────
|
||||
try {
|
||||
// #1262: contextual re-embeds write TEXT embeddings — thread the
|
||||
// caller-resolved write column like every other embed path.
|
||||
const embeddingColumn = await resolveWriteColumnForEngine(args.engine);
|
||||
await args.engine.transaction(async (tx) => {
|
||||
await tx.upsertChunks(args.pageSlug, phase1.embeddedChunks, {
|
||||
sourceId: args.sourceId,
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
});
|
||||
await tx.updatePageContextualRetrievalState(
|
||||
args.pageSlug,
|
||||
|
||||
@@ -141,7 +141,6 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
|
||||
'pgbouncer_prepare',
|
||||
'pgvector',
|
||||
'pool_budget',
|
||||
'embed_concurrency',
|
||||
'progressive_batch_audit_health',
|
||||
'queue_health',
|
||||
'reranker_health',
|
||||
|
||||
+13
-2
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput } from './types.ts';
|
||||
import type { ChunkInput, ResolvedColumn } from './types.ts';
|
||||
import { embedBatchWithBackoff } from '../commands/embed.ts';
|
||||
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
|
||||
import { AbortError } from './abort-check.ts';
|
||||
@@ -61,6 +61,13 @@ export interface EmbedStaleOpts {
|
||||
* Omit to keep the legacy `embedding IS NULL`-only behavior.
|
||||
*/
|
||||
embeddingSignature?: string;
|
||||
/**
|
||||
* #1262: caller-resolved write-side embedding column. Threaded into BOTH
|
||||
* listStaleChunks (staleness predicate) and upsertChunks (write target) so
|
||||
* an alt-column brain converges instead of re-selecting embedded rows.
|
||||
* Resolve at the boundary via `resolveWriteColumnForEngine()`.
|
||||
*/
|
||||
embeddingColumn?: ResolvedColumn;
|
||||
/**
|
||||
* DB-contention pacer (paced-backfill). When enabled it (a) supplies the
|
||||
* worker count via the caller passing `concurrency = bundle.maxConcurrency`
|
||||
@@ -156,6 +163,7 @@ export async function embedStaleForSource(
|
||||
afterPageId,
|
||||
afterChunkIndex,
|
||||
sourceId,
|
||||
...(opts.embeddingColumn && { embeddingColumn: opts.embeddingColumn }),
|
||||
}),
|
||||
);
|
||||
if (batch.length === 0) {
|
||||
@@ -223,7 +231,10 @@ export async function embedStaleForSource(
|
||||
doc_comment: c.doc_comment ?? undefined,
|
||||
symbol_name_qualified: c.symbol_name_qualified ?? undefined,
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, {
|
||||
sourceId: keySourceId,
|
||||
...(opts.embeddingColumn && { embeddingColumn: opts.embeddingColumn }),
|
||||
}));
|
||||
// v0.41.31: stamp provenance only when EVERY chunk was stale (fully
|
||||
// re-embedded this pass) — a partially-stale page keeps preserved
|
||||
// chunks of unknown provenance, so don't claim current. After the
|
||||
|
||||
+22
-3
@@ -12,6 +12,7 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
CodeEdgeInput, CodeEdgeResult,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
@@ -987,8 +988,13 @@ export interface BrainEngine {
|
||||
* — Postgres rolls back automatically on conn drop, so commit-ambiguous
|
||||
* failure replays to the same end state. Callers MUST NOT wrap externally;
|
||||
* see {@link BatchOpts} retry-contract block.
|
||||
*
|
||||
* `opts.embeddingColumn` (optional) selects the content_chunks column that
|
||||
* receives TEXT embeddings (#1262). The caller resolves the descriptor at
|
||||
* the import/embed boundary via `resolveWriteColumn()`; engines never read
|
||||
* config or choose columns themselves. Omitted => legacy `embedding`.
|
||||
*/
|
||||
upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & BatchOpts): Promise<void>;
|
||||
upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void>;
|
||||
/**
|
||||
* Read every chunk for a page. `opts.sourceId` source-scopes the page
|
||||
* lookup; without it, multi-source brains return chunks from every
|
||||
@@ -1005,8 +1011,13 @@ export interface BrainEngine {
|
||||
* counts across every source in the brain. Operators running
|
||||
* `gbrain embed --stale --source media-corpus` expect only that
|
||||
* source's NULLs touched; the caller threads `sourceId` here.
|
||||
*
|
||||
* `opts.embeddingColumn` switches the staleness predicate from the legacy
|
||||
* `embedding` column to the resolved write-side column, so alt-column
|
||||
* brains do not perpetually re-select rows whose target column is already
|
||||
* populated (#1262). Must match the eventual upsertChunks target.
|
||||
*/
|
||||
countStaleChunks(opts?: { sourceId?: string; signature?: string }): Promise<number>;
|
||||
countStaleChunks(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number>;
|
||||
/**
|
||||
* Sum of LENGTH(chunk_text) over stale chunks — the character-count
|
||||
* backlog the embed phase / embed-backfill will process. Sibling of
|
||||
@@ -1020,8 +1031,13 @@ export interface BrainEngine {
|
||||
* model signature (a model/dims swap). NULL signature is GRANDFATHERED
|
||||
* (never counted) so the post-migration corpus isn't flagged en masse.
|
||||
* Omit `signature` for the legacy `embedding IS NULL`-only count.
|
||||
*
|
||||
* `opts.embeddingColumn` switches the staleness predicate to the resolved
|
||||
* write-side column (#1262) — same contract as countStaleChunks — so the
|
||||
* sync cost gate doesn't count an alt-column brain's fully-embedded corpus
|
||||
* as phantom backlog.
|
||||
*/
|
||||
sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): Promise<number>;
|
||||
sumStaleChunkChars(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number>;
|
||||
/**
|
||||
* Stamp `pages.embedding_signature = signature` for one page. Called after
|
||||
* a page's chunks are (re)embedded so a later model swap can detect it as
|
||||
@@ -1069,6 +1085,9 @@ export interface BrainEngine {
|
||||
// both round-trip TIMESTAMPTZ as Date | string; ISO string is the
|
||||
// common denominator on the wire).
|
||||
afterUpdatedAt?: string | null;
|
||||
// #1262: staleness predicate targets this column when set (must match
|
||||
// countStaleChunks and the eventual upsertChunks write target).
|
||||
embeddingColumn?: ResolvedColumn;
|
||||
}): Promise<StaleChunkRow[]>;
|
||||
/**
|
||||
* Delete every chunk for a page. Internal page-id lookup is sourceId-scoped
|
||||
|
||||
+25
-4
@@ -10,7 +10,8 @@ import { findChunkForOffset } from './chunkers/edge-extractor.ts';
|
||||
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
|
||||
import { slugifyPath, slugifyCodePath, isCodeFilePath } from './sync.ts';
|
||||
import type { ChunkInput, PageInput, PageType } from './types.ts';
|
||||
import type { ChunkInput, PageInput, PageType, ResolvedColumn } from './types.ts';
|
||||
import { resolveWriteColumnForEngine } from './search/embedding-column.ts';
|
||||
import { computeEffectiveDate } from './effective-date.ts';
|
||||
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
|
||||
import { logSlugFallback } from './audit-slug-fallback.ts';
|
||||
@@ -740,6 +741,14 @@ export async function importFromContent(
|
||||
// schema DEFAULT — required for multi-source brains; harmless ('default')
|
||||
// for single-source callers.
|
||||
const txOpts = sourceId ? { sourceId } : undefined;
|
||||
// #1262: resolve the write-side embedding column once (merged config +
|
||||
// gateway model) BEFORE the transaction; the descriptor rides only on
|
||||
// upsertChunks so text embeddings land in the registered column.
|
||||
const chunkWriteColumn = await resolveWriteColumnForEngine(engine);
|
||||
const chunkOpts: { sourceId?: string; embeddingColumn?: ResolvedColumn } | undefined =
|
||||
(sourceId || chunkWriteColumn)
|
||||
? { ...(sourceId && { sourceId }), ...(chunkWriteColumn && { embeddingColumn: chunkWriteColumn }) }
|
||||
: undefined;
|
||||
await engine.transaction(async (tx) => {
|
||||
if (existing) await tx.createVersion(slug, txOpts);
|
||||
|
||||
@@ -824,7 +833,7 @@ export async function importFromContent(
|
||||
}
|
||||
|
||||
if (chunks.length > 0) {
|
||||
await tx.upsertChunks(slug, chunks, txOpts);
|
||||
await tx.upsertChunks(slug, chunks, chunkOpts);
|
||||
// v0.41.31: stamp embedding provenance when this import actually
|
||||
// embedded (not --no-embed), so a later model/dims swap is detectable
|
||||
// as stale via embed --stale. The deferred/backfill + per-slug embed
|
||||
@@ -1064,6 +1073,12 @@ export async function importCodeFile(
|
||||
const title = `${relativePath} (${lang})`;
|
||||
const sourceId = opts.sourceId;
|
||||
const txOpts = sourceId ? { sourceId } : undefined;
|
||||
// #1262: write-side embedding column descriptor (rides only on upsertChunks).
|
||||
const chunkWriteColumn = await resolveWriteColumnForEngine(engine);
|
||||
const chunkOpts: { sourceId?: string; embeddingColumn?: ResolvedColumn } | undefined =
|
||||
(sourceId || chunkWriteColumn)
|
||||
? { ...(sourceId && { sourceId }), ...(chunkWriteColumn && { embeddingColumn: chunkWriteColumn }) }
|
||||
: undefined;
|
||||
|
||||
const byteLength = Buffer.byteLength(content, 'utf-8');
|
||||
if (byteLength > MAX_FILE_SIZE) {
|
||||
@@ -1183,7 +1198,7 @@ export async function importCodeFile(
|
||||
await tx.addTag(slug, lang, txOpts);
|
||||
|
||||
if (chunks.length > 0) {
|
||||
await tx.upsertChunks(slug, chunks, txOpts);
|
||||
await tx.upsertChunks(slug, chunks, chunkOpts);
|
||||
// v0.41.31: stamp embedding provenance ONLY when every chunk was
|
||||
// freshly embedded with the current model this call (no reuse-by-hash
|
||||
// carrying old-model vectors). Mixed pages stay unstamped rather than
|
||||
@@ -1332,6 +1347,12 @@ export async function withImportTransaction(
|
||||
): Promise<void> {
|
||||
const sourceId = spec.sourceId ?? 'default';
|
||||
const txOpts = spec.sourceId ? { sourceId: spec.sourceId } : undefined;
|
||||
// #1262: write-side embedding column descriptor (rides only on upsertChunks).
|
||||
const chunkWriteColumn = await resolveWriteColumnForEngine(engine);
|
||||
const chunkOpts: { sourceId?: string; embeddingColumn?: ResolvedColumn } | undefined =
|
||||
(spec.sourceId || chunkWriteColumn)
|
||||
? { ...(spec.sourceId && { sourceId: spec.sourceId }), ...(chunkWriteColumn && { embeddingColumn: chunkWriteColumn }) }
|
||||
: undefined;
|
||||
await engine.transaction(async (tx) => {
|
||||
if (spec.hadExisting) await tx.createVersion(spec.slug, txOpts);
|
||||
await tx.putPage(spec.slug, spec.page, txOpts);
|
||||
@@ -1347,7 +1368,7 @@ export async function withImportTransaction(
|
||||
}
|
||||
if (spec.chunks !== undefined) {
|
||||
if (spec.chunks.length > 0) {
|
||||
await tx.upsertChunks(spec.slug, spec.chunks, txOpts);
|
||||
await tx.upsertChunks(spec.slug, spec.chunks, chunkOpts);
|
||||
} else {
|
||||
await tx.deleteChunks(spec.slug, txOpts);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ import { tryAcquireDbLock } from '../../db-lock.ts';
|
||||
import { BudgetTracker, BudgetExhausted } from '../../budget/budget-tracker.ts';
|
||||
import { withBudgetTracker } from '../../ai/gateway.ts';
|
||||
import { embedStaleForSource } from '../../embed-stale.ts';
|
||||
import { resolveWriteColumnForEngine } from '../../search/embedding-column.ts';
|
||||
import { currentEmbeddingSignature } from '../../embedding.ts';
|
||||
import { type DbPacer, createDbPacer, createNoopPacer } from '../../db-pacer.ts';
|
||||
import { resolvePaceMode, loadPaceModeConfig, readPaceEnv } from '../../pace-mode.ts';
|
||||
@@ -164,12 +165,16 @@ export function makeEmbedBackfillHandler(engine: BrainEngine) {
|
||||
// the supervisor, so pacing it is the headline win.
|
||||
const { pacer, concurrency } = await resolveBackfillPacer(engine, job.data);
|
||||
|
||||
// #1262: resolve the write-side embedding column once at the job boundary.
|
||||
const embeddingColumn = await resolveWriteColumnForEngine(engine);
|
||||
|
||||
try {
|
||||
const result = await withBudgetTracker(tracker, async () =>
|
||||
embedStaleForSource(engine, sourceId, {
|
||||
batchSize,
|
||||
signal: job.signal,
|
||||
pacer,
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
...(concurrency !== undefined && { concurrency }),
|
||||
// v0.41.31: re-embed pages whose model signature drifted + stamp
|
||||
// provenance as chunks land.
|
||||
|
||||
+49
-38
@@ -40,6 +40,7 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -56,7 +57,7 @@ import { GBrainError, PAGE_SORT_SQL, ENRICH_ORDER_SQL } from './types.ts';
|
||||
import { finalizeLastSeen } from './chronicle/last-seen.ts';
|
||||
import { computeAnomaliesFromBuckets } from './cycle/anomaly.ts';
|
||||
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, buildWebsearchQueryExpr } from './search/sql-ranking.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
|
||||
import {
|
||||
normalizeEngineColumn,
|
||||
buildVectorCastFragment,
|
||||
@@ -1591,8 +1592,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query, innerLimit, limit, offset];
|
||||
let extraFilter = '';
|
||||
if (opts?.language) {
|
||||
@@ -1632,7 +1631,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
const keywordSql =
|
||||
`WITH ranked AS (
|
||||
@@ -1640,14 +1638,14 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.slug, p.id as page_id, p.title, p.type, p.source_id,
|
||||
p.effective_date, p.effective_date_source,
|
||||
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
|
||||
ts_rank(cc.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score,
|
||||
ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
|
||||
CASE WHEN p.updated_at < (
|
||||
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
|
||||
) THEN true ELSE false END AS stale
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
JOIN sources s ON s.id = p.source_id
|
||||
WHERE cc.search_vector @@ ${ftsQueryExpr} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
|
||||
WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', $1) ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
|
||||
-- v0.27.1: hide image rows from default text-keyword search so
|
||||
-- OCR text doesn't drown text-page hits. Image-similarity queries
|
||||
-- run a separate vector path on embedding_image.
|
||||
@@ -1715,10 +1713,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query, limit, offset];
|
||||
let extraFilter = '';
|
||||
if (opts?.type) {
|
||||
@@ -1766,7 +1761,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
COALESCE(rep.chunk_index, 0) as chunk_index,
|
||||
COALESCE(rep.chunk_text, '') as chunk_text,
|
||||
COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,
|
||||
ts_rank_cd(p.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score,
|
||||
ts_rank_cd(p.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
|
||||
CASE WHEN p.updated_at < (
|
||||
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
|
||||
) THEN true ELSE false END AS stale
|
||||
@@ -1781,7 +1776,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
|
||||
LIMIT 1
|
||||
) rep ON true
|
||||
WHERE p.search_vector @@ ${ftsQueryExpr}
|
||||
WHERE p.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)
|
||||
${extraFilter} ${hardExcludeClause} ${visibilityClause}
|
||||
ORDER BY score DESC, p.id ASC
|
||||
LIMIT $2 OFFSET $3`;
|
||||
@@ -1968,8 +1963,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query, limit, offset];
|
||||
let extraFilter = '';
|
||||
if (opts?.language) {
|
||||
@@ -2004,21 +1997,20 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT
|
||||
p.slug, p.id as page_id, p.title, p.type, p.source_id,
|
||||
p.effective_date, p.effective_date_source,
|
||||
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
|
||||
ts_rank(cc.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score,
|
||||
ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
|
||||
CASE WHEN p.updated_at < (
|
||||
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
|
||||
) THEN true ELSE false END AS stale
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
JOIN sources s ON s.id = p.source_id
|
||||
WHERE cc.search_vector @@ ${ftsQueryExpr} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
|
||||
WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', $1) ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
|
||||
ORDER BY score DESC
|
||||
LIMIT $2 OFFSET $3`,
|
||||
params
|
||||
@@ -2239,12 +2231,20 @@ export class PGLiteEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Chunks
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & BatchOpts): Promise<void> {
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {
|
||||
return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal, () => this._upsertChunksOnce(slug, chunks, opts), chunks.length);
|
||||
}
|
||||
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string }): Promise<void> {
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn }): Promise<void> {
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// #1262: caller-resolved write target for TEXT embeddings. Descriptor
|
||||
// names are identifier-validated + quoted by buildVectorCastFragment;
|
||||
// omitted => legacy `embedding vector`. Mirrors postgres-engine.ts.
|
||||
const targetFragment = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn)
|
||||
: undefined;
|
||||
const targetCol = targetFragment?.col ?? 'embedding';
|
||||
const embeddingCast = targetFragment?.castSql.replace('$1::', '') ?? 'vector';
|
||||
|
||||
// Source-scope the page-id lookup so duplicate slugs in different sources
|
||||
// do not return multiple rows or target the wrong page.
|
||||
@@ -2279,7 +2279,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// list. Image chunks pass embedding=null + embedding_image=Float32Array
|
||||
// (1024-dim Voyage). Text/code chunks pass embedding=Float32Array +
|
||||
// embedding_image=null. Default modality='text' when omitted.
|
||||
const cols = '(page_id, chunk_index, chunk_text, chunk_source, embedding, model, token_count, embedded_at, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)';
|
||||
const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${targetCol}, model, token_count, embedded_at, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;
|
||||
const rowParts: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIdx = 1;
|
||||
@@ -2297,7 +2297,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
const modality = chunk.modality ?? 'text';
|
||||
|
||||
// Inline ::vector NULL literals to avoid a per-branch placeholder.
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::${embeddingCast}` : 'NULL';
|
||||
const embeddedAtPh = embeddingStr ? 'now()' : 'NULL';
|
||||
const embeddingImagePh = embeddingImageStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
|
||||
@@ -2336,19 +2336,19 @@ export class PGLiteEngine implements BrainEngine {
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
chunk_text = EXCLUDED.chunk_text,
|
||||
chunk_source = EXCLUDED.chunk_source,
|
||||
embedding = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding
|
||||
${targetCol} = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${targetCol}
|
||||
WHEN content_chunks.${targetCol} IS NULL THEN EXCLUDED.${targetCol}
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
THEN EXCLUDED.${targetCol}
|
||||
ELSE content_chunks.${targetCol}
|
||||
END,
|
||||
model = COALESCE(EXCLUDED.model, content_chunks.model),
|
||||
token_count = EXCLUDED.token_count,
|
||||
embedded_at = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL
|
||||
WHEN content_chunks.embedding IS NULL AND EXCLUDED.embedding IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.${targetCol} IS NULL THEN NULL
|
||||
WHEN content_chunks.${targetCol} IS NULL AND EXCLUDED.${targetCol} IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedded_at
|
||||
@@ -2386,14 +2386,19 @@ export class PGLiteEngine implements BrainEngine {
|
||||
* drift (NULL grandfathered → never stale). Shared by countStaleChunks +
|
||||
* sumStaleChunkChars so they can't drift.
|
||||
*/
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string }): { where: string; params: unknown[] } {
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): { where: string; params: unknown[] } {
|
||||
// #1262: staleness targets the caller-resolved write column when set
|
||||
// (identifier-validated + quoted); legacy `embedding` otherwise.
|
||||
const staleCol = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn).col
|
||||
: 'embedding';
|
||||
const params: unknown[] = [];
|
||||
const conds: string[] = [];
|
||||
if (opts?.signature !== undefined) {
|
||||
params.push(opts.signature);
|
||||
conds.push(`(cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
conds.push(`(cc.${staleCol} IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
} else {
|
||||
conds.push(`cc.embedding IS NULL`);
|
||||
conds.push(`cc.${staleCol} IS NULL`);
|
||||
}
|
||||
conds.push(`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
|
||||
if (opts?.sourceId !== undefined) {
|
||||
@@ -2403,7 +2408,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return { where: conds.join(' AND '), params };
|
||||
}
|
||||
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string }): Promise<number> {
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
// D7: source-scoped count for `gbrain embed --stale --source X`. Always
|
||||
// JOIN pages so embed-skip + signature predicates apply. PGLite is
|
||||
// PostgreSQL 17.5 in WASM and supports the full JSONB operator set.
|
||||
@@ -2419,7 +2424,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return Number(count);
|
||||
}
|
||||
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): Promise<number> {
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
// Sibling of countStaleChunks: same stale predicate, summing chunk_text
|
||||
// length for the sync cost preview. ::bigint guards int4 overflow.
|
||||
const { where, params } = this.buildStaleChunkWhere(opts);
|
||||
@@ -2472,11 +2477,17 @@ export class PGLiteEngine implements BrainEngine {
|
||||
sourceId?: string;
|
||||
orderBy?: 'page_id' | 'updated_desc';
|
||||
afterUpdatedAt?: string | null;
|
||||
embeddingColumn?: ResolvedColumn;
|
||||
}): Promise<StaleChunkRow[]> {
|
||||
const limit = opts?.batchSize ?? 2000;
|
||||
const afterPid = opts?.afterPageId ?? 0;
|
||||
const afterIdx = opts?.afterChunkIndex ?? -1;
|
||||
const orderBy = opts?.orderBy ?? 'page_id';
|
||||
// #1262: staleness follows the caller-resolved write column (validated +
|
||||
// quoted identifier); legacy `embedding` otherwise.
|
||||
const staleCol = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn).col
|
||||
: 'embedding';
|
||||
|
||||
// v0.41.18.0 (A13, codex #9): --priority recent path. See postgres-engine
|
||||
// sibling for full rationale. Same composite cursor + ORDER BY.
|
||||
@@ -2490,7 +2501,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
|
||||
LIMIT $1`,
|
||||
@@ -2501,7 +2512,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
p.updated_at < $1::timestamptz
|
||||
@@ -2520,7 +2531,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND p.source_id = $1
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
|
||||
@@ -2532,7 +2543,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND p.source_id = $1
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
@@ -2557,7 +2568,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
cc.model, cc.token_count, p.source_id, cc.page_id
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (cc.page_id, cc.chunk_index) > ($1, $2)
|
||||
ORDER BY cc.page_id, cc.chunk_index
|
||||
@@ -2571,7 +2582,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
cc.model, cc.token_count, p.source_id, cc.page_id
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
AND p.source_id = $1
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (cc.page_id, cc.chunk_index) > ($2, $3)
|
||||
|
||||
+50
-38
@@ -50,6 +50,7 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -64,7 +65,7 @@ import { ConnectionManager } from './connection-manager.ts';
|
||||
import { logConnectionEvent } from './connection-audit.ts';
|
||||
import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, takeRowToTake, takeHitRowToHit, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
|
||||
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, buildWebsearchQueryExpr } from './search/sql-ranking.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
|
||||
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
|
||||
import { DELETE_BATCH_SIZE } from './engine-constants.ts';
|
||||
|
||||
@@ -1691,8 +1692,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
|
||||
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
|
||||
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query];
|
||||
let typeClause = '';
|
||||
if (type) {
|
||||
@@ -1763,7 +1762,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
const rawQuery = `
|
||||
WITH ranked_chunks AS (
|
||||
@@ -1771,11 +1769,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.slug, p.id as page_id, p.title, p.type, p.source_id,
|
||||
p.effective_date, p.effective_date_source,
|
||||
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
|
||||
ts_rank(cc.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score
|
||||
ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
JOIN sources s ON s.id = p.source_id
|
||||
WHERE cc.search_vector @@ ${ftsQueryExpr}
|
||||
WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)
|
||||
${typeClause}
|
||||
${typesClause}
|
||||
${excludeSlugsClause}
|
||||
@@ -1866,10 +1864,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query];
|
||||
let typeClause = '';
|
||||
if (opts?.type) {
|
||||
@@ -1929,7 +1924,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
COALESCE(rep.chunk_index, 0) as chunk_index,
|
||||
COALESCE(rep.chunk_text, '') as chunk_text,
|
||||
COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,
|
||||
ts_rank_cd(p.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score,
|
||||
ts_rank_cd(p.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
|
||||
false AS stale
|
||||
FROM pages p
|
||||
JOIN sources s ON s.id = p.source_id
|
||||
@@ -1942,7 +1937,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
|
||||
LIMIT 1
|
||||
) rep ON true
|
||||
WHERE p.search_vector @@ ${ftsQueryExpr}
|
||||
WHERE p.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)
|
||||
${typeClause}
|
||||
${typesClause}
|
||||
${excludeSlugsClause}
|
||||
@@ -2006,8 +2001,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
|
||||
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
|
||||
|
||||
// #2380: slash-bearing queries match both the split-word and literal
|
||||
// slash forms — see buildWebsearchQueryExpr in ./search/sql-ranking.ts.
|
||||
const params: unknown[] = [query];
|
||||
let typeClause = '';
|
||||
if (type) {
|
||||
@@ -2068,19 +2061,18 @@ export class PostgresEngine implements BrainEngine {
|
||||
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
|
||||
// — safe to interpolate into raw SQL.
|
||||
const ftsLang = getFtsLanguage();
|
||||
const ftsQueryExpr = buildWebsearchQueryExpr(ftsLang, '$1', query);
|
||||
|
||||
const rawQuery = `
|
||||
SELECT
|
||||
p.slug, p.id as page_id, p.title, p.type, p.source_id,
|
||||
p.effective_date, p.effective_date_source,
|
||||
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
|
||||
ts_rank(cc.search_vector, ${ftsQueryExpr}) * ${sourceFactorCase} AS score,
|
||||
ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
|
||||
false AS stale
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
JOIN sources s ON s.id = p.source_id
|
||||
WHERE cc.search_vector @@ ${ftsQueryExpr}
|
||||
WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)
|
||||
${typeClause}
|
||||
${typesClause}
|
||||
${excludeSlugsClause}
|
||||
@@ -2389,13 +2381,21 @@ export class PostgresEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Chunks
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & BatchOpts): Promise<void> {
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {
|
||||
return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal, () => this._upsertChunksOnce(slug, chunks, opts), chunks.length);
|
||||
}
|
||||
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string }): Promise<void> {
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn }): Promise<void> {
|
||||
const sql = this.sql;
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// #1262: caller-resolved write target for TEXT embeddings. Descriptor
|
||||
// names are identifier-validated + quoted by buildVectorCastFragment;
|
||||
// omitted => legacy `embedding vector`.
|
||||
const targetFragment = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn)
|
||||
: undefined;
|
||||
const targetCol = targetFragment?.col ?? 'embedding';
|
||||
const embeddingCast = targetFragment?.castSql.replace('$1::', '') ?? 'vector';
|
||||
|
||||
// Source-scope the page-id lookup. Without this filter, multi-source
|
||||
// brains where the slug exists in 2+ sources return >1 row and the
|
||||
@@ -2422,7 +2422,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
// scope metadata through upserts.
|
||||
// v0.27.1 (Phase 8): added `modality` + `embedding_image` to the column
|
||||
// list. Image chunks pass embedding=null + embedding_image=Float32Array.
|
||||
const cols = '(page_id, chunk_index, chunk_text, chunk_source, embedding, model, token_count, embedded_at, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)';
|
||||
const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${targetCol}, model, token_count, embedded_at, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;
|
||||
const rows: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIdx = 1;
|
||||
@@ -2439,7 +2439,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
: null;
|
||||
const modality = chunk.modality ?? 'text';
|
||||
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::${embeddingCast}` : 'NULL';
|
||||
const embeddedAtPh = embeddingStr ? 'now()' : 'NULL';
|
||||
const embeddingImagePh = embeddingImageStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
|
||||
@@ -2487,19 +2487,19 @@ export class PostgresEngine implements BrainEngine {
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
chunk_text = EXCLUDED.chunk_text,
|
||||
chunk_source = EXCLUDED.chunk_source,
|
||||
embedding = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding
|
||||
${targetCol} = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${targetCol}
|
||||
WHEN content_chunks.${targetCol} IS NULL THEN EXCLUDED.${targetCol}
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
THEN EXCLUDED.${targetCol}
|
||||
ELSE content_chunks.${targetCol}
|
||||
END,
|
||||
model = COALESCE(EXCLUDED.model, content_chunks.model),
|
||||
token_count = EXCLUDED.token_count,
|
||||
embedded_at = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL
|
||||
WHEN content_chunks.embedding IS NULL AND EXCLUDED.embedding IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.${targetCol} IS NULL THEN NULL
|
||||
WHEN content_chunks.${targetCol} IS NULL AND EXCLUDED.${targetCol} IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedded_at
|
||||
@@ -2539,14 +2539,19 @@ export class PostgresEngine implements BrainEngine {
|
||||
* embedding_signature drift (NULL grandfathered). Shared by
|
||||
* countStaleChunks + sumStaleChunkChars (parity with the PGLite sibling).
|
||||
*/
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string }): { where: string; params: unknown[] } {
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): { where: string; params: unknown[] } {
|
||||
// #1262: staleness targets the caller-resolved write column when set
|
||||
// (identifier-validated + quoted); legacy `embedding` otherwise.
|
||||
const staleCol = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn).col
|
||||
: 'embedding';
|
||||
const params: unknown[] = [];
|
||||
const conds: string[] = [];
|
||||
if (opts?.signature !== undefined) {
|
||||
params.push(opts.signature);
|
||||
conds.push(`(cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
conds.push(`(cc.${staleCol} IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
} else {
|
||||
conds.push(`cc.embedding IS NULL`);
|
||||
conds.push(`cc.${staleCol} IS NULL`);
|
||||
}
|
||||
conds.push(`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
|
||||
if (opts?.sourceId !== undefined) {
|
||||
@@ -2556,7 +2561,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
return { where: conds.join(' AND '), params };
|
||||
}
|
||||
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string }): Promise<number> {
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
// Always JOIN pages so the embed_skip + signature predicates apply.
|
||||
// D7: source_id scoping. v0.41.31: optional signature widens staleness
|
||||
// to embedding_signature drift (NULL grandfathered).
|
||||
@@ -2574,7 +2579,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): Promise<number> {
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
// Sibling of countStaleChunks: same stale predicate, summing chunk_text
|
||||
// length for the sync cost preview. ::bigint guards int4 overflow.
|
||||
const { where, params } = this.buildStaleChunkWhere(opts);
|
||||
@@ -2627,11 +2632,18 @@ export class PostgresEngine implements BrainEngine {
|
||||
sourceId?: string;
|
||||
orderBy?: 'page_id' | 'updated_desc';
|
||||
afterUpdatedAt?: string | null;
|
||||
embeddingColumn?: ResolvedColumn;
|
||||
}): Promise<StaleChunkRow[]> {
|
||||
const limit = opts?.batchSize ?? 2000;
|
||||
const afterPid = opts?.afterPageId ?? 0;
|
||||
const afterIdx = opts?.afterChunkIndex ?? -1;
|
||||
const orderBy = opts?.orderBy ?? 'page_id';
|
||||
// #1262: staleness follows the caller-resolved write column (validated +
|
||||
// quoted identifier); legacy `embedding` otherwise. Interpolated below as
|
||||
// an unsafe FRAGMENT (identifiers can't be bound parameters).
|
||||
const staleCol = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn).col
|
||||
: 'embedding';
|
||||
|
||||
// RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING).
|
||||
return await this.withScopedReadTransaction(undefined, opts?.sourceId, async (tx) => {
|
||||
@@ -2648,7 +2660,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
|
||||
LIMIT ${limit}
|
||||
@@ -2658,7 +2670,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
p.updated_at < ${afterUpdated}::timestamptz
|
||||
@@ -2676,7 +2688,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND p.source_id = ${opts.sourceId}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
|
||||
@@ -2687,7 +2699,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND p.source_id = ${opts.sourceId}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
@@ -2707,7 +2719,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
cc.model, cc.token_count, p.source_id, cc.page_id
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
|
||||
ORDER BY cc.page_id, cc.chunk_index
|
||||
@@ -2720,7 +2732,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
cc.model, cc.token_count, p.source_id, cc.page_id
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.embedding IS NULL
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
AND p.source_id = ${opts.sourceId}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
|
||||
|
||||
@@ -443,6 +443,80 @@ export function resolveEmbeddingColumn(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the WRITE-side embedding column for the currently configured
|
||||
* embedding model (#1262). The read-side resolver above answers "which
|
||||
* column does this query search?"; this one answers "which column should
|
||||
* newly produced text embeddings land in?".
|
||||
*
|
||||
* Unlike read-side search, writes take no per-call column override. The
|
||||
* import/embed boundary resolves once from merged config + gateway state
|
||||
* and passes the descriptor into `engine.upsertChunks`; engines stay
|
||||
* config-free (same contract as the read-side descriptor).
|
||||
*
|
||||
* Behavior:
|
||||
* - no user-declared `embedding_columns` => undefined (legacy brain,
|
||||
* writes keep targeting the default `embedding` column)
|
||||
* - a user-declared entry whose `provider` matches the current
|
||||
* embedding model => that entry's descriptor
|
||||
* - no provider match => undefined (fall back to legacy `embedding`)
|
||||
*
|
||||
* Only USER-declared entries are consulted — never the cfg-derived
|
||||
* builtins. The `embedding_image` builtin's provider is the multimodal
|
||||
* model; matching it here would misroute text embeddings into the image
|
||||
* column. The no-match fallback is intentional: switching models before
|
||||
* registering a matching column must not silently write vectors into an
|
||||
* arbitrary column.
|
||||
*/
|
||||
export function resolveWriteColumn(cfg: GBrainConfig): ResolvedColumn | undefined {
|
||||
const userColumns = cfg.embedding_columns;
|
||||
if (
|
||||
!userColumns ||
|
||||
typeof userColumns !== 'object' ||
|
||||
Array.isArray(userColumns) ||
|
||||
Object.keys(userColumns).length === 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Same model-resolution chain as the registry builtin: cfg > gateway > default.
|
||||
let gwModel: string | undefined;
|
||||
try {
|
||||
const gw = require('../ai/gateway.ts') as typeof import('../ai/gateway.ts');
|
||||
gwModel = gw.getEmbeddingModel();
|
||||
} catch {
|
||||
// Gateway unconfigured — fall through to the canonical default.
|
||||
}
|
||||
const currentModel = cfg.embedding_model ?? gwModel ?? DEFAULT_EMBEDDING_MODEL;
|
||||
|
||||
for (const [name, entry] of Object.entries(userColumns)) {
|
||||
if (!entry) continue;
|
||||
validateColumnKey(name);
|
||||
validateColumnConfig(name, entry);
|
||||
if (entry.provider !== currentModel) continue;
|
||||
return {
|
||||
name,
|
||||
type: entry.type,
|
||||
dimensions: entry.dimensions,
|
||||
embeddingModel: entry.provider,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Engine-boundary convenience: merged config (file/env + DB plane) →
|
||||
* resolveWriteColumn. Dynamic import keeps config.ts out of this module's
|
||||
* static graph (mirrors the gateway require above).
|
||||
*/
|
||||
export async function resolveWriteColumnForEngine(
|
||||
engine: { getConfig(key: string): Promise<string | null | undefined> },
|
||||
): Promise<ResolvedColumn | undefined> {
|
||||
const { loadConfigWithEngine } = await import('../config.ts');
|
||||
const cfg = await loadConfigWithEngine(engine);
|
||||
return cfg ? resolveWriteColumn(cfg) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the resolved column is the default `embedding` name.
|
||||
* Name-based check; does not compare embedding space.
|
||||
|
||||
@@ -251,28 +251,6 @@ export function buildOrFallbackWebsearchQuery(query: string): string | null {
|
||||
return tokens.join(' OR ');
|
||||
}
|
||||
|
||||
/**
|
||||
* #2380: FTS query expression for slash-bearing queries. Postgres' default
|
||||
* text-search parser classifies `foo/bar` as a single `file`-alias lexeme —
|
||||
* on BOTH the query side and the index side. So a raw `foo/bar` query only
|
||||
* matched documents carrying the identical joined lexeme (literal paths),
|
||||
* and a slash-split query only matches documents whose text had the words
|
||||
* separated. Neither form alone covers both document shapes; OR the two
|
||||
* parses so a slash query matches prose ("foo and bar", stemmed, AND
|
||||
* semantics) AND literal slash forms ("src/core/x.ts") alike.
|
||||
*
|
||||
* Slash-free queries return the plain single-parse expression — byte-
|
||||
* identical SQL and identical ts_rank to the historical behavior.
|
||||
*
|
||||
* `ftsLang` is validated by getFtsLanguage() (safe to interpolate);
|
||||
* `param` is a `$N` placeholder, never user text.
|
||||
*/
|
||||
export function buildWebsearchQueryExpr(ftsLang: string, param: string, query: string): string {
|
||||
const plain = `websearch_to_tsquery('${ftsLang}', ${param})`;
|
||||
if (!query.includes('/')) return plain;
|
||||
return `(websearch_to_tsquery('${ftsLang}', translate(${param}, '/', ' ')) || ${plain})`;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// v0.29.1 — Recency component SQL builder
|
||||
// ============================================================
|
||||
|
||||
@@ -28,8 +28,8 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
test('LiteLLM and llama-server declare no_batch_cap: true', () => {
|
||||
for (const id of ['litellm', 'llama-server']) {
|
||||
test('Ollama, LiteLLM, llama-server all declare no_batch_cap: true', () => {
|
||||
for (const id of ['ollama', 'litellm', 'llama-server']) {
|
||||
const r = getRecipe(id);
|
||||
expect(r, `${id} not registered`).toBeDefined();
|
||||
expect(
|
||||
@@ -39,18 +39,6 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
}
|
||||
});
|
||||
|
||||
test('#2552: Ollama declares a conservative static batch cap, not no_batch_cap', () => {
|
||||
// A CPU-only Ollama box wedges when a whole page ships in one request;
|
||||
// Ollama never returns a token-limit error so the recursive-halving
|
||||
// safety net can't fire. The pre-split cap is the only guard.
|
||||
const r = getRecipe('ollama');
|
||||
expect(r).toBeDefined();
|
||||
const e = r!.touchpoints.embedding!;
|
||||
expect(e.no_batch_cap).toBeUndefined();
|
||||
expect(e.max_batch_tokens).toBe(4096);
|
||||
expect(e.chars_per_token).toBe(2);
|
||||
});
|
||||
|
||||
test('configureGateway does NOT warn for ollama/litellm/llama-server', () => {
|
||||
warnSpy.mockClear();
|
||||
resetGateway();
|
||||
|
||||
@@ -241,3 +241,136 @@ describe('buildVectorCastFragment — engine SQL composer (D3)', () => {
|
||||
expect(castSql).toBe('$1::halfvec(2560)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PGLite engine: upsertChunks write-side ResolvedColumn descriptor (#1262)', () => {
|
||||
test('halfvec descriptor writes the text embedding to the alternate column, not legacy embedding', async () => {
|
||||
await engine.putPage('docs/write-alt-pglite', {
|
||||
type: 'concept',
|
||||
title: 'Write alt column PGLite',
|
||||
compiled_truth: 'PGLite write-side alternate embedding column test.',
|
||||
});
|
||||
|
||||
const descriptor: ResolvedColumn = {
|
||||
name: 'embedding_ze',
|
||||
type: 'halfvec',
|
||||
dimensions: 2560,
|
||||
embeddingModel: 'zeroentropyai:zembed-1',
|
||||
};
|
||||
await engine.upsertChunks('docs/write-alt-pglite', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'PGLite write-side alternate embedding column test.',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(2560).fill(0.25),
|
||||
},
|
||||
], { embeddingColumn: descriptor });
|
||||
|
||||
const rows = await engine.executeRaw<{
|
||||
has_default: boolean;
|
||||
has_ze: boolean;
|
||||
has_embedded_at: boolean;
|
||||
}>(
|
||||
`SELECT embedding IS NOT NULL AS has_default,
|
||||
embedding_ze IS NOT NULL AS has_ze,
|
||||
embedded_at IS NOT NULL AS has_embedded_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = 'docs/write-alt-pglite'`,
|
||||
);
|
||||
expect(rows.length).toBe(1);
|
||||
expect(rows[0].has_default).toBe(false);
|
||||
expect(rows[0].has_ze).toBe(true);
|
||||
expect(rows[0].has_embedded_at).toBe(true);
|
||||
});
|
||||
|
||||
test('text-unchanged re-upsert without a vector preserves the alternate-column embedding', async () => {
|
||||
const descriptor: ResolvedColumn = {
|
||||
name: 'embedding_ze',
|
||||
type: 'halfvec',
|
||||
dimensions: 2560,
|
||||
embeddingModel: 'zeroentropyai:zembed-1',
|
||||
};
|
||||
// Same chunk_text, no embedding: the ON CONFLICT CASE must keep the
|
||||
// existing alternate-column vector (D24 semantics follow the column).
|
||||
await engine.upsertChunks('docs/write-alt-pglite', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'PGLite write-side alternate embedding column test.',
|
||||
chunk_source: 'compiled_truth',
|
||||
},
|
||||
], { embeddingColumn: descriptor });
|
||||
const rows = await engine.executeRaw<{ has_ze: boolean }>(
|
||||
`SELECT embedding_ze IS NOT NULL AS has_ze
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = 'docs/write-alt-pglite'`,
|
||||
);
|
||||
expect(rows).toEqual([{ has_ze: true }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PGLite: embed --stale converges on an alt-column brain (#1262)', () => {
|
||||
test('boundary resolves the write column; stale scan does not re-select embedded rows', async () => {
|
||||
const { runEmbedCore } = await import('../../src/commands/embed.ts');
|
||||
const local = new PGLiteEngine();
|
||||
const previousHome = process.env.GBRAIN_HOME;
|
||||
process.env.GBRAIN_HOME = `/tmp/gbrain-write-col-stale-${Date.now()}`;
|
||||
try {
|
||||
await local.connect({});
|
||||
await local.initSchema();
|
||||
await (local as any).db.exec(
|
||||
`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_ze halfvec(2560)`,
|
||||
);
|
||||
|
||||
const descriptor: ResolvedColumn = {
|
||||
name: 'embedding_ze',
|
||||
type: 'halfvec',
|
||||
dimensions: 2560,
|
||||
embeddingModel: 'zeroentropyai:zembed-1',
|
||||
};
|
||||
await local.setConfig('embedding_columns', JSON.stringify({
|
||||
embedding_ze: { provider: 'zeroentropyai:zembed-1', dimensions: 2560, type: 'halfvec' },
|
||||
}));
|
||||
configureGateway({
|
||||
embedding_model: 'zeroentropyai:zembed-1',
|
||||
embedding_dimensions: 2560,
|
||||
env: {},
|
||||
});
|
||||
|
||||
await local.putPage('docs/stale-alt-pglite', {
|
||||
type: 'concept',
|
||||
title: 'Dynamic stale column',
|
||||
compiled_truth: 'A chunk that is embedded only in the dynamic column.',
|
||||
});
|
||||
await local.upsertChunks('docs/stale-alt-pglite', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'A chunk that is embedded only in the dynamic column.',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(2560).fill(0.25),
|
||||
},
|
||||
], { embeddingColumn: descriptor });
|
||||
|
||||
// Engine-level contrast: legacy predicate still sees the row as stale;
|
||||
// the alt-column predicate does not.
|
||||
expect(await local.countStaleChunks()).toBe(1);
|
||||
expect(await local.countStaleChunks({ embeddingColumn: descriptor })).toBe(0);
|
||||
// sumStaleChunkChars feeds the sync cost gate — same predicate contract.
|
||||
expect(await local.sumStaleChunkChars()).toBeGreaterThan(0);
|
||||
expect(await local.sumStaleChunkChars({ embeddingColumn: descriptor })).toBe(0);
|
||||
expect(await local.listStaleChunks({ embeddingColumn: descriptor, batchSize: 100 })).toHaveLength(0);
|
||||
expect(await local.listStaleChunks({ batchSize: 100 })).toHaveLength(1);
|
||||
|
||||
// Boundary-level: `embed --stale --dry-run` resolves the write column
|
||||
// from merged config + gateway and reports NOTHING to embed. Without
|
||||
// the fix this reports 1 (perpetual re-embed loop).
|
||||
const result = await runEmbedCore(local, { stale: true, dryRun: true });
|
||||
expect(result.would_embed).toBe(0);
|
||||
} finally {
|
||||
await local.disconnect();
|
||||
if (previousHome === undefined) delete process.env.GBRAIN_HOME;
|
||||
else process.env.GBRAIN_HOME = previousHome;
|
||||
resetGateway();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -224,4 +224,54 @@ if (!dbUrl) {
|
||||
await engine.executeRaw(`UPDATE content_chunks SET embedding_voyage = '${v}'::vector WHERE id = ${dogId}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Postgres: upsertChunks write-side ResolvedColumn descriptor (#1262)', () => {
|
||||
const descriptor: ResolvedColumn = {
|
||||
name: 'embedding_ze',
|
||||
type: 'halfvec',
|
||||
dimensions: 2560,
|
||||
embeddingModel: 'zeroentropyai:zembed-1',
|
||||
};
|
||||
|
||||
test('halfvec descriptor writes the text embedding to the alternate column, not legacy embedding', async () => {
|
||||
await engine.putPage('docs/write-alt-postgres', {
|
||||
type: 'concept',
|
||||
title: 'Write alt column Postgres',
|
||||
compiled_truth: 'Postgres write-side alternate embedding column test.',
|
||||
});
|
||||
await engine.upsertChunks('docs/write-alt-postgres', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'Postgres write-side alternate embedding column test.',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(2560).fill(0.25),
|
||||
},
|
||||
], { embeddingColumn: descriptor });
|
||||
|
||||
const rows = await engine.executeRaw<{
|
||||
has_default: boolean;
|
||||
has_ze: boolean;
|
||||
}>(
|
||||
`SELECT embedding IS NOT NULL AS has_default,
|
||||
embedding_ze IS NOT NULL AS has_ze
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = 'docs/write-alt-postgres'`,
|
||||
);
|
||||
expect(rows.length).toBe(1);
|
||||
expect(rows[0].has_default).toBe(false);
|
||||
expect(rows[0].has_ze).toBe(true);
|
||||
}, 30_000);
|
||||
|
||||
test('stale scan follows the write-side column (count + list parity with the write target)', async () => {
|
||||
// Legacy predicate: cat/dog/write-alt rows all have embedding NULL.
|
||||
expect(await engine.countStaleChunks()).toBeGreaterThan(0);
|
||||
// Alt-column predicate: every chunk has embedding_ze populated.
|
||||
expect(await engine.countStaleChunks({ embeddingColumn: descriptor })).toBe(0);
|
||||
expect(await engine.listStaleChunks({ embeddingColumn: descriptor, batchSize: 100 })).toHaveLength(0);
|
||||
expect((await engine.listStaleChunks({ batchSize: 100 })).length).toBeGreaterThan(0);
|
||||
// updated_desc arm uses the same predicate.
|
||||
expect(await engine.listStaleChunks({ embeddingColumn: descriptor, orderBy: 'updated_desc', batchSize: 100 })).toHaveLength(0);
|
||||
}, 30_000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* #2552: cloud-tuned embedding defaults silently wedge CPU-only local
|
||||
* endpoints (Ollama). Three-part fix under test:
|
||||
*
|
||||
* 1. `isLocalEmbeddingEndpoint()` — gateway helper detecting local
|
||||
* inference servers (ollama / llama-server recipes, localhost base URL).
|
||||
* 2. `resolveEmbedConcurrency()` — embed auto-caps the 20-worker fan-out
|
||||
* at LOCAL_EMBED_CONCURRENCY_CAP for local endpoints unless the
|
||||
* operator set GBRAIN_EMBED_CONCURRENCY explicitly.
|
||||
* 3. `computeEmbedConcurrencyCheck()` — doctor warns when an explicit env
|
||||
* override fans out against a local endpoint.
|
||||
*
|
||||
* Serial: mutates process.env and the module-global gateway config.
|
||||
*/
|
||||
|
||||
import { afterAll, afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
configureGateway,
|
||||
resetGateway,
|
||||
isLocalEmbeddingEndpoint,
|
||||
LOCAL_EMBED_CONCURRENCY_CAP,
|
||||
} from '../src/core/ai/gateway.ts';
|
||||
import { resolveEmbedConcurrency } from '../src/commands/embed.ts';
|
||||
import { computeEmbedConcurrencyCheck } from '../src/commands/doctor.ts';
|
||||
|
||||
const SAVED_ENV = process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
|
||||
afterEach(() => {
|
||||
resetGateway();
|
||||
if (SAVED_ENV === undefined) delete process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
else process.env.GBRAIN_EMBED_CONCURRENCY = SAVED_ENV;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
describe('#2552 isLocalEmbeddingEndpoint', () => {
|
||||
test('false when the gateway is not configured (fail-open to cloud behavior)', () => {
|
||||
resetGateway();
|
||||
expect(isLocalEmbeddingEndpoint()).toBe(false);
|
||||
});
|
||||
|
||||
test('true for the ollama recipe', () => {
|
||||
configureGateway({ embedding_model: 'ollama:nomic-embed-text', env: {} });
|
||||
expect(isLocalEmbeddingEndpoint()).toBe(true);
|
||||
});
|
||||
|
||||
test('true for the llama-server recipe', () => {
|
||||
configureGateway({ embedding_model: 'llama-server:my-gguf', env: {} });
|
||||
expect(isLocalEmbeddingEndpoint()).toBe(true);
|
||||
});
|
||||
|
||||
test('false for a cloud recipe', () => {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-small',
|
||||
env: { OPENAI_API_KEY: 'fake' },
|
||||
});
|
||||
expect(isLocalEmbeddingEndpoint()).toBe(false);
|
||||
});
|
||||
|
||||
test('true when a cloud recipe base URL is explicitly pointed at localhost', () => {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-small',
|
||||
env: { OPENAI_API_KEY: 'fake' },
|
||||
base_urls: { openai: 'http://localhost:8080/v1' },
|
||||
});
|
||||
expect(isLocalEmbeddingEndpoint()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#2552 resolveEmbedConcurrency', () => {
|
||||
test('caps at LOCAL_EMBED_CONCURRENCY_CAP for a local endpoint when env is unset', () => {
|
||||
delete process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
configureGateway({ embedding_model: 'ollama:nomic-embed-text', env: {} });
|
||||
expect(resolveEmbedConcurrency()).toBe(LOCAL_EMBED_CONCURRENCY_CAP);
|
||||
});
|
||||
|
||||
test('explicit env override always wins, even against a local endpoint', () => {
|
||||
process.env.GBRAIN_EMBED_CONCURRENCY = '10';
|
||||
configureGateway({ embedding_model: 'ollama:nomic-embed-text', env: {} });
|
||||
expect(resolveEmbedConcurrency()).toBe(10);
|
||||
});
|
||||
|
||||
test('cloud endpoints keep the historical default of 20', () => {
|
||||
delete process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
configureGateway({ env: { OPENAI_API_KEY: 'fake' } });
|
||||
expect(resolveEmbedConcurrency()).toBe(20);
|
||||
});
|
||||
|
||||
test('pacing only ever lowers concurrency', () => {
|
||||
delete process.env.GBRAIN_EMBED_CONCURRENCY;
|
||||
configureGateway({ embedding_model: 'ollama:nomic-embed-text', env: {} });
|
||||
expect(resolveEmbedConcurrency(1)).toBe(1);
|
||||
expect(resolveEmbedConcurrency(16)).toBe(LOCAL_EMBED_CONCURRENCY_CAP);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#2552 computeEmbedConcurrencyCheck (doctor)', () => {
|
||||
test('ok for non-local endpoints', () => {
|
||||
expect(computeEmbedConcurrencyCheck(false, '20', 2).status).toBe('ok');
|
||||
});
|
||||
|
||||
test('warn when an explicit override exceeds the local cap', () => {
|
||||
const check = computeEmbedConcurrencyCheck(true, '20', 2);
|
||||
expect(check.status).toBe('warn');
|
||||
expect(check.message).toContain('GBRAIN_EMBED_CONCURRENCY=20');
|
||||
});
|
||||
|
||||
test('ok when env is unset against a local endpoint (auto-cap applies)', () => {
|
||||
expect(computeEmbedConcurrencyCheck(true, undefined, 2).status).toBe('ok');
|
||||
});
|
||||
|
||||
test('ok when the override is at or under the cap', () => {
|
||||
expect(computeEmbedConcurrencyCheck(true, '2', 2).status).toBe('ok');
|
||||
expect(computeEmbedConcurrencyCheck(true, '1', 2).status).toBe('ok');
|
||||
});
|
||||
});
|
||||
@@ -216,67 +216,6 @@ describe('PGLiteEngine: Search', () => {
|
||||
expect(results.length).toBe(0);
|
||||
});
|
||||
|
||||
// Regression (#2380): queries containing `/` used to bypass FTS AND
|
||||
// semantics. Postgres' default text-search parser classifies `foo/bar` as
|
||||
// a `file`-alias token mapped to the `simple` dictionary, so it became a
|
||||
// single un-stemmed lexeme `'foo/bar'` that never matches indexed text —
|
||||
// the primary FTS pass returned 0 and the OR fallback took over, matching
|
||||
// pages that contain EITHER term. searchKeyword/searchTitles now normalize
|
||||
// `/` to whitespace before websearch_to_tsquery parses, so the primary
|
||||
// AND pass matches directly.
|
||||
test('searchKeyword: slash query matches with AND semantics, not OR fallback', async () => {
|
||||
// Decoy shares only ONE of the two query terms ('enterprise').
|
||||
await engine.putPage('concepts/enterprise-pricing', {
|
||||
type: 'concept', title: 'Widget Pricing',
|
||||
compiled_truth: 'Enterprise pricing for widgets.',
|
||||
});
|
||||
await engine.upsertChunks('concepts/enterprise-pricing', [
|
||||
{ chunk_index: 0, chunk_text: 'Enterprise pricing for widgets', chunk_source: 'compiled_truth' },
|
||||
]);
|
||||
|
||||
// Both terms co-occur only in the novamind chunk. Pre-fix this returned
|
||||
// BOTH pages (primary pass zero-hit → OR fallback); post-fix the primary
|
||||
// AND pass returns exactly the co-occurrence page.
|
||||
const results = await engine.searchKeyword('NovaMind/enterprise');
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].slug).toBe('companies/novamind');
|
||||
});
|
||||
|
||||
test('searchTitles: slash query matches with AND semantics, not OR fallback', async () => {
|
||||
await engine.putPage('companies/novamind-enterprise', {
|
||||
type: 'company', title: 'NovaMind Enterprise Platform',
|
||||
compiled_truth: 'Placeholder body.',
|
||||
});
|
||||
await engine.putPage('guides/enterprise-sales', {
|
||||
type: 'concept', title: 'Enterprise Sales Guide',
|
||||
compiled_truth: 'Placeholder body.',
|
||||
});
|
||||
|
||||
// Pre-fix: `NovaMind/Enterprise` parsed as one file-alias lexeme → the
|
||||
// primary title pass returned 0 and the OR fallback matched BOTH titles.
|
||||
const results = await engine.searchTitles('NovaMind/Enterprise');
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].slug).toBe('companies/novamind-enterprise');
|
||||
});
|
||||
|
||||
test('searchKeyword: slash query still matches the literal slash form (file paths)', async () => {
|
||||
// The INDEX side also emits the joined file-alias lexeme for literal
|
||||
// `foo/bar` text, so a query normalized to split words alone would go
|
||||
// blind to documents containing the literal slash form (paths, URLs).
|
||||
// buildWebsearchQueryExpr ORs both parses; this pins the raw arm.
|
||||
await engine.putPage('runbooks/widget-deploy', {
|
||||
type: 'concept', title: 'Widget Deploy Runbook',
|
||||
compiled_truth: 'Runbook for the acme/widget deployment pipeline.',
|
||||
});
|
||||
await engine.upsertChunks('runbooks/widget-deploy', [
|
||||
{ chunk_index: 0, chunk_text: 'Runbook for the acme/widget deployment pipeline', chunk_source: 'compiled_truth' },
|
||||
]);
|
||||
|
||||
const results = await engine.searchKeyword('acme/widget');
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].slug).toBe('runbooks/widget-deploy');
|
||||
});
|
||||
|
||||
test('tsvector trigger populates search_vector on insert', async () => {
|
||||
// Verify the PL/pgSQL trigger fires and content_chunks.search_vector is
|
||||
// populated from chunk_text. v0.20.0 Cathedral II Layer 3 moved FTS from
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* throw on unknown string.
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { describe, test, expect, afterAll, afterEach } from 'bun:test';
|
||||
import {
|
||||
resolveEmbeddingColumn,
|
||||
resolveWriteColumn,
|
||||
getEmbeddingColumnRegistry,
|
||||
buildVectorCastFragment,
|
||||
quoteIdentifier,
|
||||
@@ -34,6 +35,28 @@ import {
|
||||
} from '../../src/core/search/embedding-column.ts';
|
||||
import type { GBrainConfig } from '../../src/core/config.ts';
|
||||
import type { ResolvedColumn } from '../../src/core/types.ts';
|
||||
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
|
||||
|
||||
/**
|
||||
* Teardown: reset AND re-apply the legacy preload config
|
||||
* (test/helpers/legacy-embedding-preload.ts). A bare resetGateway() would
|
||||
* leave the slot empty for the NEXT file's beforeAll (the preload's
|
||||
* per-test beforeEach only fires before tests, not before beforeAll), which
|
||||
* would make sibling PGLite fixtures initSchema at the 1280 default instead
|
||||
* of the legacy 1536 their seed vectors assume.
|
||||
*/
|
||||
function restorePreloadGateway() {
|
||||
resetGateway();
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
embedding_dimensions: 1536,
|
||||
env: { ...process.env },
|
||||
});
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
restorePreloadGateway();
|
||||
});
|
||||
|
||||
function cfg(overrides: Partial<GBrainConfig> = {}): GBrainConfig {
|
||||
return { engine: 'pglite', ...overrides };
|
||||
@@ -522,3 +545,89 @@ describe('codex /ship #4 — isCacheSafe (embedding-space-based skip)', () => {
|
||||
expect(isCacheSafe(r, cfg())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveWriteColumn — write-side boundary resolution (#1262)', () => {
|
||||
afterEach(() => {
|
||||
restorePreloadGateway();
|
||||
});
|
||||
|
||||
test('no registry / empty registry returns undefined (legacy single-column brain)', () => {
|
||||
expect(resolveWriteColumn(cfg())).toBeUndefined();
|
||||
expect(resolveWriteColumn(cfg({ embedding_columns: {} }))).toBeUndefined();
|
||||
});
|
||||
|
||||
test('provider match via cfg.embedding_model returns the descriptor', () => {
|
||||
const r = resolveWriteColumn(cfg({
|
||||
embedding_model: 'voyage:voyage-3-large',
|
||||
embedding_dimensions: 1024,
|
||||
embedding_columns: {
|
||||
embedding_voyage: { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' },
|
||||
},
|
||||
}));
|
||||
expect(r).toEqual({
|
||||
name: 'embedding_voyage',
|
||||
type: 'vector',
|
||||
dimensions: 1024,
|
||||
embeddingModel: 'voyage:voyage-3-large',
|
||||
});
|
||||
});
|
||||
|
||||
test('provider match via gateway state (cfg.embedding_model unset) returns descriptor', () => {
|
||||
configureGateway({
|
||||
embedding_model: 'zeroentropyai:zembed-1',
|
||||
embedding_dimensions: 2560,
|
||||
env: {},
|
||||
});
|
||||
const r = resolveWriteColumn(cfg({
|
||||
embedding_columns: {
|
||||
embedding_ze: { provider: 'zeroentropyai:zembed-1', dimensions: 2560, type: 'halfvec' },
|
||||
},
|
||||
}));
|
||||
expect(r).toEqual({
|
||||
name: 'embedding_ze',
|
||||
type: 'halfvec',
|
||||
dimensions: 2560,
|
||||
embeddingModel: 'zeroentropyai:zembed-1',
|
||||
});
|
||||
});
|
||||
|
||||
test('no provider match returns undefined instead of guessing a column', () => {
|
||||
configureGateway({
|
||||
embedding_model: 'zeroentropyai:zembed-1',
|
||||
embedding_dimensions: 2560,
|
||||
env: {},
|
||||
});
|
||||
const r = resolveWriteColumn(cfg({
|
||||
embedding_columns: {
|
||||
embedding_voyage: { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' },
|
||||
},
|
||||
}));
|
||||
expect(r).toBeUndefined();
|
||||
});
|
||||
|
||||
test('only USER-declared columns are consulted — multimodal builtin never captures text writes', () => {
|
||||
// Current model equals the embedding_image BUILTIN's provider; a registry
|
||||
// walk that consulted builtins would misroute text writes into the image
|
||||
// column. resolveWriteColumn must return undefined here.
|
||||
configureGateway({
|
||||
embedding_model: 'voyage:voyage-multimodal-3',
|
||||
embedding_dimensions: 1024,
|
||||
env: {},
|
||||
});
|
||||
const r = resolveWriteColumn(cfg({
|
||||
embedding_columns: {
|
||||
embedding_other: { provider: 'openai:text-embedding-3-large', dimensions: 1536, type: 'vector' },
|
||||
},
|
||||
}));
|
||||
expect(r).toBeUndefined();
|
||||
});
|
||||
|
||||
test('malformed registry entry throws loud (same validation as the read side)', () => {
|
||||
expect(() => resolveWriteColumn(cfg({
|
||||
embedding_model: 'voyage:voyage-3-large',
|
||||
embedding_columns: {
|
||||
'bad"col': { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' },
|
||||
} as never,
|
||||
}))).toThrow(EmbeddingColumnConfigError);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user