mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 02:12:40 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e044021ef | ||
|
|
553515c82c |
+13
-43
@@ -1,7 +1,6 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
|
||||
import type { ChunkInput, ResolvedColumn } from '../core/types.ts';
|
||||
import { resolveWriteColumnForEngine } from '../core/search/embedding-column.ts';
|
||||
import type { ChunkInput } from '../core/types.ts';
|
||||
import { chunkText } from '../core/chunkers/recursive.ts';
|
||||
import { createProgress, type ProgressReporter } from '../core/progress.ts';
|
||||
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
|
||||
@@ -184,13 +183,8 @@ 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, embeddingColumn?: ResolvedColumn): Promise<void> {
|
||||
async function preflightDimMismatch(engine: BrainEngine, dryRun: boolean): 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;
|
||||
@@ -244,12 +238,7 @@ 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.
|
||||
// #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);
|
||||
await preflightDimMismatch(engine, !!opts.dryRun);
|
||||
|
||||
const result: EmbedResult = {
|
||||
embedded: 0,
|
||||
@@ -264,7 +253,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, embeddingColumn);
|
||||
await embedPage(engine, s, !!opts.dryRun, result, opts.sourceId, opts.signal);
|
||||
} catch (e: unknown) {
|
||||
serr(` Error embedding ${s}: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
@@ -358,7 +347,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
|
||||
catchUp: opts.catchUp,
|
||||
pacer,
|
||||
paceMaxConcurrency,
|
||||
}, opts.signal, embeddingColumn);
|
||||
}, opts.signal);
|
||||
} finally {
|
||||
// E1: surface pacing telemetry (human + structured) when pacing was on.
|
||||
const snap = pacer.snapshot();
|
||||
@@ -387,7 +376,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, embeddingColumn);
|
||||
await embedPage(engine, opts.slug, !!opts.dryRun, result, opts.sourceId, opts.signal);
|
||||
return result;
|
||||
}
|
||||
throw new Error('No embed target specified. Pass { slug }, { slugs }, { all }, or { stale }.');
|
||||
@@ -532,13 +521,8 @@ 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}`);
|
||||
@@ -570,7 +554,7 @@ async function embedPage(
|
||||
}
|
||||
|
||||
if (inputs.length > 0) {
|
||||
await engine.upsertChunks(slug, inputs, chunkOpts);
|
||||
await engine.upsertChunks(slug, inputs, opts);
|
||||
chunks = await engine.getChunks(slug, opts);
|
||||
}
|
||||
}
|
||||
@@ -605,7 +589,7 @@ async function embedPage(
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
|
||||
await engine.upsertChunks(slug, updated, chunkOpts);
|
||||
await engine.upsertChunks(slug, updated, opts);
|
||||
// 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})).
|
||||
@@ -638,7 +622,6 @@ 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
|
||||
@@ -661,7 +644,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, embeddingColumn);
|
||||
return await embedAllStale(engine, sourceId, dryRun, result, onProgress, staleOpts, signature, signal);
|
||||
}
|
||||
|
||||
// --all path: pacer (no-op when off). E-1: lower the worker count to the
|
||||
@@ -742,10 +725,7 @@ 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, {
|
||||
...(pageSourceId && { sourceId: pageSourceId }),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
|
||||
// v0.41.31: stamp embedding provenance so a later model swap is
|
||||
// detectable as stale.
|
||||
await observed(pacer, () =>
|
||||
@@ -825,16 +805,10 @@ async function embedAllStale(
|
||||
},
|
||||
signature?: string,
|
||||
externalSignal?: AbortSignal,
|
||||
embeddingColumn?: ResolvedColumn,
|
||||
) {
|
||||
// D7: thread sourceId so source-scoped runs only count + visit
|
||||
// that source's NULL embeddings.
|
||||
// #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;
|
||||
const sourceOpt = sourceId ? { sourceId } : 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
|
||||
@@ -993,7 +967,6 @@ async function embedAllStale(
|
||||
afterUpdatedAt,
|
||||
}),
|
||||
...(sourceId && { sourceId }),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}),
|
||||
);
|
||||
if (batch.length === 0) {
|
||||
@@ -1046,10 +1019,7 @@ 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,
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
// 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
|
||||
@@ -1120,7 +1090,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, ...sourceOpt } : sourceOpt,
|
||||
signature ? { signature, ...(sourceId ? { sourceId } : {}) } : (sourceId ? { sourceId } : undefined),
|
||||
);
|
||||
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.`);
|
||||
|
||||
@@ -2059,6 +2059,8 @@ export async function registerBuiltinHandlers(
|
||||
sourceId,
|
||||
windowSeconds,
|
||||
brainDir: repoPath,
|
||||
// #2750: worker cancel/timeout/lock-loss propagates into the drain.
|
||||
abortSignal: job.signal,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof LockUnavailableError) {
|
||||
|
||||
@@ -576,16 +576,9 @@ 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 {
|
||||
const { resolveWriteColumnForEngine } = await import('../core/search/embedding-column.ts');
|
||||
const embeddingColumn = await resolveWriteColumnForEngine(engine);
|
||||
staleChars = await engine.sumStaleChunkChars({
|
||||
signature: currentEmbeddingSignature(),
|
||||
...(embeddingColumn && { embeddingColumn }),
|
||||
});
|
||||
staleChars = await engine.sumStaleChunkChars({ signature: currentEmbeddingSignature() });
|
||||
} catch {
|
||||
staleChars = 0;
|
||||
}
|
||||
|
||||
@@ -61,7 +61,6 @@ 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';
|
||||
|
||||
@@ -287,13 +286,9 @@ 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,
|
||||
|
||||
@@ -23,6 +23,10 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from '../engine.ts';
|
||||
import { anySignal } from '../abort-check.ts';
|
||||
|
||||
/** Fresh cleanup budget for the lock release after the window signal fires. */
|
||||
const LOCK_RELEASE_GRACE_MS = 5_000;
|
||||
|
||||
export interface ExtractAtomsDrainDeps {
|
||||
/**
|
||||
@@ -30,13 +34,13 @@ export interface ExtractAtomsDrainDeps {
|
||||
* via `withRefreshingLock`. MUST throw when the lock is held by another
|
||||
* process (e.g. `LockUnavailableError`) — the drain lets that propagate so
|
||||
* the caller can report `cycle_already_running` and exit, matching the
|
||||
* routine cycle's skip contract.
|
||||
* routine cycle's skip contract. The signal bounds lock acquisition too.
|
||||
*/
|
||||
withLock: <T>(work: () => Promise<T>) => Promise<T>;
|
||||
/** Process one bounded batch (rediscovers eligibility). Returns counts. */
|
||||
runBatch: () => Promise<{ extracted: number; skipped: number }>;
|
||||
withLock: <T>(work: () => Promise<T>, signal: AbortSignal) => Promise<T>;
|
||||
/** Process one batch. The signal fires at the drain wallclock deadline. */
|
||||
runBatch: (signal: AbortSignal) => Promise<{ extracted: number; skipped: number }>;
|
||||
/** Count remaining eligible-but-unextracted pages, or null on query error. */
|
||||
countRemaining: () => Promise<number | null>;
|
||||
countRemaining: (signal: AbortSignal) => Promise<number | null>;
|
||||
/** Injectable clock. Production: Date.now. */
|
||||
now: () => number;
|
||||
/** Optional progress sink (one line per batch). */
|
||||
@@ -48,6 +52,8 @@ export interface ExtractAtomsDrainOpts {
|
||||
windowMs: number;
|
||||
/** Hard cap on batches (belt-and-suspenders against a 0-progress loop). Default 1000. */
|
||||
maxBatches?: number;
|
||||
/** External caller cancellation (worker timeout / shutdown). */
|
||||
abortSignal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface ExtractAtomsDrainResult {
|
||||
@@ -68,35 +74,79 @@ export async function runExtractAtomsDrain(
|
||||
opts: ExtractAtomsDrainOpts,
|
||||
): Promise<ExtractAtomsDrainResult> {
|
||||
const maxBatches = opts.maxBatches ?? 1000;
|
||||
return deps.withLock(async () => {
|
||||
const deadline = deps.now() + opts.windowMs;
|
||||
const deadline = deps.now() + opts.windowMs;
|
||||
// #2750: the window used to be checked only BETWEEN batches, so one slow
|
||||
// batch (sequential LLM calls) or a hung lock/count/write overran it without
|
||||
// bound (observed window=120s → 282.5s). A real-time deadline signal now
|
||||
// cancels (Postgres) or abandons (PGLite, cooperative) whatever is in
|
||||
// flight; the injected clock still drives loop-boundary checks so the pure
|
||||
// loop stays unit-testable.
|
||||
const signal = anySignal(
|
||||
AbortSignal.timeout(Math.max(1, opts.windowMs)),
|
||||
opts.abortSignal,
|
||||
);
|
||||
const result: ExtractAtomsDrainResult = await deps.withLock(async () => {
|
||||
let extracted = 0;
|
||||
let skipped = 0;
|
||||
let batches = 0;
|
||||
let stopped: ExtractAtomsDrainResult['stopped'] = 'window';
|
||||
|
||||
while (deps.now() < deadline) {
|
||||
while (deps.now() < deadline && !signal.aborted) {
|
||||
if (batches >= maxBatches) { stopped = 'max_batches'; break; }
|
||||
|
||||
const before = await deps.countRemaining();
|
||||
let before: number | null;
|
||||
try {
|
||||
before = await deps.countRemaining(signal);
|
||||
} catch (err) {
|
||||
if (signal.aborted) break;
|
||||
throw err;
|
||||
}
|
||||
if (before === 0) { stopped = 'drained'; break; }
|
||||
|
||||
const r = await deps.runBatch();
|
||||
// The backlog count consumed the same wallclock budget — re-check so a
|
||||
// slow count can't hand the batch a window that already expired.
|
||||
if (deps.now() >= deadline || signal.aborted) break;
|
||||
|
||||
let r: { extracted: number; skipped: number };
|
||||
try {
|
||||
r = await deps.runBatch(signal);
|
||||
} catch (err) {
|
||||
if (signal.aborted) break;
|
||||
throw err;
|
||||
}
|
||||
extracted += r.extracted;
|
||||
skipped += r.skipped;
|
||||
batches++;
|
||||
deps.onBatch?.({ batch: batches, extracted: r.extracted, remaining: before });
|
||||
|
||||
// A deadline abort inside the batch can surface as zero progress;
|
||||
// window exhaustion wins over the generic no_progress label.
|
||||
if (deps.now() >= deadline || signal.aborted) break;
|
||||
|
||||
// Stop if a batch made zero forward progress — extraction is failing or
|
||||
// everything left is ineligible (e.g. all skipped). Prevents a hot loop
|
||||
// that spends budget without draining.
|
||||
if (r.extracted === 0 && r.skipped === 0) { stopped = 'no_progress'; break; }
|
||||
}
|
||||
|
||||
const remaining = await deps.countRemaining();
|
||||
// After the window elapsed, don't spend more unbounded time on a final
|
||||
// count — report remaining as unknown instead of overrunning further.
|
||||
const windowElapsed = signal.aborted || deps.now() >= deadline;
|
||||
let remaining: number | null = null;
|
||||
if (!windowElapsed) {
|
||||
try {
|
||||
remaining = await deps.countRemaining(signal);
|
||||
} catch (err) {
|
||||
if (!signal.aborted) throw err;
|
||||
}
|
||||
}
|
||||
if (remaining === 0) stopped = 'drained';
|
||||
return { phase: 'extract_atoms', status: 'ok', extracted, skipped, remaining, batches, stopped };
|
||||
});
|
||||
}, signal);
|
||||
// Internal window expiry is a normal partial result. An EXTERNAL abort
|
||||
// (worker cancel/timeout/shutdown) must reject so Minion records the abort.
|
||||
if (opts.abortSignal?.aborted) throw opts.abortSignal.reason;
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Shared wiring helper (v0.42.x #1685 DECISION 5A) ──────────────────────
|
||||
@@ -134,6 +184,8 @@ export interface DrainForSourceOpts {
|
||||
maxBatches?: number;
|
||||
/** Optional per-batch progress sink (stderr line in dream; job progress in the handler). */
|
||||
onBatch?: ExtractAtomsDrainDeps['onBatch'];
|
||||
/** Worker cancellation / shutdown signal (Minion `job.signal`). */
|
||||
abortSignal?: AbortSignal;
|
||||
}
|
||||
|
||||
export async function runExtractAtomsDrainForSource(
|
||||
@@ -149,12 +201,17 @@ export async function runExtractAtomsDrainForSource(
|
||||
|
||||
return runExtractAtomsDrain(
|
||||
{
|
||||
withLock: (work) => withRefreshingLock(engine, lockId, work, { ttlMinutes: 5 }),
|
||||
runBatch: async () => {
|
||||
withLock: (work, signal) => withRefreshingLock(engine, lockId, work, {
|
||||
ttlMinutes: 5,
|
||||
signal,
|
||||
releaseTimeoutMs: LOCK_RELEASE_GRACE_MS,
|
||||
}),
|
||||
runBatch: async (signal) => {
|
||||
const r = await runPhaseExtractAtoms(engine, {
|
||||
sourceId: extractionSourceId,
|
||||
dryRun: false,
|
||||
brainDir: opts.brainDir,
|
||||
abortSignal: signal,
|
||||
});
|
||||
const d = (r.details ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
@@ -162,10 +219,14 @@ export async function runExtractAtomsDrainForSource(
|
||||
skipped: Number(d.duplicates_skipped ?? 0),
|
||||
};
|
||||
},
|
||||
countRemaining: () => countExtractAtomsBacklog(engine, extractionSourceId),
|
||||
countRemaining: (signal) => countExtractAtomsBacklog(engine, extractionSourceId, signal),
|
||||
now: Date.now,
|
||||
onBatch: opts.onBatch,
|
||||
},
|
||||
{ windowMs: opts.windowSeconds * 1000, maxBatches: opts.maxBatches },
|
||||
{
|
||||
windowMs: opts.windowSeconds * 1000,
|
||||
maxBatches: opts.maxBatches,
|
||||
abortSignal: opts.abortSignal,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,10 @@ import { createHash } from 'crypto';
|
||||
import { slugifySegment } from '../sync.ts';
|
||||
|
||||
const DEFAULT_BUDGET_USD = 0.3;
|
||||
// #2750: fresh wallclock budget for the receipt/rollup bookkeeping writes when
|
||||
// the caller's deadline already fired — committed atoms must not lose their
|
||||
// cost/receipt trail, but the writes can't be unbounded either.
|
||||
const BOOKKEEPING_GRACE_MS = 5_000;
|
||||
|
||||
// v0.42+ TODO: read atom_type enum from active pack manifest at runtime.
|
||||
const ATOM_TYPES = [
|
||||
@@ -155,6 +159,13 @@ export interface ExtractAtomsOpts {
|
||||
* `heartbeat()` on the passed reporter.
|
||||
*/
|
||||
progress?: ProgressReporter;
|
||||
/**
|
||||
* #2750: caller deadline/cancellation. Forwarded to every gateway call and
|
||||
* DB query/write so the drain window bounds real lifetime, plus a
|
||||
* cooperative between-item check (the PGLite path, where query abort only
|
||||
* abandons the waiter).
|
||||
*/
|
||||
abortSignal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface ExtractedAtom {
|
||||
@@ -212,6 +223,7 @@ export async function discoverExtractablePages(
|
||||
engine: BrainEngine,
|
||||
sourceId: string,
|
||||
affectedSlugs?: string[],
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<DiscoveredPage[]> {
|
||||
const hasFilter = Array.isArray(affectedSlugs) && affectedSlugs.length > 0;
|
||||
const sql = `
|
||||
@@ -251,13 +263,16 @@ export async function discoverExtractablePages(
|
||||
slug: string;
|
||||
compiled_truth: string;
|
||||
content_hash: string;
|
||||
}>(sql, params);
|
||||
}>(sql, params, { signal: abortSignal });
|
||||
return rows.map((r) => ({
|
||||
slug: r.slug,
|
||||
content: r.compiled_truth,
|
||||
contentHash: r.content_hash,
|
||||
}));
|
||||
} catch (err) {
|
||||
// A deadline abort is not a fail-soft condition — propagate so the
|
||||
// caller stops instead of proceeding with an empty page list.
|
||||
if (abortSignal?.aborted) throw err;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[extract_atoms] page-discovery query failed: ${msg}`);
|
||||
return []; // fail-soft: transcript path still proceeds
|
||||
@@ -282,6 +297,7 @@ export async function discoverExtractablePages(
|
||||
export async function countExtractAtomsBacklog(
|
||||
engine: BrainEngine,
|
||||
sourceId?: string,
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<number | null> {
|
||||
try {
|
||||
// Two modes: scoped (the phase's per-source `remaining`) vs brain-wide
|
||||
@@ -321,9 +337,10 @@ export async function countExtractAtomsBacklog(
|
||||
const params = scoped
|
||||
? [sourceId, extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION]
|
||||
: [extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION];
|
||||
const rows = await engine.executeRaw<{ cnt: string | number }>(sql, params);
|
||||
const rows = await engine.executeRaw<{ cnt: string | number }>(sql, params, { signal: abortSignal });
|
||||
return Number(rows[0]?.cnt ?? 0);
|
||||
} catch (err) {
|
||||
if (abortSignal?.aborted) throw err;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[extract_atoms] backlog count failed: ${msg}`);
|
||||
return null;
|
||||
@@ -350,6 +367,7 @@ export async function atomsExistingForHashes(
|
||||
engine: BrainEngine,
|
||||
sourceId: string,
|
||||
contentHash16s: string[],
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<Set<string>> {
|
||||
if (contentHash16s.length === 0) return new Set();
|
||||
try {
|
||||
@@ -361,9 +379,11 @@ export async function atomsExistingForHashes(
|
||||
AND deleted_at IS NULL
|
||||
AND frontmatter->>'source_hash' = ANY($2::text[])`,
|
||||
[sourceId, contentHash16s],
|
||||
{ signal: abortSignal },
|
||||
);
|
||||
return new Set(rows.map(r => r.h));
|
||||
} catch (err) {
|
||||
if (abortSignal?.aborted) throw err;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[extract_atoms] batch idempotency check failed (assuming none extracted): ${msg}`);
|
||||
return new Set();
|
||||
@@ -384,6 +404,7 @@ export async function runPhaseExtractAtoms(
|
||||
): Promise<PhaseResult> {
|
||||
const sourceId = opts.sourceId ?? 'default';
|
||||
const chat = opts._chat ?? gatewayChat;
|
||||
if (opts.abortSignal?.aborted) throw opts.abortSignal.reason;
|
||||
|
||||
// 1a. Get transcripts (test seam OR production discovery).
|
||||
// v0.41.2.1: config loader switched to loadConfigWithEngine() so the
|
||||
@@ -425,7 +446,7 @@ export async function runPhaseExtractAtoms(
|
||||
if (opts._pages !== undefined) {
|
||||
pages = opts._pages;
|
||||
} else {
|
||||
pages = await discoverExtractablePages(engine, sourceId, opts.affectedSlugs);
|
||||
pages = await discoverExtractablePages(engine, sourceId, opts.affectedSlugs, opts.abortSignal);
|
||||
}
|
||||
|
||||
// 2. Apply transcript-side source-hash idempotency in ONE batch query
|
||||
@@ -437,7 +458,7 @@ export async function runPhaseExtractAtoms(
|
||||
// Surface a heartbeat before the batch query so even an instant
|
||||
// short-circuit shows a sign of life (closes Issue 2 silent-phase pain).
|
||||
opts.progress?.heartbeat(`checking existing atoms for ${allHashes16.length} transcripts`);
|
||||
const existingHashes = await atomsExistingForHashes(engine, sourceId, allHashes16);
|
||||
const existingHashes = await atomsExistingForHashes(engine, sourceId, allHashes16, opts.abortSignal);
|
||||
for (const t of transcripts) {
|
||||
if (existingHashes.has(t.contentHash.slice(0, 16))) {
|
||||
duplicatesSkipped++;
|
||||
@@ -501,6 +522,7 @@ export async function runPhaseExtractAtoms(
|
||||
const failures: Array<{ source: string; error: string }> = [];
|
||||
let estimatedSpendUsd = 0;
|
||||
const budgetCap = DEFAULT_BUDGET_USD;
|
||||
let deadlineAborted = false;
|
||||
|
||||
// v0.41.19.0 (T3): throttled yield helper. Fires `opts.yieldDuringPhase`
|
||||
// every 30s. Cycle.ts threads `buildYieldDuringPhase(lock, outer)` so
|
||||
@@ -526,6 +548,12 @@ export async function runPhaseExtractAtoms(
|
||||
}
|
||||
|
||||
for (const item of work) {
|
||||
// #2750: cooperative between-item abort. Works on every engine — this is
|
||||
// the primary bound on PGLite, where query abort only abandons the waiter.
|
||||
if (opts.abortSignal?.aborted) {
|
||||
deadlineAborted = true;
|
||||
break;
|
||||
}
|
||||
await maybeYield();
|
||||
if (estimatedSpendUsd >= budgetCap) {
|
||||
if (item.kind === 'transcript') transcriptsSkipped++;
|
||||
@@ -544,16 +572,22 @@ export async function runPhaseExtractAtoms(
|
||||
},
|
||||
],
|
||||
maxTokens: 2000,
|
||||
abortSignal: opts.abortSignal,
|
||||
});
|
||||
// Rough cost estimate — Haiku at ~$0.80/M input + $4/M output.
|
||||
// A completed gateway call is billable even if the deadline fires
|
||||
// immediately afterward, so record usage BEFORE the abort check.
|
||||
estimatedSpendUsd +=
|
||||
(result.usage.input_tokens * 0.8 + result.usage.output_tokens * 4.0) / 1_000_000;
|
||||
if (opts.abortSignal?.aborted) {
|
||||
deadlineAborted = true;
|
||||
break;
|
||||
}
|
||||
// Post-await yield: closes the "long LLM call past TTL" hazard
|
||||
// codex flagged. The 30s throttle inside maybeYield bounds the
|
||||
// actual refresh rate so this is cheap when calls are fast.
|
||||
await maybeYield();
|
||||
|
||||
// Rough cost estimate — Haiku at ~$0.80/M input + $4/M output
|
||||
estimatedSpendUsd +=
|
||||
(result.usage.input_tokens * 0.8 + result.usage.output_tokens * 4.0) / 1_000_000;
|
||||
|
||||
const atoms = parseAtomsResponse(result.text);
|
||||
if (atoms.length === 0) {
|
||||
if (item.kind === 'transcript') transcriptsProcessed++;
|
||||
@@ -592,7 +626,7 @@ export async function runPhaseExtractAtoms(
|
||||
},
|
||||
timeline: '',
|
||||
},
|
||||
{ sourceId },
|
||||
{ sourceId, signal: opts.abortSignal },
|
||||
);
|
||||
totalAtomsExtracted++;
|
||||
}
|
||||
@@ -605,6 +639,11 @@ export async function runPhaseExtractAtoms(
|
||||
// Reporter rate-limits to ~1 line/sec; safe to tick every iter.
|
||||
opts.progress?.tick(1, `${totalAtomsExtracted} atoms / ${duplicatesSkipped} skipped`);
|
||||
} catch (err) {
|
||||
// A deadline abort is a partial result, not a per-item failure.
|
||||
if (opts.abortSignal?.aborted) {
|
||||
deadlineAborted = true;
|
||||
break;
|
||||
}
|
||||
failures.push({
|
||||
source: originLabel,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
@@ -615,6 +654,12 @@ export async function runPhaseExtractAtoms(
|
||||
// v0.42 Wave B2: write extract receipt + rollup row when the phase
|
||||
// actually extracted atoms. Both are best-effort per F-OUT-19 —
|
||||
// audit-trail / search-visibility surfaces don't block the phase result.
|
||||
//
|
||||
// #2750: bookkeeping runs on a FRESH short grace signal, never the caller's
|
||||
// work deadline — the deadline may have already fired (partial run) and
|
||||
// committed atoms must not lose their receipt/cost trail; but the writes
|
||||
// stay bounded so the overrun is capped at the grace window.
|
||||
const bookkeepingSignal = opts.dryRun ? undefined : AbortSignal.timeout(BOOKKEEPING_GRACE_MS);
|
||||
if (!opts.dryRun && totalAtomsExtracted > 0) {
|
||||
const runId = `atoms-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;
|
||||
try {
|
||||
@@ -629,19 +674,24 @@ export async function runPhaseExtractAtoms(
|
||||
summary:
|
||||
`Extracted ${totalAtomsExtracted} atoms from ` +
|
||||
`${transcriptsProcessed} transcripts + ${pagesProcessed} pages.`,
|
||||
});
|
||||
}, { signal: bookkeepingSignal });
|
||||
} catch (err) {
|
||||
console.error(`[extract_atoms] receipt write failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
if (!opts.dryRun) {
|
||||
await upsertExtractRollup(engine, {
|
||||
kind: 'atoms',
|
||||
source_id: sourceId,
|
||||
cost_delta: estimatedSpendUsd,
|
||||
round_completed_delta: failures.length === 0 ? 1 : 0,
|
||||
halt_delta: failures.length > 0 ? 1 : 0,
|
||||
});
|
||||
try {
|
||||
await upsertExtractRollup(engine, {
|
||||
kind: 'atoms',
|
||||
source_id: sourceId,
|
||||
cost_delta: estimatedSpendUsd,
|
||||
// A deadline-truncated run is not a completed round.
|
||||
round_completed_delta: failures.length === 0 && !deadlineAborted ? 1 : 0,
|
||||
halt_delta: failures.length > 0 ? 1 : 0,
|
||||
}, { signal: bookkeepingSignal });
|
||||
} catch (err) {
|
||||
console.error(`[extract_atoms] rollup write failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -670,6 +720,7 @@ export async function runPhaseExtractAtoms(
|
||||
budget_usd: budgetCap,
|
||||
source_id: sourceId,
|
||||
dry_run: opts.dryRun ?? false,
|
||||
deadline_aborted: deadlineAborted,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+50
-22
@@ -26,7 +26,8 @@ import type { BrainEngine } from './engine.ts';
|
||||
|
||||
export interface DbLockHandle {
|
||||
id: string;
|
||||
release: () => Promise<void>;
|
||||
/** Optional signal bounds the release DELETE (deadline-bound callers). */
|
||||
release: (signal?: AbortSignal) => Promise<void>;
|
||||
refresh: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -173,6 +174,7 @@ export async function tryAcquireDbLock(
|
||||
engine: BrainEngine,
|
||||
lockId: string,
|
||||
ttlMinutes: number = DEFAULT_TTL_MINUTES,
|
||||
opts: { signal?: AbortSignal } = {},
|
||||
): Promise<DbLockHandle | null> {
|
||||
const pid = process.pid;
|
||||
const host = hostname();
|
||||
@@ -205,20 +207,26 @@ export async function tryAcquireDbLock(
|
||||
// `gbrain sync --break-lock --max-age <s>` uses last_refreshed_at (not
|
||||
// acquired_at) to identify wedged-but-alive holders without stealing
|
||||
// healthy long-running holders that are actively refreshing.
|
||||
const rows: Array<{ id: string }> = await sql`
|
||||
INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
|
||||
VALUES (${lockId}, ${pid}, ${host}, NOW(), NOW() + ${ttl}::interval, NOW())
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET holder_pid = ${pid},
|
||||
holder_host = ${host},
|
||||
acquired_at = NOW(),
|
||||
ttl_expires_at = NOW() + ${ttl}::interval,
|
||||
last_refreshed_at = NOW()
|
||||
WHERE gbrain_cycle_locks.ttl_expires_at < NOW()
|
||||
AND (gbrain_cycle_locks.last_refreshed_at IS NULL
|
||||
OR gbrain_cycle_locks.last_refreshed_at < NOW() - ${stealGraceSeconds} * INTERVAL '1 second')
|
||||
RETURNING id
|
||||
`;
|
||||
// #2750: routed through executeRaw so a deadline-bound caller's signal
|
||||
// can cancel a hung acquire (pool exhaustion). Cancellation is
|
||||
// transactional; in the rare ambiguous-commit case the row's TTL is the
|
||||
// backstop (drain locks use a short 5-minute TTL).
|
||||
const rows = await engine.executeRaw<{ id: string }>(
|
||||
`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
|
||||
VALUES ($1, $2, $3, NOW(), NOW() + $4::interval, NOW())
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET holder_pid = $2,
|
||||
holder_host = $3,
|
||||
acquired_at = NOW(),
|
||||
ttl_expires_at = NOW() + $4::interval,
|
||||
last_refreshed_at = NOW()
|
||||
WHERE gbrain_cycle_locks.ttl_expires_at < NOW()
|
||||
AND (gbrain_cycle_locks.last_refreshed_at IS NULL
|
||||
OR gbrain_cycle_locks.last_refreshed_at < NOW() - $5 * INTERVAL '1 second')
|
||||
RETURNING id`,
|
||||
[lockId, pid, host, ttl, stealGraceSeconds],
|
||||
{ signal: opts.signal },
|
||||
);
|
||||
if (rows.length === 0) return null;
|
||||
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
|
||||
await sql`
|
||||
@@ -241,12 +249,17 @@ export async function tryAcquireDbLock(
|
||||
[ttl, lockId, pid],
|
||||
);
|
||||
},
|
||||
release: async () => {
|
||||
release: async (signal?: AbortSignal) => {
|
||||
deregister();
|
||||
await sql`
|
||||
DELETE FROM gbrain_cycle_locks
|
||||
WHERE id = ${lockId} AND holder_pid = ${pid}
|
||||
`;
|
||||
// Direct session pool (same rationale as refresh, #1794) + optional
|
||||
// signal so a deadline-bound caller's release can't hang forever on
|
||||
// an exhausted pooler. TTL is the backstop if the DELETE is cancelled.
|
||||
await engine.executeRawDirect(
|
||||
`DELETE FROM gbrain_cycle_locks
|
||||
WHERE id = $1 AND holder_pid = $2`,
|
||||
[lockId, pid],
|
||||
{ signal },
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -303,6 +316,11 @@ export async function tryAcquireDbLock(
|
||||
const first = await acquireOnce();
|
||||
if (first) return first;
|
||||
|
||||
// #2750: deadline-bound callers prefer an honest busy result over the
|
||||
// best-effort same-host takeover below, whose inspect/delete/retry calls
|
||||
// are not signal-bounded. The initial upsert already reclaims expired locks.
|
||||
if (opts.signal) return null;
|
||||
|
||||
// v0.42 (#1780 Gap 3): the lock is held and its TTL hasn't expired (the
|
||||
// upsert's ON CONFLICT ... WHERE ttl_expires_at < NOW() returned no row).
|
||||
// If the holder is on THIS host, provably dead, and past the grace window,
|
||||
@@ -796,6 +814,10 @@ export interface WithRefreshingLockOpts {
|
||||
ttlMinutes?: number;
|
||||
/** Heartbeat-fail threshold in ms — abort if SELECT 1 takes longer. Default 30000. */
|
||||
heartbeatTimeoutMs?: number;
|
||||
/** #2750: bound lock acquisition with the caller's deadline signal. */
|
||||
signal?: AbortSignal;
|
||||
/** Fresh cleanup budget for the release DELETE when `signal` is set. Default 5000. */
|
||||
releaseTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -815,7 +837,7 @@ export async function withRefreshingLock<T>(
|
||||
// Refresh 6x per TTL window so a missed tick doesn't expire the lock.
|
||||
const refreshIntervalMs = Math.max(15000, (ttlMinutes * 60 * 1000) / 6);
|
||||
|
||||
const handle = await tryAcquireDbLock(engine, lockId, ttlMinutes);
|
||||
const handle = await tryAcquireDbLock(engine, lockId, ttlMinutes, { signal: opts.signal });
|
||||
if (!handle) throw new LockUnavailableError(lockId);
|
||||
|
||||
let healthOk = true;
|
||||
@@ -854,7 +876,13 @@ export async function withRefreshingLock<T>(
|
||||
return await work();
|
||||
} finally {
|
||||
clearInterval(interval);
|
||||
try { await handle.release(); } catch { /* idempotent */ }
|
||||
// #2750: when the caller is deadline-bound, its work signal may already
|
||||
// have fired — release on a FRESH short grace signal so cleanup neither
|
||||
// inherits the spent deadline nor hangs unbounded. TTL is the backstop.
|
||||
const releaseSignal = opts.signal
|
||||
? AbortSignal.timeout(opts.releaseTimeoutMs ?? 5_000)
|
||||
: undefined;
|
||||
try { await handle.release(releaseSignal); } catch { /* idempotent; TTL backstop */ }
|
||||
if (!healthOk) {
|
||||
// Surface that the heartbeat detected backend trouble — caller can
|
||||
// log to the connection-events audit if desired.
|
||||
|
||||
+2
-13
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput, ResolvedColumn } from './types.ts';
|
||||
import type { ChunkInput } 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,13 +61,6 @@ 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`
|
||||
@@ -163,7 +156,6 @@ export async function embedStaleForSource(
|
||||
afterPageId,
|
||||
afterChunkIndex,
|
||||
sourceId,
|
||||
...(opts.embeddingColumn && { embeddingColumn: opts.embeddingColumn }),
|
||||
}),
|
||||
);
|
||||
if (batch.length === 0) {
|
||||
@@ -231,10 +223,7 @@ 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,
|
||||
...(opts.embeddingColumn && { embeddingColumn: opts.embeddingColumn }),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
// 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
|
||||
|
||||
+12
-23
@@ -12,7 +12,6 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
CodeEdgeInput, CodeEdgeResult,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
@@ -697,8 +696,16 @@ export interface BrainEngine {
|
||||
* is included in the INSERT column list so ON CONFLICT (source_id, slug)
|
||||
* DO UPDATE actually targets the intended row instead of fabricating a
|
||||
* duplicate at (default, slug). Multi-source brains MUST pass sourceId.
|
||||
*
|
||||
* `opts.signal` (#2750): optional cancellation for deadline-bound writers.
|
||||
* Postgres cancels the in-flight statement; PGLite pre-checks only (query
|
||||
* cancellation is not possible in-process — cooperative abort between calls).
|
||||
*/
|
||||
putPage(slug: string, page: PageInput, opts?: { sourceId?: string }): Promise<Page>;
|
||||
putPage(
|
||||
slug: string,
|
||||
page: PageInput,
|
||||
opts?: { sourceId?: string; signal?: AbortSignal },
|
||||
): Promise<Page>;
|
||||
/**
|
||||
* v0.41.13 (#1309) — identity-based dedup pre-check for the import pipeline.
|
||||
*
|
||||
@@ -988,13 +995,8 @@ 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; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void>;
|
||||
upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & 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
|
||||
@@ -1011,13 +1013,8 @@ 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; embeddingColumn?: ResolvedColumn }): Promise<number>;
|
||||
countStaleChunks(opts?: { sourceId?: string; signature?: string }): Promise<number>;
|
||||
/**
|
||||
* Sum of LENGTH(chunk_text) over stale chunks — the character-count
|
||||
* backlog the embed phase / embed-backfill will process. Sibling of
|
||||
@@ -1031,13 +1028,8 @@ 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; embeddingColumn?: ResolvedColumn }): Promise<number>;
|
||||
sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): 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
|
||||
@@ -1085,9 +1077,6 @@ 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
|
||||
|
||||
@@ -187,6 +187,7 @@ function buildReceiptFrontmatter(input: ExtractReceiptInput): Record<string, unk
|
||||
export async function writeReceipt(
|
||||
engine: BrainEngine,
|
||||
input: ExtractReceiptInput,
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<{ slug: string; page: Page }> {
|
||||
const slug = receiptSlug(input);
|
||||
const title = `${input.kind} — ${input.round} — ${input.source_id}`;
|
||||
@@ -201,7 +202,7 @@ export async function writeReceipt(
|
||||
compiled_truth,
|
||||
frontmatter,
|
||||
},
|
||||
{ sourceId: input.source_id },
|
||||
{ sourceId: input.source_id, signal: opts?.signal },
|
||||
);
|
||||
|
||||
return { slug, page };
|
||||
|
||||
@@ -70,6 +70,7 @@ function today(): string {
|
||||
export async function upsertExtractRollup(
|
||||
engine: BrainEngine,
|
||||
input: RollupUpsertInput,
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
const day = input.day ?? today();
|
||||
const cost = input.cost_delta ?? 0;
|
||||
@@ -96,9 +97,12 @@ export async function upsertExtractRollup(
|
||||
rollup_write_failures = extract_rollup_7d.rollup_write_failures + EXCLUDED.rollup_write_failures,
|
||||
updated_at = now()`,
|
||||
[input.kind, input.source_id, day, cost, halts, evalFails, evalPasses, completed, failures],
|
||||
{ signal: opts?.signal },
|
||||
);
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
// Signal-bounded callers get the abort surfaced, not a swallowed `ok:false`.
|
||||
if (opts?.signal?.aborted) throw err;
|
||||
const msg = (err as Error).message || String(err);
|
||||
// Don't spam: log once per process per (kind, day) error class.
|
||||
rollupErrorLogOnce(input.kind, day, msg);
|
||||
|
||||
+4
-25
@@ -10,8 +10,7 @@ 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, ResolvedColumn } from './types.ts';
|
||||
import { resolveWriteColumnForEngine } from './search/embedding-column.ts';
|
||||
import type { ChunkInput, PageInput, PageType } from './types.ts';
|
||||
import { computeEffectiveDate } from './effective-date.ts';
|
||||
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
|
||||
import { logSlugFallback } from './audit-slug-fallback.ts';
|
||||
@@ -741,14 +740,6 @@ 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);
|
||||
|
||||
@@ -833,7 +824,7 @@ export async function importFromContent(
|
||||
}
|
||||
|
||||
if (chunks.length > 0) {
|
||||
await tx.upsertChunks(slug, chunks, chunkOpts);
|
||||
await tx.upsertChunks(slug, chunks, txOpts);
|
||||
// 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
|
||||
@@ -1073,12 +1064,6 @@ 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) {
|
||||
@@ -1198,7 +1183,7 @@ export async function importCodeFile(
|
||||
await tx.addTag(slug, lang, txOpts);
|
||||
|
||||
if (chunks.length > 0) {
|
||||
await tx.upsertChunks(slug, chunks, chunkOpts);
|
||||
await tx.upsertChunks(slug, chunks, txOpts);
|
||||
// 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
|
||||
@@ -1347,12 +1332,6 @@ 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);
|
||||
@@ -1368,7 +1347,7 @@ export async function withImportTransaction(
|
||||
}
|
||||
if (spec.chunks !== undefined) {
|
||||
if (spec.chunks.length > 0) {
|
||||
await tx.upsertChunks(spec.slug, spec.chunks, chunkOpts);
|
||||
await tx.upsertChunks(spec.slug, spec.chunks, txOpts);
|
||||
} else {
|
||||
await tx.deleteChunks(spec.slug, txOpts);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,6 @@ 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';
|
||||
@@ -165,16 +164,12 @@ 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.
|
||||
|
||||
+31
-43
@@ -40,7 +40,6 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -1004,7 +1003,15 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return { slug: r.slug, id: Number(r.id) };
|
||||
}
|
||||
|
||||
async putPage(slug: string, page: PageInput, opts?: { sourceId?: string }): Promise<Page> {
|
||||
async putPage(
|
||||
slug: string,
|
||||
page: PageInput,
|
||||
opts?: { sourceId?: string; signal?: AbortSignal },
|
||||
): Promise<Page> {
|
||||
// #2750: PGLite is in-process WASM — no query cancellation. Pre-check so
|
||||
// an already-fired deadline skips the write; abort is cooperative
|
||||
// between calls (same posture as executeRaw's documented gap).
|
||||
if (opts?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
|
||||
slug = validateSlug(slug);
|
||||
const hash = page.content_hash || contentHash(page);
|
||||
const frontmatter = page.frontmatter || {};
|
||||
@@ -2231,20 +2238,12 @@ export class PGLiteEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Chunks
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & 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; embeddingColumn?: ResolvedColumn }): Promise<void> {
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string }): Promise<void> {
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// #1262: caller-resolved write target for TEXT embeddings. Descriptor
|
||||
// names are identifier-validated + quoted by buildVectorCastFragment;
|
||||
// omitted => legacy `embedding vector`. Mirrors postgres-engine.ts.
|
||||
const targetFragment = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn)
|
||||
: undefined;
|
||||
const targetCol = targetFragment?.col ?? 'embedding';
|
||||
const embeddingCast = targetFragment?.castSql.replace('$1::', '') ?? 'vector';
|
||||
|
||||
// Source-scope the page-id lookup so duplicate slugs in different sources
|
||||
// do not return multiple rows or target the wrong page.
|
||||
@@ -2279,7 +2278,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, ${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 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 rowParts: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIdx = 1;
|
||||
@@ -2297,7 +2296,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++}::${embeddingCast}` : 'NULL';
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
const embeddedAtPh = embeddingStr ? 'now()' : 'NULL';
|
||||
const embeddingImagePh = embeddingImageStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
|
||||
@@ -2336,19 +2335,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,
|
||||
${targetCol} = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${targetCol}
|
||||
WHEN content_chunks.${targetCol} IS NULL THEN EXCLUDED.${targetCol}
|
||||
embedding = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.${targetCol}
|
||||
ELSE content_chunks.${targetCol}
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
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.${targetCol} IS NULL THEN NULL
|
||||
WHEN content_chunks.${targetCol} IS NULL AND EXCLUDED.${targetCol} IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
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.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedded_at
|
||||
@@ -2386,19 +2385,14 @@ 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; 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';
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string }): { where: string; params: unknown[] } {
|
||||
const params: unknown[] = [];
|
||||
const conds: string[] = [];
|
||||
if (opts?.signature !== undefined) {
|
||||
params.push(opts.signature);
|
||||
conds.push(`(cc.${staleCol} IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
conds.push(`(cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
} else {
|
||||
conds.push(`cc.${staleCol} IS NULL`);
|
||||
conds.push(`cc.embedding IS NULL`);
|
||||
}
|
||||
conds.push(`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
|
||||
if (opts?.sourceId !== undefined) {
|
||||
@@ -2408,7 +2402,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return { where: conds.join(' AND '), params };
|
||||
}
|
||||
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string }): 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.
|
||||
@@ -2424,7 +2418,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return Number(count);
|
||||
}
|
||||
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): 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);
|
||||
@@ -2477,17 +2471,11 @@ 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.
|
||||
@@ -2501,7 +2489,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
WHERE cc.embedding 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`,
|
||||
@@ -2512,7 +2500,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
WHERE cc.embedding IS NULL
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
p.updated_at < $1::timestamptz
|
||||
@@ -2531,7 +2519,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE cc.${staleCol} IS NULL
|
||||
WHERE cc.embedding 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
|
||||
@@ -2543,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.${staleCol} IS NULL
|
||||
WHERE cc.embedding IS NULL
|
||||
AND p.source_id = $1
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
@@ -2568,7 +2556,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.${staleCol} IS NULL
|
||||
WHERE cc.embedding 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
|
||||
@@ -2582,7 +2570,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.${staleCol} IS NULL
|
||||
WHERE cc.embedding IS NULL
|
||||
AND p.source_id = $1
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (cc.page_id, cc.chunk_index) > ($2, $3)
|
||||
|
||||
+77
-46
@@ -50,7 +50,6 @@ import type {
|
||||
BrainStats, BrainHealth,
|
||||
IngestLogEntry, IngestLogInput,
|
||||
EngineConfig,
|
||||
ResolvedColumn,
|
||||
EvalCandidate, EvalCandidateInput,
|
||||
EvalCaptureFailure, EvalCaptureFailureReason,
|
||||
SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
|
||||
@@ -73,6 +72,32 @@ function escapeSqlStringLiteral(value: string): string {
|
||||
return value.replace(/'/g, "''");
|
||||
}
|
||||
|
||||
/**
|
||||
* #2750: race a promise against an AbortSignal, detaching the listener once
|
||||
* settled (long-lived drain signals are reused across many calls, so a bare
|
||||
* Promise.race would leak one listener per call). The abandoned promise keeps
|
||||
* running; used only for pool-acquisition waits where that is harmless.
|
||||
*/
|
||||
function waitForSignal<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (!signal) return work;
|
||||
if (signal.aborted) return Promise.reject(new DOMException('aborted', 'AbortError'));
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
fn();
|
||||
};
|
||||
const onAbort = () => finish(() => reject(new DOMException('aborted', 'AbortError')));
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
work.then(
|
||||
(value) => finish(() => resolve(value)),
|
||||
(err) => finish(() => reject(err)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function getPostgresSchema(
|
||||
dims: number = DEFAULT_EMBEDDING_DIMENSIONS,
|
||||
model: string = DEFAULT_EMBEDDING_MODEL,
|
||||
@@ -1062,7 +1087,12 @@ export class PostgresEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
async putPage(slug: string, page: PageInput, opts?: { sourceId?: string }): Promise<Page> {
|
||||
async putPage(
|
||||
slug: string,
|
||||
page: PageInput,
|
||||
opts?: { sourceId?: string; signal?: AbortSignal },
|
||||
): Promise<Page> {
|
||||
if (opts?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
|
||||
slug = validateSlug(slug);
|
||||
const sql = this.sql;
|
||||
const hash = page.content_hash || contentHash(page);
|
||||
@@ -1097,7 +1127,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
const sourceUri = page.source_uri ?? null;
|
||||
const ingestedVia = page.ingested_via ?? null;
|
||||
const ingestedAt = (sourceKind || sourceUri || ingestedVia) ? new Date() : null;
|
||||
const rows = await sql`
|
||||
const pending = sql`
|
||||
INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at)
|
||||
VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${page.title}, ${page.compiled_truth}, ${page.timeline || ''}, ${sql.json(frontmatter as Parameters<typeof sql.json>[0])}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, COALESCE(${chunkerVersion}::smallint, ${MARKDOWN_CHUNKER_VERSION}), ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})
|
||||
ON CONFLICT (source_id, slug) DO UPDATE SET
|
||||
@@ -1120,6 +1150,22 @@ export class PostgresEngine implements BrainEngine {
|
||||
ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at)
|
||||
RETURNING id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at
|
||||
`;
|
||||
// #2750: cancel the in-flight statement when the caller's deadline fires,
|
||||
// same .cancel() wiring as runUnsafe (postgres.js pending queries).
|
||||
if (opts?.signal) {
|
||||
const signal = opts.signal;
|
||||
const onAbort = () => {
|
||||
try { (pending as unknown as { cancel?: () => void }).cancel?.(); } catch { /* best-effort */ }
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
try {
|
||||
const rows = await pending;
|
||||
return rowToPage(rows[0]);
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
const rows = await pending;
|
||||
return rowToPage(rows[0]);
|
||||
}
|
||||
|
||||
@@ -2381,21 +2427,13 @@ export class PostgresEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Chunks
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {
|
||||
async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string } & 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; embeddingColumn?: ResolvedColumn }): Promise<void> {
|
||||
private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string }): Promise<void> {
|
||||
const sql = this.sql;
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// #1262: caller-resolved write target for TEXT embeddings. Descriptor
|
||||
// names are identifier-validated + quoted by buildVectorCastFragment;
|
||||
// omitted => legacy `embedding vector`.
|
||||
const targetFragment = opts?.embeddingColumn
|
||||
? buildVectorCastFragment(opts.embeddingColumn)
|
||||
: undefined;
|
||||
const targetCol = targetFragment?.col ?? 'embedding';
|
||||
const embeddingCast = targetFragment?.castSql.replace('$1::', '') ?? 'vector';
|
||||
|
||||
// Source-scope the page-id lookup. Without this filter, multi-source
|
||||
// brains where the slug exists in 2+ sources return >1 row and the
|
||||
@@ -2422,7 +2460,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, ${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 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 rows: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIdx = 1;
|
||||
@@ -2439,7 +2477,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
: null;
|
||||
const modality = chunk.modality ?? 'text';
|
||||
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::${embeddingCast}` : 'NULL';
|
||||
const embeddingPh = embeddingStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
const embeddedAtPh = embeddingStr ? 'now()' : 'NULL';
|
||||
const embeddingImagePh = embeddingImageStr ? `$${paramIdx++}::vector` : 'NULL';
|
||||
|
||||
@@ -2487,19 +2525,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,
|
||||
${targetCol} = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${targetCol}
|
||||
WHEN content_chunks.${targetCol} IS NULL THEN EXCLUDED.${targetCol}
|
||||
embedding = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.${targetCol}
|
||||
ELSE content_chunks.${targetCol}
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
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.${targetCol} IS NULL THEN NULL
|
||||
WHEN content_chunks.${targetCol} IS NULL AND EXCLUDED.${targetCol} IS NOT NULL THEN EXCLUDED.embedded_at
|
||||
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.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.embedded_at
|
||||
@@ -2539,19 +2577,14 @@ 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; 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';
|
||||
private buildStaleChunkWhere(opts?: { sourceId?: string; signature?: string }): { where: string; params: unknown[] } {
|
||||
const params: unknown[] = [];
|
||||
const conds: string[] = [];
|
||||
if (opts?.signature !== undefined) {
|
||||
params.push(opts.signature);
|
||||
conds.push(`(cc.${staleCol} IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
conds.push(`(cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $${params.length}))`);
|
||||
} else {
|
||||
conds.push(`cc.${staleCol} IS NULL`);
|
||||
conds.push(`cc.embedding IS NULL`);
|
||||
}
|
||||
conds.push(`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
|
||||
if (opts?.sourceId !== undefined) {
|
||||
@@ -2561,7 +2594,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
return { where: conds.join(' AND '), params };
|
||||
}
|
||||
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
async countStaleChunks(opts?: { sourceId?: string; signature?: string }): 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).
|
||||
@@ -2579,7 +2612,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string; embeddingColumn?: ResolvedColumn }): Promise<number> {
|
||||
async sumStaleChunkChars(opts?: { sourceId?: string; signature?: string }): 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);
|
||||
@@ -2632,18 +2665,11 @@ 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) => {
|
||||
@@ -2660,7 +2686,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding 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}
|
||||
@@ -2670,7 +2696,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding IS NULL
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
p.updated_at < ${afterUpdated}::timestamptz
|
||||
@@ -2688,7 +2714,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding 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
|
||||
@@ -2699,7 +2725,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
p.updated_at
|
||||
FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding IS NULL
|
||||
AND p.source_id = ${opts.sourceId}
|
||||
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
|
||||
AND (
|
||||
@@ -2719,7 +2745,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 ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding 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
|
||||
@@ -2732,7 +2758,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 ${tx.unsafe(`cc.${staleCol} IS NULL`)}
|
||||
WHERE cc.embedding 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})
|
||||
@@ -5828,11 +5854,16 @@ export class PostgresEngine implements BrainEngine {
|
||||
params?: unknown[],
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<T[]> {
|
||||
// #2750: an already-fired signal short-circuits BEFORE any pool routing,
|
||||
// and the direct-pool acquisition itself is signal-bounded — under pooler
|
||||
// exhaustion `ddl()` can stall indefinitely, which used to make even a
|
||||
// "bounded" lock release hang past its caller's deadline.
|
||||
if (opts?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
|
||||
// Inside an open transaction, _sql is the reserved tx connection (set via
|
||||
// defineProperty in transaction()); never reroute off it.
|
||||
const inTransaction = this._sql !== null && this.connectionManager?.peekReadPool() !== this._sql;
|
||||
const conn = (!inTransaction && this.connectionManager?.isDualPoolActive())
|
||||
? await this.connectionManager.ddl()
|
||||
? await waitForSignal(this.connectionManager.ddl(), opts?.signal)
|
||||
: this.sql;
|
||||
return this.runUnsafe<T>(conn, sql, params, opts);
|
||||
}
|
||||
|
||||
@@ -443,80 +443,6 @@ 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.
|
||||
|
||||
@@ -17,6 +17,7 @@ import { runPhaseExtractAtoms, parseAtomsResponse } from '../../src/core/cycle/e
|
||||
import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';
|
||||
import { resetPgliteState } from '../helpers/reset-pglite.ts';
|
||||
import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
|
||||
import type { BrainEngine } from '../../src/core/engine.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
@@ -177,6 +178,180 @@ describe('v0.41 T5: runPhaseExtractAtoms via stubbed chat', () => {
|
||||
expect((result.details?.failures as unknown[]).length).toBe(1);
|
||||
});
|
||||
|
||||
// ── #2750: caller deadline bounds the phase ────────────────────────────
|
||||
|
||||
test('caller deadline aborts a hung chat before processing the next item', async () => {
|
||||
let calls = 0;
|
||||
const chat = async (opts: ChatOpts) => {
|
||||
calls++;
|
||||
return await new Promise<never>((_resolve, reject) => {
|
||||
const signal = opts.abortSignal;
|
||||
if (!signal) return reject(new Error('missing abort signal'));
|
||||
if (signal.aborted) return reject(signal.reason);
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
};
|
||||
const started = Date.now();
|
||||
const result = await runPhaseExtractAtoms(engine, {
|
||||
_transcripts: [
|
||||
{ filePath: '/hung.txt', content: 'a', contentHash: 'hung-a' },
|
||||
{ filePath: '/never.txt', content: 'b', contentHash: 'hung-b' },
|
||||
],
|
||||
_pages: [],
|
||||
_chat: chat as typeof import('../../src/core/ai/gateway.ts').chat,
|
||||
abortSignal: AbortSignal.timeout(25),
|
||||
});
|
||||
expect(Date.now() - started).toBeLessThan(2_000);
|
||||
expect(calls).toBe(1);
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.details?.deadline_aborted).toBe(true);
|
||||
expect(result.details?.atoms_extracted).toBe(0);
|
||||
expect(result.details?.failures).toEqual([]);
|
||||
});
|
||||
|
||||
test('billable chat usage is counted when the deadline fires as the response resolves', async () => {
|
||||
const controller = new AbortController();
|
||||
const chat = async (opts: ChatOpts): Promise<ChatResult> => {
|
||||
controller.abort(new DOMException('deadline', 'TimeoutError'));
|
||||
return stubChat(`[{"title":"late","atom_type":"insight","body":"b"}]`, {
|
||||
input_tokens: 1_000,
|
||||
output_tokens: 500,
|
||||
})(opts);
|
||||
};
|
||||
const result = await runPhaseExtractAtoms(engine, {
|
||||
_transcripts: [{ filePath: '/late.txt', content: 'a', contentHash: 'late' }],
|
||||
_pages: [],
|
||||
_chat: chat,
|
||||
abortSignal: controller.signal,
|
||||
});
|
||||
expect(result.details?.deadline_aborted).toBe(true);
|
||||
expect(Number(result.details?.estimated_spend_usd)).toBeGreaterThan(0);
|
||||
expect(result.details?.atoms_extracted).toBe(0);
|
||||
});
|
||||
|
||||
test('deadline after partial progress still writes receipt and incomplete rollup', async () => {
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
let notifySecondChat!: () => void;
|
||||
const secondChatStarted = new Promise<void>((resolve) => { notifySecondChat = resolve; });
|
||||
const chat = async (opts: ChatOpts): Promise<ChatResult> => {
|
||||
calls++;
|
||||
if (calls === 1) {
|
||||
return stubChat(`[{"title":"committed","atom_type":"insight","body":"b"}]`)(opts);
|
||||
}
|
||||
notifySecondChat();
|
||||
return await new Promise<never>((_resolve, reject) => {
|
||||
const signal = opts.abortSignal;
|
||||
if (!signal) return reject(new Error('missing abort signal'));
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const pending = runPhaseExtractAtoms(engine, {
|
||||
_transcripts: [
|
||||
{ filePath: '/committed.txt', content: 'a', contentHash: 'committed-a' },
|
||||
{ filePath: '/hung.txt', content: 'b', contentHash: 'hung-b' },
|
||||
],
|
||||
_pages: [],
|
||||
_chat: chat,
|
||||
abortSignal: controller.signal,
|
||||
});
|
||||
await secondChatStarted;
|
||||
controller.abort(new DOMException('deadline', 'TimeoutError'));
|
||||
const result = await pending;
|
||||
|
||||
const atoms = await engine.executeRaw<{ n: number }>(
|
||||
`SELECT COUNT(*)::int AS n FROM pages WHERE type = 'atom'`,
|
||||
);
|
||||
const receipts = await engine.executeRaw<{ n: number }>(
|
||||
`SELECT COUNT(*)::int AS n FROM pages WHERE type = 'extract_receipt'`,
|
||||
);
|
||||
const rollups = await engine.executeRaw<{
|
||||
cost_usd: string | number;
|
||||
round_completed_count: string | number;
|
||||
}>(
|
||||
`SELECT cost_usd, round_completed_count
|
||||
FROM extract_rollup_7d
|
||||
WHERE kind = 'atoms' AND source_id = 'default'`,
|
||||
);
|
||||
expect(result.details?.deadline_aborted).toBe(true);
|
||||
expect(atoms[0].n).toBe(1);
|
||||
expect(receipts[0].n).toBe(1);
|
||||
expect(Number(rollups[0].cost_usd)).toBeGreaterThan(0);
|
||||
expect(Number(rollups[0].round_completed_count)).toBe(0);
|
||||
});
|
||||
|
||||
test('bookkeeping runs on a fresh grace signal, not the fired work deadline', async () => {
|
||||
const controller = new AbortController();
|
||||
let putCalls = 0;
|
||||
let receiptSignal: AbortSignal | undefined;
|
||||
let rollupSignal: AbortSignal | undefined;
|
||||
const signalAwareEngine = {
|
||||
executeRaw: async (sql: string, _params?: unknown[], opts?: { signal?: AbortSignal }) => {
|
||||
if (sql.includes('INSERT INTO extract_rollup_7d')) rollupSignal = opts?.signal;
|
||||
return [];
|
||||
},
|
||||
putPage: async (_slug: string, _page: unknown, opts?: { signal?: AbortSignal }) => {
|
||||
putCalls++;
|
||||
if (putCalls === 1) {
|
||||
// Atom write in flight; the work deadline fires before bookkeeping.
|
||||
controller.abort(new DOMException('work deadline', 'TimeoutError'));
|
||||
} else {
|
||||
receiptSignal = opts?.signal;
|
||||
}
|
||||
return {};
|
||||
},
|
||||
} as unknown as BrainEngine;
|
||||
|
||||
const result = await runPhaseExtractAtoms(signalAwareEngine, {
|
||||
_transcripts: [{ filePath: '/one.txt', content: 'a', contentHash: 'one' }],
|
||||
_pages: [],
|
||||
_chat: stubChat(`[{"title":"one","atom_type":"insight","body":"b"}]`),
|
||||
abortSignal: controller.signal,
|
||||
});
|
||||
|
||||
expect(result.details?.atoms_extracted).toBe(1);
|
||||
expect(putCalls).toBe(2); // atom write + receipt write
|
||||
expect(receiptSignal).toBeDefined();
|
||||
expect(receiptSignal).not.toBe(controller.signal);
|
||||
expect(receiptSignal?.aborted).toBe(false);
|
||||
expect(rollupSignal).toBe(receiptSignal);
|
||||
});
|
||||
|
||||
test('caller deadline cancels a hung atom write and stops the phase', async () => {
|
||||
const controller = new AbortController();
|
||||
let notifyWriteStarted!: () => void;
|
||||
const writeStarted = new Promise<void>((resolve) => { notifyWriteStarted = resolve; });
|
||||
let writeCalls = 0;
|
||||
const signalAwareEngine = {
|
||||
executeRaw: async () => [],
|
||||
putPage: async (_slug: string, _page: unknown, opts?: { signal?: AbortSignal }) => {
|
||||
writeCalls++;
|
||||
notifyWriteStarted();
|
||||
return await new Promise<never>((_resolve, reject) => {
|
||||
const signal = opts?.signal;
|
||||
if (!signal) return reject(new Error('missing abort signal'));
|
||||
if (signal.aborted) return reject(signal.reason);
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
},
|
||||
} as unknown as BrainEngine;
|
||||
|
||||
const pending = runPhaseExtractAtoms(signalAwareEngine, {
|
||||
_transcripts: [{ filePath: '/hung-write.txt', content: 'a', contentHash: 'hung-write' }],
|
||||
_pages: [],
|
||||
_chat: stubChat(`[{"title":"hung write","atom_type":"insight","body":"b"}]`),
|
||||
abortSignal: controller.signal,
|
||||
});
|
||||
await writeStarted;
|
||||
controller.abort(new DOMException('deadline', 'TimeoutError'));
|
||||
const result = await pending;
|
||||
|
||||
expect(writeCalls).toBe(1);
|
||||
expect(result.details?.deadline_aborted).toBe(true);
|
||||
expect(result.details?.atoms_extracted).toBe(0);
|
||||
});
|
||||
|
||||
// v0.41.2.1 regression case (D9 #14 wording): with _pages:[] and same
|
||||
// _transcripts, all PRE-EXISTING PhaseResult.details fields match
|
||||
// pre-fix values byte-for-byte. The new fields (pages_processed,
|
||||
|
||||
@@ -241,136 +241,3 @@ 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,54 +224,4 @@ 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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -43,26 +43,135 @@ describe('runExtractAtomsDrain (issue #1678)', () => {
|
||||
expect(batches).toBe(3);
|
||||
});
|
||||
|
||||
it('stops at the wallclock window with remaining > 0', async () => {
|
||||
// SYNC stepping clock: now() #1 sets deadline (0+100=100); the while-check
|
||||
// then sees 50, 50 (two batches), then 999999 → past deadline → stop.
|
||||
const times = [0, 50, 50, 999_999];
|
||||
let ti = 0;
|
||||
const now = () => times[Math.min(ti++, times.length - 1)];
|
||||
it('stops at the wallclock window; remaining is unknown (no post-window count)', async () => {
|
||||
// Each batch consumes 60ms of the 100ms window: two batches fit, the
|
||||
// third boundary check sees 120 ≥ 100 and stops. #2750: after the window
|
||||
// elapses the final countRemaining is SKIPPED (it would overrun the
|
||||
// window), so remaining reports null.
|
||||
let now = 0;
|
||||
const result = await runExtractAtomsDrain(
|
||||
{
|
||||
withLock: passThroughLock,
|
||||
countRemaining: async () => 5, // never drains
|
||||
runBatch: async () => ({ extracted: 1, skipped: 0 }),
|
||||
now,
|
||||
runBatch: async () => {
|
||||
now += 60;
|
||||
return { extracted: 1, skipped: 0 };
|
||||
},
|
||||
now: () => now,
|
||||
},
|
||||
{ windowMs: 100 },
|
||||
);
|
||||
expect(result.stopped).toBe('window');
|
||||
expect(result.remaining).toBe(5);
|
||||
expect(result.remaining).toBeNull();
|
||||
expect(result.batches).toBe(2);
|
||||
});
|
||||
|
||||
it('passes one drain-level deadline signal into count and batch', async () => {
|
||||
const seen: AbortSignal[] = [];
|
||||
const controller = new AbortController();
|
||||
let now = 0;
|
||||
const result = await runExtractAtomsDrain(
|
||||
{
|
||||
withLock: passThroughLock,
|
||||
countRemaining: async (signal) => {
|
||||
seen.push(signal);
|
||||
return 5;
|
||||
},
|
||||
runBatch: async (signal) => {
|
||||
seen.push(signal);
|
||||
now = 100;
|
||||
return { extracted: 1, skipped: 0 };
|
||||
},
|
||||
now: () => now,
|
||||
},
|
||||
{ windowMs: 100, abortSignal: controller.signal },
|
||||
);
|
||||
expect(result.stopped).toBe('window');
|
||||
expect(result.batches).toBe(1);
|
||||
expect(seen.length).toBe(2);
|
||||
expect(seen[0]).toBe(seen[1]);
|
||||
// Combined (timeout + external) signal, not the raw external one.
|
||||
expect(seen[0]).not.toBe(controller.signal);
|
||||
});
|
||||
|
||||
it('aborts a hung backlog count at the window deadline and releases the lock', async () => {
|
||||
let released = false;
|
||||
const result = await runExtractAtomsDrain(
|
||||
{
|
||||
withLock: async (work) => {
|
||||
try { return await work(); }
|
||||
finally { released = true; }
|
||||
},
|
||||
// Hangs until the drain's real-time deadline signal fires (10ms).
|
||||
countRemaining: (signal) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
}),
|
||||
runBatch: async () => ({ extracted: 0, skipped: 0 }),
|
||||
now: () => 0, // injected clock never advances — the SIGNAL must save us
|
||||
},
|
||||
{ windowMs: 10 },
|
||||
);
|
||||
expect(result.stopped).toBe('window');
|
||||
expect(result.remaining).toBeNull();
|
||||
expect(released).toBe(true);
|
||||
});
|
||||
|
||||
it('rethrows external cancellation after releasing the lock', async () => {
|
||||
const controller = new AbortController();
|
||||
let released = false;
|
||||
const pending = runExtractAtomsDrain(
|
||||
{
|
||||
withLock: async (work) => {
|
||||
try { return await work(); }
|
||||
finally { released = true; }
|
||||
},
|
||||
countRemaining: (signal) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
}),
|
||||
runBatch: async () => ({ extracted: 0, skipped: 0 }),
|
||||
now: () => 0,
|
||||
},
|
||||
{ windowMs: 1_000_000, abortSignal: controller.signal },
|
||||
);
|
||||
controller.abort(new DOMException('worker timeout', 'AbortError'));
|
||||
await expect(pending).rejects.toThrow('worker timeout');
|
||||
expect(released).toBe(true);
|
||||
});
|
||||
|
||||
it('classifies a deadline-exhausted zero-progress batch as window, not no_progress', async () => {
|
||||
let now = 0;
|
||||
const result = await runExtractAtomsDrain(
|
||||
{
|
||||
withLock: passThroughLock,
|
||||
countRemaining: async () => 5,
|
||||
runBatch: async () => {
|
||||
now = 100; // batch consumed the whole window and returned nothing
|
||||
return { extracted: 0, skipped: 0 };
|
||||
},
|
||||
now: () => now,
|
||||
},
|
||||
{ windowMs: 100 },
|
||||
);
|
||||
expect(result.stopped).toBe('window');
|
||||
expect(result.batches).toBe(1);
|
||||
});
|
||||
|
||||
it('bounds a hung lock acquisition with the drain deadline signal', async () => {
|
||||
const started = Date.now();
|
||||
await expect(runExtractAtomsDrain(
|
||||
{
|
||||
withLock: (_work, signal) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
}),
|
||||
countRemaining: async () => 1,
|
||||
runBatch: async () => ({ extracted: 0, skipped: 0 }),
|
||||
now: Date.now,
|
||||
},
|
||||
{ windowMs: 10 },
|
||||
)).rejects.toThrow();
|
||||
expect(Date.now() - started).toBeLessThan(1_000);
|
||||
});
|
||||
|
||||
it('stops on a zero-progress batch (no hot loop)', async () => {
|
||||
let batches = 0;
|
||||
const result = await runExtractAtomsDrain(
|
||||
@@ -133,4 +242,17 @@ describe('shared wiring helper holds the cycle lock (5A)', () => {
|
||||
expect(src).toContain('cycleLockIdFor(opts.sourceId)');
|
||||
expect(src).toContain('withRefreshingLock(engine, lockId');
|
||||
});
|
||||
|
||||
// #2750: the deadline signal must reach the phase, the backlog count, AND
|
||||
// the lock wrapper — and the transcript path (brainDir) must stay wired
|
||||
// exactly as the routine callers expect (PR #2752 takeover reverted its
|
||||
// unsanctioned transcript-suppression scope change).
|
||||
it('threads the drain deadline signal through phase, count, and lock', () => {
|
||||
const jobsSrc = readFileSync(join(import.meta.dir, '../src/commands/jobs.ts'), 'utf8');
|
||||
expect(src).toContain('abortSignal: signal');
|
||||
expect(src).toContain('countExtractAtomsBacklog(engine, extractionSourceId, signal)');
|
||||
expect(src).toContain('brainDir: opts.brainDir');
|
||||
expect(src).not.toContain('_transcripts');
|
||||
expect(jobsSrc).toContain('abortSignal: job.signal');
|
||||
});
|
||||
});
|
||||
|
||||
Vendored
+9
-6
@@ -24,15 +24,18 @@ import type { BrainEngine } from '../../src/core/engine.ts';
|
||||
// Mock engine: healthCheck() calls engine.executeRaw; return empty rows so
|
||||
// the query path exercises without needing Postgres.
|
||||
//
|
||||
// #1849: start() now acquires the queue-scoped DB singleton lock via
|
||||
// tryAcquireDbLock, which uses the postgres `sql` tagged-template escape hatch.
|
||||
// The stub returns a single row from every call so acquire succeeds (length 1
|
||||
// → acquired) and refresh/release are no-ops. Each spawned runner is a fresh
|
||||
// process, so there's no cross-test lock state to clean up.
|
||||
// #1849: start() acquires the queue-scoped DB singleton lock via
|
||||
// tryAcquireDbLock. #2750 routed the acquire upsert through engine.executeRaw
|
||||
// (signal-boundable) and release through engine.executeRawDirect, so the
|
||||
// stub returns a single row from the lock upsert (length 1 → acquired) and
|
||||
// empty rows everywhere else. Each spawned runner is a fresh process, so
|
||||
// there's no cross-test lock state to clean up.
|
||||
const sqlStub = (..._args: unknown[]) => Promise.resolve([{ id: 'supervisor-lock' }]);
|
||||
const mockEngine: Partial<BrainEngine> = {
|
||||
kind: 'postgres' as const,
|
||||
executeRaw: async () => [],
|
||||
executeRaw: async (query: string) =>
|
||||
query.includes('gbrain_cycle_locks') ? [{ id: 'supervisor-lock' }] : [],
|
||||
executeRawDirect: async () => [],
|
||||
sql: sqlStub,
|
||||
} as unknown as BrainEngine;
|
||||
|
||||
|
||||
@@ -98,14 +98,39 @@ describe('PostgresEngine.executeRawDirect — routing decision (PR #1816)', () =
|
||||
});
|
||||
|
||||
test('already-aborted signal short-circuits with AbortError before routing the query', async () => {
|
||||
const readConn = fakeSql('read');
|
||||
let unsafeCalls = 0;
|
||||
let ddlCalls = 0;
|
||||
const readConn: FakeSql = { unsafe: async () => { unsafeCalls++; return []; } };
|
||||
const directConn = fakeSql('direct');
|
||||
const engine = makeEngine({ dualPoolActive: true, readConn, directConn });
|
||||
const e = engine as unknown as { connectionManager: { ddl: () => Promise<FakeSql> } };
|
||||
e.connectionManager.ddl = async () => { ddlCalls++; return directConn; };
|
||||
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
await expect(
|
||||
engine.executeRawDirect('UPDATE minion_jobs SET x=1', [], { signal: ac.signal }),
|
||||
).rejects.toThrow(/abort/i);
|
||||
// #2750: short-circuits BEFORE pool routing — no ddl(), no unsafe().
|
||||
expect(ddlCalls).toBe(0);
|
||||
expect(unsafeCalls).toBe(0);
|
||||
});
|
||||
|
||||
test('#2750: signal bounds a stalled direct-pool acquisition before unsafe starts', async () => {
|
||||
let unsafeCalls = 0;
|
||||
const readConn: FakeSql = { unsafe: async () => { unsafeCalls++; return []; } };
|
||||
const directConn = fakeSql('direct');
|
||||
const engine = makeEngine({ dualPoolActive: true, readConn, directConn });
|
||||
const e = engine as unknown as { connectionManager: { ddl: () => Promise<FakeSql> } };
|
||||
e.connectionManager.ddl = () => new Promise<FakeSql>(() => {}); // pooler exhausted: never resolves
|
||||
|
||||
const started = Date.now();
|
||||
await expect(engine.executeRawDirect(
|
||||
'DELETE FROM gbrain_cycle_locks',
|
||||
[],
|
||||
{ signal: AbortSignal.timeout(10) },
|
||||
)).rejects.toThrow(/abort/i);
|
||||
expect(Date.now() - started).toBeLessThan(1_000);
|
||||
expect(unsafeCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,10 +13,9 @@
|
||||
* throw on unknown string.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, afterAll, afterEach } from 'bun:test';
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import {
|
||||
resolveEmbeddingColumn,
|
||||
resolveWriteColumn,
|
||||
getEmbeddingColumnRegistry,
|
||||
buildVectorCastFragment,
|
||||
quoteIdentifier,
|
||||
@@ -35,28 +34,6 @@ 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 };
|
||||
@@ -545,89 +522,3 @@ 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