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