mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 09:52:22 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3487e4b255 | ||
|
|
159ddc3249 |
+43
-13
@@ -1,6 +1,7 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.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';
|
||||
@@ -183,8 +184,13 @@ export class EmbeddingDimMismatchError extends Error {
|
||||
* 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;
|
||||
@@ -238,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,
|
||||
@@ -253,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}`);
|
||||
}
|
||||
@@ -347,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();
|
||||
@@ -376,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 }.');
|
||||
@@ -521,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}`);
|
||||
@@ -554,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);
|
||||
}
|
||||
}
|
||||
@@ -589,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})).
|
||||
@@ -622,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
|
||||
@@ -644,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
|
||||
@@ -725,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, () =>
|
||||
@@ -805,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
|
||||
@@ -967,6 +993,7 @@ async function embedAllStale(
|
||||
afterUpdatedAt,
|
||||
}),
|
||||
...(sourceId && { sourceId }),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}),
|
||||
);
|
||||
if (batch.length === 0) {
|
||||
@@ -1019,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
|
||||
@@ -1090,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.`);
|
||||
|
||||
@@ -50,10 +50,6 @@ const PER_TASK_KEYS: Array<{ key: string; tier: ModelTier; description: string }
|
||||
{ key: 'models.eval.contradictions_judge', tier: 'utility', description: 'Contradiction probe judge (v0.34 temporal-aware)' },
|
||||
{ key: 'models.expansion', tier: 'utility', description: 'Query expansion for hybrid search' },
|
||||
{ key: 'models.chat', tier: 'reasoning', description: 'Default `gateway.chat()` model' },
|
||||
{ key: 'models.propose_takes', tier: 'reasoning', description: 'propose_takes claim extractor' },
|
||||
{ key: 'models.grade_takes', tier: 'reasoning', description: 'grade_takes verdict judge' },
|
||||
{ key: 'models.calibration_profile', tier: 'reasoning', description: 'Calibration profile generator' },
|
||||
{ key: 'models.brainstorm', tier: 'reasoning', description: '`gbrain brainstorm` orchestrator' },
|
||||
];
|
||||
|
||||
interface ModelEntry {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -61,10 +61,7 @@ export const MAX_OUTPUT_TOKENS_CEIL = 32_000;
|
||||
* (with a readable error) instead of the provider's opaque HTTP 400.
|
||||
*/
|
||||
export const ANTHROPIC_OUTPUT_CAPS: Record<string, number> = {
|
||||
'claude-fable-5': 64_000,
|
||||
'claude-opus-4-8': 32_000,
|
||||
'claude-opus-4-7': 32_000,
|
||||
'claude-sonnet-5': 64_000,
|
||||
'claude-sonnet-4-6': 64_000,
|
||||
'claude-haiku-4-5': 64_000,
|
||||
'claude-haiku-4-5-20251001': 64_000,
|
||||
|
||||
@@ -32,7 +32,6 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from '../engine.ts';
|
||||
import { resolveModel } from '../model-config.ts';
|
||||
import { chat as defaultChat, embedQuery, type ChatResult, type ChatOpts } from '../ai/gateway.ts';
|
||||
import { hybridSearch, hybridSearchCached } from '../search/hybrid.ts';
|
||||
import { fetchFar, type CloseRef, type FarPage } from './domain-bank.ts';
|
||||
@@ -539,14 +538,7 @@ async function _runBrainstormInner(
|
||||
const embedFn = opts.embedQueryFn ?? embedQuery;
|
||||
|
||||
// ---- Phase 0: cost preview + TTY grace ----
|
||||
// Tier-resolved (mirrors the cycle phases): honors models.brainstorm >
|
||||
// models.default > models.tier.reasoning; the fallback keeps stock
|
||||
// behavior identical (reasoning tier default IS claude-sonnet-4-6).
|
||||
const modelStr = opts.modelOverride ?? await resolveModel(engine, {
|
||||
configKey: 'models.brainstorm',
|
||||
tier: 'reasoning',
|
||||
fallback: 'anthropic:claude-sonnet-4-6',
|
||||
});
|
||||
const modelStr = opts.modelOverride ?? 'anthropic:claude-sonnet-4-6';
|
||||
const { aborted, estimate } = await previewCostAndWait({
|
||||
profile,
|
||||
model: modelStr,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
*/
|
||||
|
||||
import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
|
||||
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
|
||||
import { resolveModel } from '../model-config.ts';
|
||||
import { chat as gatewayChat } from '../ai/gateway.ts';
|
||||
import { TIER_DEFAULTS } from '../model-config.ts';
|
||||
import { gateVoice, type VoiceGateGenerator, type VoiceGateJudge } from '../calibration/voice-gate.ts';
|
||||
import { patternStatementTemplate, type PatternStatementSlots } from '../calibration/templates.ts';
|
||||
// v0.41 T10 — domain widening. The aggregator module resolves the active
|
||||
@@ -229,16 +229,7 @@ class CalibrationProfilePhase extends BaseCyclePhase {
|
||||
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
|
||||
const holder = opts.holder ?? 'garry';
|
||||
const promptVersion = opts.promptVersion ?? CALIBRATION_PROFILE_PROMPT_VERSION;
|
||||
// Resolved once (see propose-takes.ts for the chain): models.calibration_profile
|
||||
// > models.default > env > the gateway's chat model (itself resolved
|
||||
// through models.chat + the reasoning tier). Provider-prefixed per #2451
|
||||
// — a bare id would make gateway.chat() throw "missing a provider
|
||||
// prefix". Drives the generator's chat call, the budget label, and the
|
||||
// persisted model_id, so the three can never disagree.
|
||||
const modelId = opts.model ?? await resolveModel(engine, {
|
||||
configKey: 'models.calibration_profile',
|
||||
fallback: getChatModel(),
|
||||
});
|
||||
const modelId = opts.model ?? TIER_DEFAULTS.reasoning;
|
||||
const gradeCompletion = opts.gradeCompletion ?? 1.0;
|
||||
const patternsGenerator = opts.patternsGenerator ?? defaultPatternsGenerator;
|
||||
const biasTagsGenerator = opts.biasTagsGenerator ?? defaultBiasTagsGenerator;
|
||||
@@ -274,7 +265,6 @@ class CalibrationProfilePhase extends BaseCyclePhase {
|
||||
scorecard,
|
||||
holder,
|
||||
attempt,
|
||||
modelHint: modelId,
|
||||
...(feedback !== undefined ? { feedback } : {}),
|
||||
});
|
||||
return lines.join('\n');
|
||||
|
||||
@@ -36,9 +36,7 @@
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
|
||||
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
|
||||
import { resolveModel } from '../model-config.ts';
|
||||
import { splitProviderModelId } from '../model-id.ts';
|
||||
import { chat as gatewayChat } from '../ai/gateway.ts';
|
||||
import { GBrainError } from '../types.ts';
|
||||
import type { OperationContext } from '../operations.ts';
|
||||
import type { BrainEngine, Take, TakeResolution } from '../engine.ts';
|
||||
@@ -397,24 +395,7 @@ class GradeTakesPhase extends BaseCyclePhase {
|
||||
const autoResolve = opts.autoResolve ?? false; // D17 default OFF
|
||||
const autoResolveThreshold = opts.autoResolveThreshold ?? 0.95; // D12 conservative
|
||||
const resolvedByLabel = opts.resolvedByLabel ?? 'gbrain:grade_takes';
|
||||
// Resolve the judge model ONCE (see propose-takes.ts for the chain —
|
||||
// same label-vs-actual split fixed here: the judge call rode the
|
||||
// gateway's chat_model while the grade cache key, evidence signature,
|
||||
// and budget label recorded a hardcoded 4.6).
|
||||
// NOTE: changing the resolved judge model invalidates the grade cache
|
||||
// (judge_model_id is part of its key) — a one-time, budget-capped
|
||||
// re-grade wave that is CORRECT, since the actual judge did change.
|
||||
const judgeModelFull = opts.model ?? await resolveModel(engine, {
|
||||
configKey: 'models.grade_takes',
|
||||
fallback: getChatModel(),
|
||||
});
|
||||
// Bare tail for cache keys / evidence signatures / stored ids — the
|
||||
// grade cache has always been keyed on bare ids; the gateway default
|
||||
// resolves provider-prefixed, and normalizing preserves cache continuity
|
||||
// on stock installs (no spurious re-judge wave from a prefix change). A
|
||||
// genuinely different configured judge still invalidates, which is
|
||||
// correct. The FULL string drives the actual judge call.
|
||||
const judgeModelId = splitProviderModelId(judgeModelFull).model || judgeModelFull;
|
||||
const judgeModelId = opts.model ?? 'claude-sonnet-4-6';
|
||||
|
||||
const useEnsemble = opts.useEnsemble ?? false;
|
||||
const ensembleThreshold = opts.ensembleThreshold ?? 0.85;
|
||||
@@ -487,7 +468,7 @@ class GradeTakesPhase extends BaseCyclePhase {
|
||||
// Call the single-model judge. Errors on a single take log warning + continue.
|
||||
let verdict: JudgeVerdict;
|
||||
try {
|
||||
verdict = await judge({ take, evidence, modelHint: judgeModelFull });
|
||||
verdict = await judge({ take, evidence, modelHint: opts.model });
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
result.warnings.push(`judge failed on take ${take.id}: ${msg}`);
|
||||
|
||||
@@ -5,16 +5,11 @@
|
||||
* a tuned LLM extractor, writes the extracted gradeable claims to the
|
||||
* `take_proposals` queue. User accepts/rejects via `gbrain takes propose`.
|
||||
*
|
||||
* Idempotency contract (D17 schema spec; per-claim rows since migration v125):
|
||||
* Every scan of a (source_id, page_slug, content_hash, prompt_version)
|
||||
* tuple leaves at least one row — one per extracted claim, or a single
|
||||
* status='empty' sentinel when extraction yields nothing — so an unchanged
|
||||
* page never re-spends LLM tokens. Pre-v125 only proposal rows were
|
||||
* written: a zero-claim page never entered the cache and was re-extracted
|
||||
* on EVERY cycle (observed live: ~60 such pages × every cycle ≈ 1,400
|
||||
* wasted extractor calls / ~$15 per day — ~90% of total autopilot spend).
|
||||
* Bumping PROPOSE_TAKES_PROMPT_VERSION cleanly invalidates the cache so a
|
||||
* tuned prompt re-runs proposals on every page.
|
||||
* Idempotency contract (D17 schema spec):
|
||||
* The unique index on (source_id, page_slug, content_hash, prompt_version)
|
||||
* means an unchanged page never re-spends LLM tokens. Bumping
|
||||
* PROPOSE_TAKES_PROMPT_VERSION cleanly invalidates the cache so a tuned
|
||||
* prompt re-runs proposals on every page.
|
||||
*
|
||||
* F2 fence dedup:
|
||||
* The phase reads the page's existing `<!-- gbrain:takes:begin -->` fence
|
||||
@@ -45,7 +40,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
|
||||
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
|
||||
import { resolveModel } from '../model-config.ts';
|
||||
import { writeReceipt } from '../extract/receipt-writer.ts';
|
||||
import { upsertExtractRollup } from '../extract/rollup-writer.ts';
|
||||
import { GBrainError } from '../types.ts';
|
||||
@@ -313,18 +307,6 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
const promptVersion = opts.promptVersion ?? PROPOSE_TAKES_PROMPT_VERSION;
|
||||
const pageLimit = opts.pageLimit ?? 100;
|
||||
const skipPagesWithFence = opts.skipPagesWithFence ?? false;
|
||||
// Resolve the extractor model ONCE: models.propose_takes >
|
||||
// models.default > GBRAIN_MODEL env > the gateway's chat model (which
|
||||
// reconfigureGatewayWithEngine already resolved through models.chat +
|
||||
// the reasoning tier). One resolved provider-prefixed string drives the
|
||||
// actual chat call, the budget estimate, AND the stored model_id — so
|
||||
// the recorded model can never disagree with the model that ran (#2451
|
||||
// convention: stored ids are provider-prefixed, nested prefixes like
|
||||
// openrouter:anthropic/... stay intact).
|
||||
const extractorModelId = opts.model ?? await resolveModel(engine, {
|
||||
configKey: 'models.propose_takes',
|
||||
fallback: getChatModel(),
|
||||
});
|
||||
const proposalRunId = `propose-${new Date().toISOString().slice(0, 19).replace(/[-:T]/g, '')}-${randomUUID().slice(0, 8)}`;
|
||||
|
||||
const result: ProposeTakesResult = {
|
||||
@@ -348,6 +330,8 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
opts.reporter.start('propose_takes.pages' as never, pages.length);
|
||||
}
|
||||
|
||||
const modelId = opts.model ?? getChatModel();
|
||||
|
||||
for (const page of pages) {
|
||||
result.pages_scanned += 1;
|
||||
this.tick(opts);
|
||||
@@ -377,7 +361,7 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
|
||||
// Budget pre-check before the LLM call. Estimate: ~1500 input tokens + 500 output.
|
||||
const budget = this.checkBudget({
|
||||
modelId: extractorModelId,
|
||||
modelId,
|
||||
estimatedInputTokens: 1500,
|
||||
maxOutputTokens: 500,
|
||||
});
|
||||
@@ -396,7 +380,7 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
pagePath: page.slug,
|
||||
pageBody: body,
|
||||
existingTakes,
|
||||
modelHint: extractorModelId,
|
||||
modelHint: opts.model,
|
||||
});
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
@@ -404,42 +388,16 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Zero-claim scans MUST still enter the idempotency cache. Pre-v125
|
||||
// only proposal rows were written, so a page whose extraction yielded
|
||||
// no gradeable claims never got a row for its (page, content_hash) —
|
||||
// the cache check above missed on every subsequent cycle and the LLM
|
||||
// call was re-spent on the same unchanged page, forever. The sentinel
|
||||
// row (status='empty', empty claim_text) is invisible to the review
|
||||
// queue (pending_idx is partial on status='pending'); it exists only
|
||||
// so the cache check hits.
|
||||
if (proposals.length === 0) {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO take_proposals
|
||||
(source_id, page_slug, content_hash, prompt_version, proposal_run_id,
|
||||
status, claim_text, kind, holder, weight, domain, dedup_against_fence_rows, model_id)
|
||||
VALUES ($1, $2, $3, $4, $5, 'empty', '', 'none', 'brain', 0, NULL, NULL, $6)
|
||||
ON CONFLICT (source_id, page_slug, content_hash, prompt_version, md5(claim_text)) DO NOTHING`,
|
||||
[sourceId, page.slug, ch, promptVersion, proposalRunId, extractorModelId],
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Write proposals to take_proposals, one row per claim. The v125
|
||||
// idempotency index includes md5(claim_text), so a same-page
|
||||
// multi-claim run keeps EVERY claim — the pre-v125 four-column unique
|
||||
// index made claims 2..N conflict with claim 1 and ON CONFLICT DO
|
||||
// NOTHING silently dropped them (the review queue only ever saw the
|
||||
// first claim of each page version). RETURNING id keeps
|
||||
// proposals_inserted honest: it counts rows that actually landed,
|
||||
// not insert attempts.
|
||||
// Write proposals to take_proposals. Each row is a separate INSERT
|
||||
// because the composite idempotency key is on the per-page tuple — a
|
||||
// bulk UPSERT would collapse a same-page-multi-claim run into one row.
|
||||
for (const p of proposals) {
|
||||
const landed = await engine.executeRaw<{ id: number }>(
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO take_proposals
|
||||
(source_id, page_slug, content_hash, prompt_version, proposal_run_id,
|
||||
claim_text, kind, holder, weight, domain, dedup_against_fence_rows, model_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
ON CONFLICT (source_id, page_slug, content_hash, prompt_version, md5(claim_text)) DO NOTHING
|
||||
RETURNING id`,
|
||||
ON CONFLICT (source_id, page_slug, content_hash, prompt_version) DO NOTHING`,
|
||||
[
|
||||
sourceId,
|
||||
page.slug,
|
||||
@@ -452,10 +410,10 @@ class ProposeTakesPhase extends BaseCyclePhase {
|
||||
p.weight,
|
||||
p.domain ?? null,
|
||||
JSON.stringify(existingTakes),
|
||||
extractorModelId,
|
||||
modelId,
|
||||
],
|
||||
);
|
||||
if (landed.length > 0) result.proposals_inserted += 1;
|
||||
result.proposals_inserted += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,11 +58,8 @@ const SUMMARY_SLUG_RE = /^[a-z0-9][a-z0-9\-]*(\/[a-z0-9][a-z0-9\-]*)*$/;
|
||||
* resolver returns for known Anthropic aliases.
|
||||
*/
|
||||
const MODEL_CONTEXT_TOKENS: Record<string, number> = {
|
||||
'claude-fable-5': 1_000_000,
|
||||
'claude-opus-4-8': 1_000_000,
|
||||
'claude-opus-4-7': 1_000_000,
|
||||
'claude-opus-4-6': 1_000_000,
|
||||
'claude-sonnet-5': 1_000_000,
|
||||
'claude-sonnet-4-6': 200_000,
|
||||
'claude-sonnet-4-5': 200_000,
|
||||
'claude-haiku-4-5-20251001': 200_000,
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
@@ -5671,41 +5671,6 @@ export const MIGRATIONS: Migration[] = [
|
||||
`);
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 125,
|
||||
name: 'take_proposals_empty_scan_sentinels_and_per_claim_rows',
|
||||
// v0.42.x — kill the propose_takes rescan loop + stop dropping claims.
|
||||
//
|
||||
// Two defects, one schema touch:
|
||||
// 1. Zero-claim scans never entered the idempotency cache (only
|
||||
// proposal rows were written), so pages whose extraction yielded
|
||||
// nothing were re-extracted on EVERY cycle. Observed live: ~60
|
||||
// such pages per run ≈ 1,400 wasted extractor calls / ~$15 per
|
||||
// day — ~90% of total autopilot LLM spend. Fix: the phase now
|
||||
// writes a status='empty' sentinel row per zero-claim scan; the
|
||||
// status CHECK gains the 'empty' value. Sentinels are excluded
|
||||
// from the partial pending index, so the review queue never sees
|
||||
// them.
|
||||
// 2. The 4-column unique index collapsed a same-page multi-claim run
|
||||
// to its FIRST claim: rows 2..N conflicted and ON CONFLICT DO
|
||||
// NOTHING silently dropped them (verified live: exactly one row
|
||||
// per (page, hash) across 3 days of runs). Fix: the idempotency
|
||||
// index gains md5(claim_text) — per-claim rows, while the
|
||||
// 4-column prefix still serves the per-scan cache lookup.
|
||||
//
|
||||
// Existing data is index-safe by construction: the old index guaranteed
|
||||
// at most one row per 4-tuple, so the widened index has no duplicates
|
||||
// to trip on. The DROP+ADD CONSTRAINT pair is idempotent as a unit.
|
||||
idempotent: true,
|
||||
sql: `
|
||||
ALTER TABLE take_proposals DROP CONSTRAINT IF EXISTS take_proposals_status_check;
|
||||
ALTER TABLE take_proposals ADD CONSTRAINT take_proposals_status_check
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded','empty'));
|
||||
DROP INDEX IF EXISTS take_proposals_idempotency_idx;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS take_proposals_idempotency_idx
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version, md5(claim_text));
|
||||
`,
|
||||
},
|
||||
];
|
||||
|
||||
export const LATEST_VERSION = MIGRATIONS.length > 0
|
||||
|
||||
@@ -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.
|
||||
|
||||
+42
-22
@@ -40,6 +40,7 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -2230,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.
|
||||
@@ -2270,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;
|
||||
@@ -2288,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';
|
||||
|
||||
@@ -2327,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
|
||||
@@ -2377,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) {
|
||||
@@ -2394,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.
|
||||
@@ -2410,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);
|
||||
@@ -2463,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.
|
||||
@@ -2481,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`,
|
||||
@@ -2492,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
|
||||
@@ -2511,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
|
||||
@@ -2523,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 (
|
||||
@@ -2548,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
|
||||
@@ -2562,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)
|
||||
|
||||
@@ -762,7 +762,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
proposed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
proposal_run_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded','empty')),
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded')),
|
||||
claim_text TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
holder TEXT NOT NULL,
|
||||
@@ -777,7 +777,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
predicted_brier_bucket_n INTEGER
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS take_proposals_idempotency_idx
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version, md5(claim_text));
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version);
|
||||
CREATE INDEX IF NOT EXISTS take_proposals_pending_idx
|
||||
ON take_proposals (source_id, status, proposed_at DESC)
|
||||
WHERE status = 'pending';
|
||||
|
||||
+43
-22
@@ -50,6 +50,7 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -2380,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
|
||||
@@ -2413,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;
|
||||
@@ -2430,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';
|
||||
|
||||
@@ -2478,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
|
||||
@@ -2530,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) {
|
||||
@@ -2547,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).
|
||||
@@ -2565,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);
|
||||
@@ -2618,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) => {
|
||||
@@ -2639,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}
|
||||
@@ -2649,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
|
||||
@@ -2667,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
|
||||
@@ -2678,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 (
|
||||
@@ -2698,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
|
||||
@@ -2711,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})
|
||||
|
||||
@@ -1274,14 +1274,8 @@ CREATE INDEX IF NOT EXISTS calibration_profiles_published_idx
|
||||
WHERE published = true;
|
||||
|
||||
-- take_proposals: propose_takes phase queue. Idempotency cache via the
|
||||
-- composite unique index (source_id, page_slug, content_hash, prompt_version,
|
||||
-- md5(claim_text)) — the 4-column prefix is the per-scan cache key (mirrors
|
||||
-- v0.23 dream_verdicts); md5(claim_text) makes rows per-claim so multi-claim
|
||||
-- pages keep every claim (v125). status='empty' rows are zero-claim scan
|
||||
-- sentinels: they hold the cache slot for a page version whose extraction
|
||||
-- yielded nothing — the phase never re-spends the LLM call on that page
|
||||
-- version. Excluded from the partial pending index. proposal_run_id supports
|
||||
-- --rollback by run.
|
||||
-- composite unique index (source_id, page_slug, content_hash, prompt_version)
|
||||
-- mirrors v0.23 dream_verdicts. proposal_run_id supports --rollback by run.
|
||||
CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
|
||||
@@ -1292,7 +1286,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
proposed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
proposal_run_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded','empty')),
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded')),
|
||||
claim_text TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
holder TEXT NOT NULL,
|
||||
@@ -1307,7 +1301,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
predicted_brier_bucket_n INTEGER
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS take_proposals_idempotency_idx
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version, md5(claim_text));
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version);
|
||||
CREATE INDEX IF NOT EXISTS take_proposals_pending_idx
|
||||
ON take_proposals (source_id, status, proposed_at DESC)
|
||||
WHERE status = 'pending';
|
||||
|
||||
@@ -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.
|
||||
|
||||
+4
-10
@@ -1270,14 +1270,8 @@ CREATE INDEX IF NOT EXISTS calibration_profiles_published_idx
|
||||
WHERE published = true;
|
||||
|
||||
-- take_proposals: propose_takes phase queue. Idempotency cache via the
|
||||
-- composite unique index (source_id, page_slug, content_hash, prompt_version,
|
||||
-- md5(claim_text)) — the 4-column prefix is the per-scan cache key (mirrors
|
||||
-- v0.23 dream_verdicts); md5(claim_text) makes rows per-claim so multi-claim
|
||||
-- pages keep every claim (v125). status='empty' rows are zero-claim scan
|
||||
-- sentinels: they hold the cache slot for a page version whose extraction
|
||||
-- yielded nothing — the phase never re-spends the LLM call on that page
|
||||
-- version. Excluded from the partial pending index. proposal_run_id supports
|
||||
-- --rollback by run.
|
||||
-- composite unique index (source_id, page_slug, content_hash, prompt_version)
|
||||
-- mirrors v0.23 dream_verdicts. proposal_run_id supports --rollback by run.
|
||||
CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
|
||||
@@ -1288,7 +1282,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
proposed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
proposal_run_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded','empty')),
|
||||
CHECK (status IN ('pending','accepted','rejected','superseded')),
|
||||
claim_text TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
holder TEXT NOT NULL,
|
||||
@@ -1303,7 +1297,7 @@ CREATE TABLE IF NOT EXISTS take_proposals (
|
||||
predicted_brier_bucket_n INTEGER
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS take_proposals_idempotency_idx
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version, md5(claim_text));
|
||||
ON take_proposals (source_id, page_slug, content_hash, prompt_version);
|
||||
CREATE INDEX IF NOT EXISTS take_proposals_pending_idx
|
||||
ON take_proposals (source_id, status, proposed_at DESC)
|
||||
WHERE status = 'pending';
|
||||
|
||||
@@ -38,7 +38,6 @@ function buildMockEngine(opts: { scorecard: TakesScorecard }): {
|
||||
} {
|
||||
const captured: CapturedSql[] = [];
|
||||
const engine = {
|
||||
async getConfig() { return null; },
|
||||
kind: 'pglite',
|
||||
async getScorecard() {
|
||||
return opts.scorecard;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,7 +47,6 @@ function buildMockEngine(opts: { takes: Take[] }): {
|
||||
const captured: CapturedSql[] = [];
|
||||
const resolves: CapturedResolve[] = [];
|
||||
const engine = {
|
||||
async getConfig() { return null; },
|
||||
kind: 'pglite',
|
||||
async listTakes() {
|
||||
return opts.takes;
|
||||
|
||||
@@ -46,14 +46,12 @@ interface CapturedResolve {
|
||||
function buildMockEngine(opts: {
|
||||
takes: Take[];
|
||||
cachedGrades?: Set<string>; // composite-key strings already in take_grade_cache
|
||||
config?: Record<string, string>; // engine.getConfig plane (models.grade_takes etc.)
|
||||
}): { engine: BrainEngine; captured: CapturedSql[]; resolves: CapturedResolve[] } {
|
||||
const captured: CapturedSql[] = [];
|
||||
const resolves: CapturedResolve[] = [];
|
||||
const cached = opts.cachedGrades ?? new Set<string>();
|
||||
|
||||
const engine = {
|
||||
async getConfig(key: string) { return opts.config?.[key] ?? null; },
|
||||
kind: 'pglite',
|
||||
async listTakes() {
|
||||
return opts.takes;
|
||||
@@ -226,28 +224,6 @@ describe('runPhaseGradeTakes — phase integration', () => {
|
||||
expect(resolves).toHaveLength(0); // no canonical mutation
|
||||
});
|
||||
|
||||
test('models.grade_takes config drives the judge call; cache key stays bare-tailed', async () => {
|
||||
// Pre-fix the judge call rode the gateway's chat_model while the cache
|
||||
// key / budget label recorded a hardcoded 'claude-sonnet-4-6'. The phase
|
||||
// now resolves models.grade_takes; the judge gets the FULL string and
|
||||
// the cache row keys on the bare tail (continuity with historical rows).
|
||||
const takes = [buildTake({ id: 1, sinceDate: '2023-01-01' })];
|
||||
const { engine, captured } = buildMockEngine({
|
||||
takes,
|
||||
config: { 'models.grade_takes': 'anthropic:claude-sonnet-5' },
|
||||
});
|
||||
const hints: Array<string | undefined> = [];
|
||||
const judge: JudgeFn = async ({ modelHint }) => {
|
||||
hints.push(modelHint);
|
||||
return { verdict: 'correct', confidence: 0.9, reasoning: 'held' };
|
||||
};
|
||||
const result = await runPhaseGradeTakes(buildCtx(engine), { judge });
|
||||
expect(result.status).toBe('ok');
|
||||
expect(hints).toEqual(['anthropic:claude-sonnet-5']); // actual call gets the FULL string
|
||||
const inserts = captured.filter(c => c.sql.includes('INSERT INTO take_grade_cache'));
|
||||
expect(inserts[0]!.params[2]).toBe('claude-sonnet-5'); // judge_model_id is the bare tail
|
||||
});
|
||||
|
||||
test('D17: auto-resolve OFF by default — even high-confidence verdict does NOT mutate takes', async () => {
|
||||
const takes = [buildTake({ id: 1, sinceDate: '2023-01-01' })];
|
||||
const { engine, resolves } = buildMockEngine({ takes });
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
/**
|
||||
* propose_takes rescan-loop + dropped-claims regression tests (migration v125).
|
||||
*
|
||||
* Two live-observed defects, both fixed by the v125 schema + phase change:
|
||||
*
|
||||
* 1. RESCAN LOOP — a page whose extraction yielded zero claims never
|
||||
* entered the idempotency cache (only proposal rows were written), so
|
||||
* every cycle re-spent the extractor call on the same unchanged page.
|
||||
* Live impact: ~60 such pages × every cycle ≈ 1,400 wasted LLM calls
|
||||
* (~$15) per day — ~90% of total autopilot spend. Fix: status='empty'
|
||||
* sentinel row per zero-claim scan.
|
||||
*
|
||||
* 2. DROPPED CLAIMS — the 4-column unique index collapsed a same-page
|
||||
* multi-claim run to its first claim (rows 2..N conflicted, ON CONFLICT
|
||||
* DO NOTHING dropped them silently; verified live: exactly 1 row per
|
||||
* (page, hash) over 3 days). Fix: idempotency index gains
|
||||
* md5(claim_text).
|
||||
*
|
||||
* Hermetic: PGLite engine + injected extractor; no gateway, no LLM.
|
||||
*/
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { runPhaseProposeTakes, type ProposeTakesExtractor, type ProposedTake } from '../src/core/cycle/propose-takes.ts';
|
||||
import type { OperationContext } from '../src/core/operations.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
function ctx(): OperationContext {
|
||||
return {
|
||||
engine,
|
||||
remote: false,
|
||||
config: {} as OperationContext['config'],
|
||||
logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
|
||||
} as unknown as OperationContext;
|
||||
}
|
||||
|
||||
/** Extractor stub that counts invocations per page slug. */
|
||||
function countingExtractor(
|
||||
claimsBySlug: Record<string, ProposedTake[]>,
|
||||
): { extractor: ProposeTakesExtractor; calls: string[] } {
|
||||
const calls: string[] = [];
|
||||
const extractor: ProposeTakesExtractor = async ({ pagePath }) => {
|
||||
calls.push(pagePath);
|
||||
return claimsBySlug[pagePath] ?? [];
|
||||
};
|
||||
return { extractor, calls };
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
await engine.putPage('notes/zero-claims', {
|
||||
type: 'note',
|
||||
title: 'pure narrative',
|
||||
compiled_truth: 'A quiet walk in the park. Nothing opinionated happened at all today.',
|
||||
});
|
||||
await engine.putPage('notes/three-claims', {
|
||||
type: 'note',
|
||||
title: 'opinionated',
|
||||
compiled_truth: 'I bet acme-example wins the market. widget-co will struggle. fund-a is overexposed.',
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
describe('rescan loop — zero-claim scans enter the cache', () => {
|
||||
test('second run cache-hits: extractor is NOT called again on unchanged pages', async () => {
|
||||
const claims = {
|
||||
'notes/three-claims': [
|
||||
{ claim_text: 'acme-example wins the market', kind: 'bet' as const, holder: 'brain', weight: 0.7 },
|
||||
{ claim_text: 'widget-co will struggle', kind: 'take' as const, holder: 'brain', weight: 0.6 },
|
||||
{ claim_text: 'fund-a is overexposed', kind: 'take' as const, holder: 'brain', weight: 0.55 },
|
||||
],
|
||||
};
|
||||
|
||||
const first = countingExtractor(claims);
|
||||
const r1 = await runPhaseProposeTakes(ctx(), { extractor: first.extractor });
|
||||
expect(r1.status).toBe('ok');
|
||||
// Both pages extracted on the first pass.
|
||||
expect(first.calls).toContain('notes/zero-claims');
|
||||
expect(first.calls).toContain('notes/three-claims');
|
||||
|
||||
const second = countingExtractor(claims);
|
||||
const r2 = await runPhaseProposeTakes(ctx(), { extractor: second.extractor });
|
||||
expect(r2.status).toBe('ok');
|
||||
// THE regression: pre-fix the zero-claim page missed the cache every
|
||||
// run and was re-extracted here. (Run 1's receipt page legitimately
|
||||
// appears once — it's a new page — and its zero-claim scan now caches
|
||||
// too; pre-fix, receipts re-scanned forever as well.)
|
||||
expect(second.calls).not.toContain('notes/zero-claims');
|
||||
expect(second.calls).not.toContain('notes/three-claims');
|
||||
|
||||
// Run 2 inserted nothing, so no new receipt page exists: run 3 must be
|
||||
// fully quiescent — zero extractor calls, zero cache misses.
|
||||
const third = countingExtractor(claims);
|
||||
const r3 = await runPhaseProposeTakes(ctx(), { extractor: third.extractor });
|
||||
expect(r3.status).toBe('ok');
|
||||
expect(third.calls).toEqual([]);
|
||||
expect((r3.details as Record<string, unknown>).cache_misses).toBe(0);
|
||||
});
|
||||
|
||||
test('zero-claim scan wrote an "empty" sentinel invisible to the pending queue', async () => {
|
||||
const sentinel = await engine.executeRaw<{ status: string; claim_text: string }>(
|
||||
`SELECT status, claim_text FROM take_proposals WHERE page_slug = 'notes/zero-claims'`,
|
||||
[],
|
||||
);
|
||||
expect(sentinel.length).toBe(1);
|
||||
expect(sentinel[0].status).toBe('empty');
|
||||
expect(sentinel[0].claim_text).toBe('');
|
||||
const pending = await engine.executeRaw<{ n: number }>(
|
||||
`SELECT COUNT(*)::int AS n FROM take_proposals WHERE page_slug = 'notes/zero-claims' AND status = 'pending'`,
|
||||
[],
|
||||
);
|
||||
expect(Number(pending[0].n)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dropped claims — per-claim rows survive the idempotency index', () => {
|
||||
test('a 3-claim page stores 3 rows and reports an honest inserted count', async () => {
|
||||
const rows = await engine.executeRaw<{ claim_text: string }>(
|
||||
`SELECT claim_text FROM take_proposals WHERE page_slug = 'notes/three-claims' AND status = 'pending' ORDER BY id`,
|
||||
[],
|
||||
);
|
||||
// Pre-fix the 4-column unique index kept only the FIRST claim.
|
||||
expect(rows.length).toBe(3);
|
||||
expect(rows.map(r => r.claim_text)).toEqual([
|
||||
'acme-example wins the market',
|
||||
'widget-co will struggle',
|
||||
'fund-a is overexposed',
|
||||
]);
|
||||
});
|
||||
|
||||
test('content change re-extracts and stores the new version separately', async () => {
|
||||
await engine.putPage('notes/zero-claims', {
|
||||
type: 'note',
|
||||
title: 'pure narrative',
|
||||
compiled_truth: 'Updated: I now believe acme-example is undervalued and will re-rate within a year.',
|
||||
});
|
||||
const claims = {
|
||||
'notes/zero-claims': [
|
||||
{ claim_text: 'acme-example is undervalued', kind: 'take' as const, holder: 'brain', weight: 0.6 },
|
||||
],
|
||||
};
|
||||
const run = countingExtractor(claims);
|
||||
const r = await runPhaseProposeTakes(ctx(), { extractor: run.extractor });
|
||||
expect(r.status).toBe('ok');
|
||||
// Changed page re-extracts; the unchanged 3-claim page stays cached.
|
||||
expect(run.calls).toEqual(['notes/zero-claims']);
|
||||
expect((r.details as Record<string, unknown>).proposals_inserted).toBe(1);
|
||||
const all = await engine.executeRaw<{ status: string }>(
|
||||
`SELECT status FROM take_proposals WHERE page_slug = 'notes/zero-claims' ORDER BY id`,
|
||||
[],
|
||||
);
|
||||
// Old hash's sentinel + new hash's pending claim coexist.
|
||||
expect(all.map(r2 => r2.status).sort()).toEqual(['empty', 'pending']);
|
||||
});
|
||||
});
|
||||
@@ -41,16 +41,12 @@ interface CapturedSql {
|
||||
function buildMockEngine(opts: {
|
||||
pages: Page[];
|
||||
existingProposals?: Set<string>; // composite-key strings already in take_proposals
|
||||
config?: Record<string, string>; // engine.getConfig plane (models.tier.* etc.)
|
||||
}): { engine: BrainEngine; captured: CapturedSql[] } {
|
||||
const captured: CapturedSql[] = [];
|
||||
const existing = opts.existingProposals ?? new Set<string>();
|
||||
|
||||
const engine = {
|
||||
kind: 'pglite',
|
||||
async getConfig(key: string) {
|
||||
return opts.config?.[key] ?? null;
|
||||
},
|
||||
async listPages() {
|
||||
return opts.pages;
|
||||
},
|
||||
@@ -63,12 +59,7 @@ function buildMockEngine(opts: {
|
||||
if (existing.has(key)) return [{ id: 1 } as unknown as T];
|
||||
return [];
|
||||
}
|
||||
// INSERT ... RETURNING id — emulate a successful insert so the
|
||||
// honest proposals_inserted counter (counts RETURNING rows, not
|
||||
// attempts) sees the row land. Conflicted inserts would return [].
|
||||
if (sql.includes('INSERT INTO take_proposals') && sql.includes('RETURNING id')) {
|
||||
return [{ id: 1 } as unknown as T];
|
||||
}
|
||||
// INSERT — return nothing
|
||||
return [];
|
||||
},
|
||||
} as unknown as BrainEngine;
|
||||
@@ -276,29 +267,6 @@ describe('runPhaseProposeTakes — phase integration', () => {
|
||||
expect(inserts[0]!.params[9]).toBe('market'); // domain
|
||||
});
|
||||
|
||||
test('extractor model resolves through models.propose_takes config', async () => {
|
||||
// Pre-fix the phase's only model knob was the gateway chat model — there
|
||||
// was no per-phase config key. The phase now resolves once via
|
||||
// resolveModel(models.propose_takes > models.default > env > gateway
|
||||
// chat model); the extractor hint and the stored model_id must both
|
||||
// reflect the configured override (full provider-prefixed string, #2451).
|
||||
const pages = [buildPage({ slug: 'wiki/concepts/tier-routing', body: 'Tier-routed models will win.' })];
|
||||
const { engine, captured } = buildMockEngine({
|
||||
pages,
|
||||
config: { 'models.propose_takes': 'anthropic:claude-sonnet-5' },
|
||||
});
|
||||
const seen: Array<string | undefined> = [];
|
||||
const extractor: ProposeTakesExtractor = async ({ modelHint }) => {
|
||||
seen.push(modelHint);
|
||||
return [{ claim_text: 'tier-routed models win', kind: 'bet', holder: 'brain', weight: 0.7 }];
|
||||
};
|
||||
const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
|
||||
expect(result.status).toBe('ok');
|
||||
expect(seen).toEqual(['anthropic:claude-sonnet-5']); // chat call gets the FULL string
|
||||
const inserts = captured.filter(c => c.sql.includes('INSERT INTO take_proposals'));
|
||||
expect(inserts[0]!.params[11]).toBe('anthropic:claude-sonnet-5'); // stored model_id matches the call
|
||||
});
|
||||
|
||||
test('cache hit: page already in take_proposals is skipped', async () => {
|
||||
const body = 'A page that was already processed.';
|
||||
const pages = [buildPage({ slug: 'wiki/old-page', body })];
|
||||
|
||||
@@ -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