mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 09:52:22 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60fb33c0d9 | ||
|
|
11ed0871c2 | ||
|
|
595eeb7d6f |
+10
-5
@@ -170,10 +170,14 @@ export async function runImport(
|
||||
// v0.22.13 (PR #490 Q2): shared parseWorkers helper rejects bad input
|
||||
// (--workers 0, -3, "foo") with a loud error instead of silently falling
|
||||
// through to 1. Mirrors sync.ts's flag handling.
|
||||
const { parseWorkers } = await import('../core/sync-concurrency.ts');
|
||||
let workerCount: number;
|
||||
const { parseWorkers, autoConcurrency } = await import('../core/sync-concurrency.ts');
|
||||
// #1207: undefined (no --workers flag) defers to autoConcurrency below —
|
||||
// the shared sync/import policy (PGLite → 1, >100 files → 4) — instead of
|
||||
// hardcoding serial. Large Postgres imports stop paying one embedding
|
||||
// round-trip per file in sequence.
|
||||
let workerCount: number | undefined;
|
||||
try {
|
||||
workerCount = parseWorkers(workersArg ?? undefined) ?? 1;
|
||||
workerCount = parseWorkers(workersArg ?? undefined);
|
||||
} catch (e) {
|
||||
console.error(e instanceof Error ? e.message : String(e));
|
||||
process.exit(1);
|
||||
@@ -252,8 +256,9 @@ export async function runImport(
|
||||
}
|
||||
const files = resumeFilter(allFiles, dir, completed);
|
||||
|
||||
// Determine actual worker count
|
||||
const actualWorkers = workerCount > 1 ? workerCount : 1;
|
||||
// Determine actual worker count. Explicit --workers wins; otherwise the
|
||||
// shared autoConcurrency policy decides from engine kind + file count.
|
||||
const actualWorkers = autoConcurrency(engine, files.length, workerCount);
|
||||
if (actualWorkers > 1) {
|
||||
console.log(`Using ${actualWorkers} parallel workers`);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+24
-6
@@ -1513,12 +1513,21 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
|
||||
|
||||
const embedding = recipe.touchpoints?.embedding;
|
||||
const maxBatchTokens = embedding?.max_batch_tokens;
|
||||
const maxBatchCount = embedding?.max_batch_count;
|
||||
const charsPerToken = embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;
|
||||
|
||||
// Pre-split is gated on max_batch_tokens. Recipes without it (e.g. OpenAI)
|
||||
// ride the fast path: one embedMany call, no recursion safety net.
|
||||
const batches = maxBatchTokens
|
||||
? splitByTokenBudget(truncated, Math.floor(maxBatchTokens * effectiveSafetyFactor(recipe)), charsPerToken)
|
||||
// Pre-split is gated on max_batch_tokens / max_batch_count. Recipes with
|
||||
// neither (e.g. OpenAI) ride the fast path: one embedMany call, no
|
||||
// recursion safety net.
|
||||
const batches = (maxBatchTokens || maxBatchCount)
|
||||
? splitByTokenBudget(
|
||||
truncated,
|
||||
maxBatchTokens
|
||||
? Math.floor(maxBatchTokens * effectiveSafetyFactor(recipe))
|
||||
: Number.MAX_SAFE_INTEGER,
|
||||
charsPerToken,
|
||||
maxBatchCount,
|
||||
)
|
||||
: [truncated];
|
||||
|
||||
const allEmbeddings: Float32Array[] = [];
|
||||
@@ -1568,6 +1577,9 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
|
||||
* responsible for applying any safety-factor shrink before passing in.
|
||||
* @param charsPerToken - Provider-specific character density. Defaults to
|
||||
* `DEFAULT_CHARS_PER_TOKEN` (4) when omitted, matching OpenAI tiktoken.
|
||||
* @param maxBatchCount - #1199: optional cap on INPUTS per sub-batch, for
|
||||
* providers that reject batches by count (DashScope: 10). When omitted,
|
||||
* only the token budget governs.
|
||||
*
|
||||
* @internal exported for tests; not part of the public gateway API.
|
||||
*/
|
||||
@@ -1575,15 +1587,17 @@ export function splitByTokenBudget(
|
||||
texts: string[],
|
||||
budgetTokens: number,
|
||||
charsPerToken: number = DEFAULT_CHARS_PER_TOKEN,
|
||||
maxBatchCount?: number,
|
||||
): string[][] {
|
||||
const ratio = charsPerToken > 0 ? charsPerToken : DEFAULT_CHARS_PER_TOKEN;
|
||||
const maxCount = maxBatchCount !== undefined && maxBatchCount > 0 ? maxBatchCount : Infinity;
|
||||
const batches: string[][] = [];
|
||||
let current: string[] = [];
|
||||
let currentTokens = 0;
|
||||
|
||||
for (const text of texts) {
|
||||
const estTokens = Math.ceil(text.length / ratio);
|
||||
if (current.length > 0 && currentTokens + estTokens > budgetTokens) {
|
||||
if (current.length > 0 && (currentTokens + estTokens > budgetTokens || current.length >= maxCount)) {
|
||||
batches.push(current);
|
||||
current = [];
|
||||
currentTokens = 0;
|
||||
@@ -1609,7 +1623,11 @@ export function isTokenLimitError(err: unknown): boolean {
|
||||
/token.*limit.*exceeded/i.test(msg) ||
|
||||
// OpenAI embeddings: "Invalid 'input': maximum request size is 300000 tokens per request."
|
||||
/maximum request size.*tokens/i.test(msg) ||
|
||||
/max.*tokens.*per.*request/i.test(msg)
|
||||
/max.*tokens.*per.*request/i.test(msg) ||
|
||||
// DashScope: "batch size is invalid, it should not be larger than 10." (#1199)
|
||||
// Count-cap error, but recursive halving shrinks count too, so the same
|
||||
// safety net converges.
|
||||
/batch size is invalid/i.test(msg)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,10 @@ export const dashscope: Recipe = {
|
||||
// path. Conservative declaration so the gateway pre-splits before
|
||||
// hitting whatever undocumented server-side limit exists.
|
||||
max_batch_tokens: 8192,
|
||||
// #1199: DashScope hard-caps embeddings at 10 inputs per request
|
||||
// ("batch size is invalid, it should not be larger than 10"). The
|
||||
// token budget alone admits far more than 10 short chunks per batch.
|
||||
max_batch_count: 10,
|
||||
// text-embedding-v3 mixes English + CJK heavily; the tokenizer is
|
||||
// closer to Voyage density than OpenAI tiktoken for CJK-dominant
|
||||
// content. Conservative chars_per_token=2 leaves headroom.
|
||||
|
||||
@@ -16,6 +16,15 @@ export const google: Recipe = {
|
||||
dims_options: [768, 1536, 3072],
|
||||
cost_per_1m_tokens_usd: 0.15,
|
||||
price_last_verified: '2026-04-20',
|
||||
// #970: Gemini's documented limits are per-INPUT (2048 tokens,
|
||||
// silently truncated beyond) and per-REQUEST count (batchEmbedContents
|
||||
// caps at 100 inputs). There is no separate per-request token cap, so
|
||||
// the token budget is derived: 100 inputs × 2048 tokens. The count cap
|
||||
// binds first for typical chunk sizes. Do NOT copy the 2048 per-input
|
||||
// limit into max_batch_tokens — that would over-split 50×.
|
||||
max_batch_tokens: 204_800,
|
||||
chars_per_token: 4,
|
||||
max_batch_count: 100,
|
||||
},
|
||||
expansion: {
|
||||
models: ['gemini-2.0-flash', 'gemini-2.0-flash-lite'],
|
||||
|
||||
@@ -58,5 +58,8 @@ export function getRecipe(id: string): Recipe | undefined {
|
||||
}
|
||||
|
||||
export function listRecipes(): Recipe[] {
|
||||
return [...ALL];
|
||||
// Read the map (not ALL) so there is one source of truth — getRecipe,
|
||||
// model-resolver, and listRecipes all see the same registry, and tests
|
||||
// can inject a synthetic recipe via RECIPES to exercise registry walks.
|
||||
return [...RECIPES.values()];
|
||||
}
|
||||
|
||||
@@ -46,6 +46,16 @@ export interface EmbeddingTouchpoint {
|
||||
* Only consulted when `max_batch_tokens` is also set.
|
||||
*/
|
||||
chars_per_token?: number;
|
||||
/**
|
||||
* #1199: maximum number of INPUTS per embedding request, for providers
|
||||
* that hard-cap batch size by count rather than (or in addition to)
|
||||
* tokens — DashScope text-embedding-v3 rejects batches > 10 with
|
||||
* `InvalidParameter`, Gemini batchEmbedContents caps at 100 requests.
|
||||
* When set, the gateway's pre-split flushes a sub-batch at this count
|
||||
* even if the token budget still has room. Independent of
|
||||
* `max_batch_tokens`; either alone triggers the pre-split.
|
||||
*/
|
||||
max_batch_count?: number;
|
||||
/**
|
||||
* Budget-utilization ceiling in (0, 1]. The gateway pre-splits at
|
||||
* `safety_factor × max_batch_tokens` to leave headroom for tokenizer
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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,
|
||||
|
||||
+56
-6
@@ -79,15 +79,34 @@ export interface EmbedBatchOptions {
|
||||
* and amplify rate-limit pressure.
|
||||
*/
|
||||
maxRetries?: number;
|
||||
/**
|
||||
* #1818: bounded parallelism across BATCH_SIZE sub-batches. Defaults to
|
||||
* `GBRAIN_EMBED_BATCH_CONCURRENCY` env, else 4. Results are
|
||||
* index-addressed so output order always matches input order. Set 1 to
|
||||
* force the pre-v0.42 serial dispatch.
|
||||
*/
|
||||
concurrency?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed a batch of texts via the gateway. Sub-batches of 100 so upstream
|
||||
* progress callbacks fire incrementally on large imports. The gateway owns
|
||||
* adaptive batch splitting and per-recipe token-budget logic; this paginator
|
||||
* is purely about progress-callback granularity.
|
||||
* owns progress-callback granularity and (#1818) bounded parallel dispatch
|
||||
* of the sub-batches — the embed-stale.ts worker-pool pattern, scoped down.
|
||||
*/
|
||||
const BATCH_SIZE = 100;
|
||||
const DEFAULT_EMBED_BATCH_CONCURRENCY = 4;
|
||||
|
||||
function resolveEmbedBatchConcurrency(options: EmbedBatchOptions): number {
|
||||
if (options.concurrency !== undefined) {
|
||||
return Math.max(1, Math.floor(options.concurrency));
|
||||
}
|
||||
const env = Number(process.env.GBRAIN_EMBED_BATCH_CONCURRENCY);
|
||||
if (Number.isFinite(env) && env >= 1) return Math.floor(env);
|
||||
return DEFAULT_EMBED_BATCH_CONCURRENCY;
|
||||
}
|
||||
|
||||
export async function embedBatch(
|
||||
texts: string[],
|
||||
options: EmbedBatchOptions = {},
|
||||
@@ -103,13 +122,44 @@ export async function embedBatch(
|
||||
if (texts.length <= BATCH_SIZE && !options.onBatchComplete) {
|
||||
return gatewayEmbed(texts, gwOpts);
|
||||
}
|
||||
const results: Float32Array[] = [];
|
||||
// #1818: dispatch sub-batches through a bounded worker pool instead of a
|
||||
// serial loop. Results are written into a preallocated index-addressed
|
||||
// array so output order matches input order regardless of completion
|
||||
// order; onBatchComplete reports a monotonic completed-embedding count.
|
||||
const slices: Array<{ start: number; texts: string[] }> = [];
|
||||
for (let i = 0; i < texts.length; i += BATCH_SIZE) {
|
||||
const slice = texts.slice(i, i + BATCH_SIZE);
|
||||
const out = await gatewayEmbed(slice, gwOpts);
|
||||
results.push(...out);
|
||||
options.onBatchComplete?.(results.length, texts.length);
|
||||
slices.push({ start: i, texts: texts.slice(i, i + BATCH_SIZE) });
|
||||
}
|
||||
const results = new Array<Float32Array>(texts.length);
|
||||
let next = 0;
|
||||
let done = 0;
|
||||
const numWorkers = Math.min(resolveEmbedBatchConcurrency(options), slices.length);
|
||||
// Once any sub-batch fails, `failed` stops the surviving workers from
|
||||
// dispatching FURTHER slices — the whole call is rejecting anyway, so
|
||||
// continuing would burn real provider spend in the background and fire
|
||||
// onBatchComplete after the caller already saw the failure (worst with
|
||||
// embedBatchWithBackoff, whose 429 backoff assumes nothing is in flight).
|
||||
// In-flight sibling calls still run to completion (bounded by numWorkers-1).
|
||||
let failed = false;
|
||||
const worker = async (): Promise<void> => {
|
||||
while (!failed && next < slices.length) {
|
||||
// NOTE: no local aborted-check here — an aborted signal makes the next
|
||||
// gatewayEmbed call throw (SDK-side), which rejects the pool. Returning
|
||||
// silently instead would resolve with holes in `results`.
|
||||
const slice = slices[next++];
|
||||
let out: Float32Array[];
|
||||
try {
|
||||
out = await gatewayEmbed(slice.texts, gwOpts);
|
||||
} catch (err) {
|
||||
failed = true;
|
||||
throw err;
|
||||
}
|
||||
for (let j = 0; j < out.length; j++) results[slice.start + j] = out[j];
|
||||
done += out.length;
|
||||
if (!failed) options.onBatchComplete?.(done, texts.length);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: numWorkers }, () => worker()));
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -39,6 +39,8 @@ import {
|
||||
__getShrinkStateForTests,
|
||||
} from '../../src/core/ai/gateway.ts';
|
||||
import { AIConfigError, AITransientError } from '../../src/core/ai/errors.ts';
|
||||
import { RECIPES } from '../../src/core/ai/recipes/index.ts';
|
||||
import type { Recipe } from '../../src/core/ai/types.ts';
|
||||
|
||||
// The last test in this file leaves the gateway configured with a remote
|
||||
// provider + fake key and a REAL embed transport. Without a final reset,
|
||||
@@ -93,6 +95,14 @@ function configureGoogle(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function configureDashscope(): void {
|
||||
configureGateway({
|
||||
embedding_model: 'dashscope:text-embedding-v3',
|
||||
embedding_dimensions: 1024,
|
||||
env: { DASHSCOPE_API_KEY: 'sk-fake' },
|
||||
});
|
||||
}
|
||||
|
||||
// --------- 1. Pure helpers ---------
|
||||
|
||||
describe('splitByTokenBudget (pure helper)', () => {
|
||||
@@ -149,6 +159,27 @@ describe('splitByTokenBudget (pure helper)', () => {
|
||||
expect(splitByTokenBudget(texts, 96_000, 0)).toEqual(splitByTokenBudget(texts, 96_000, 4));
|
||||
expect(splitByTokenBudget(texts, 96_000, -1)).toEqual(splitByTokenBudget(texts, 96_000, 4));
|
||||
});
|
||||
|
||||
// #1199: count cap for providers that reject batches by input count.
|
||||
test('max_batch_count flushes even when token budget has room', () => {
|
||||
const texts = Array.from({ length: 25 }, (_, i) => `t${i}`);
|
||||
const result = splitByTokenBudget(texts, 1_000_000, 4, 10);
|
||||
expect(result.map(b => b.length)).toEqual([10, 10, 5]);
|
||||
expect(result.flat()).toEqual(texts);
|
||||
});
|
||||
|
||||
test('token budget still governs alongside max_batch_count', () => {
|
||||
const texts = ['a'.repeat(50_000), 'b'.repeat(50_000), 'c'.repeat(50_000)];
|
||||
const result = splitByTokenBudget(texts, 96_000, 1, 10);
|
||||
expect(result).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('undefined / zero / negative max_batch_count is ignored', () => {
|
||||
const texts = Array.from({ length: 25 }, () => 'x');
|
||||
expect(splitByTokenBudget(texts, 1_000_000, 4, undefined)).toHaveLength(1);
|
||||
expect(splitByTokenBudget(texts, 1_000_000, 4, 0)).toHaveLength(1);
|
||||
expect(splitByTokenBudget(texts, 1_000_000, 4, -5)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isTokenLimitError (pure helper)', () => {
|
||||
@@ -179,6 +210,12 @@ describe('isTokenLimitError (pure helper)', () => {
|
||||
expect(isTokenLimitError(new Error('Exceeded 300000 max tokens per request'))).toBe(true);
|
||||
});
|
||||
|
||||
test('matches DashScope batch-count error (#1199)', () => {
|
||||
expect(isTokenLimitError(new Error(
|
||||
'InvalidParameter: batch size is invalid, it should not be larger than 10.',
|
||||
))).toBe(true);
|
||||
});
|
||||
|
||||
test('does not match unrelated errors', () => {
|
||||
expect(isTokenLimitError(new Error('Connection refused'))).toBe(false);
|
||||
expect(isTokenLimitError(new Error('Invalid API key'))).toBe(false);
|
||||
@@ -387,26 +424,92 @@ describe('shrink-on-miss adaptive cache', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// --------- 8. Pre-split count cap through public embed() (#1199 / #970) ---------
|
||||
|
||||
describe('embed() pre-split honors max_batch_count', () => {
|
||||
beforeEach(() => resetGateway());
|
||||
afterEach(() => __setEmbedTransportForTests(null));
|
||||
|
||||
test('dashscope never dispatches more than 10 inputs per call (#1199)', async () => {
|
||||
configureDashscope();
|
||||
const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 1024));
|
||||
__setEmbedTransportForTests(stub as any);
|
||||
|
||||
// 25 short texts fit trivially in the 8192-token budget; without the
|
||||
// count cap they'd ship as ONE batch and DashScope would reject it.
|
||||
const texts = Array.from({ length: 25 }, (_, i) => `short-${i}`);
|
||||
const result = await embed(texts);
|
||||
|
||||
expect(result).toHaveLength(25);
|
||||
const callLengths = stub.mock.calls.map(([arg]) => (arg as { values: string[] }).values.length);
|
||||
expect(Math.max(...callLengths)).toBeLessThanOrEqual(10);
|
||||
expect(callLengths.reduce((a, b) => a + b, 0)).toBe(25);
|
||||
// Order preserved across sub-batches.
|
||||
expect((stub.mock.calls[0][0] as { values: string[] }).values[0]).toBe('short-0');
|
||||
});
|
||||
|
||||
test('google pre-splits at 100 inputs per batchEmbedContents call (#970)', async () => {
|
||||
configureGoogle();
|
||||
const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 768));
|
||||
__setEmbedTransportForTests(stub as any);
|
||||
|
||||
const texts = Array.from({ length: 250 }, (_, i) => `g${i}`);
|
||||
const result = await embed(texts);
|
||||
|
||||
expect(result).toHaveLength(250);
|
||||
const callLengths = stub.mock.calls.map(([arg]) => (arg as { values: string[] }).values.length);
|
||||
expect(callLengths).toEqual([100, 100, 50]);
|
||||
});
|
||||
});
|
||||
|
||||
// --------- 7. Startup warning (D9-B) ---------
|
||||
|
||||
describe('startup warning for recipes missing max_batch_tokens', () => {
|
||||
beforeEach(() => resetGateway());
|
||||
|
||||
// #970 closed google's missing cap, so no registered recipe is capless
|
||||
// anymore. Inject a synthetic capless recipe to keep the warning path
|
||||
// covered for the NEXT recipe that forgets the field.
|
||||
const caplessRecipe: Recipe = {
|
||||
id: 'capless-test',
|
||||
name: 'Capless Test Provider',
|
||||
tier: 'openai-compat',
|
||||
implementation: 'openai-compatible',
|
||||
base_url_default: 'https://example.invalid/v1',
|
||||
auth_env: { required: [] },
|
||||
touchpoints: {
|
||||
embedding: { models: ['capless-embed-1'], default_dims: 768 },
|
||||
},
|
||||
};
|
||||
|
||||
function configureCapless(): void {
|
||||
configureGateway({
|
||||
embedding_model: 'capless-test:capless-embed-1',
|
||||
embedding_dimensions: 768,
|
||||
env: {},
|
||||
});
|
||||
}
|
||||
|
||||
test('configured missing-cap recipe warns once; unrelated recipes stay quiet', () => {
|
||||
const warnings: string[] = [];
|
||||
const original = console.warn;
|
||||
console.warn = (msg: string) => warnings.push(String(msg));
|
||||
RECIPES.set(caplessRecipe.id, caplessRecipe);
|
||||
try {
|
||||
configureOpenAI();
|
||||
expect(warnings.length).toBe(0);
|
||||
// #970 regression: google now declares max_batch_tokens → quiet.
|
||||
configureGoogle();
|
||||
expect(warnings.length).toBe(0);
|
||||
configureCapless();
|
||||
const firstCallCount = warnings.length;
|
||||
// Reconfigure: the warning should NOT re-fire for the same recipes
|
||||
// within one process (we already told the operator).
|
||||
configureGoogle();
|
||||
configureCapless();
|
||||
expect(warnings.length).toBe(firstCallCount);
|
||||
} finally {
|
||||
console.warn = original;
|
||||
RECIPES.delete(caplessRecipe.id);
|
||||
}
|
||||
|
||||
// The warning text should match the documented contract.
|
||||
@@ -415,11 +518,12 @@ describe('startup warning for recipes missing max_batch_tokens', () => {
|
||||
);
|
||||
expect(contractMatch.length).toBe(1);
|
||||
|
||||
// Voyage declares max_batch_tokens → suppressed. OpenAI is the
|
||||
// canonical fast-path recipe → also suppressed by id. Both must be
|
||||
// absent from the warnings.
|
||||
// Voyage + google declare max_batch_tokens → suppressed. OpenAI is the
|
||||
// canonical fast-path recipe → also suppressed by id. All must be
|
||||
// absent from the warnings; only the synthetic capless recipe fires.
|
||||
expect(warnings.find(w => w.includes('"voyage"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"openai"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"google"'))).toBeDefined();
|
||||
expect(warnings.find(w => w.includes('"google"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"capless-test"'))).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,16 +52,7 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
}
|
||||
});
|
||||
|
||||
test('configureGateway warns for google only when google embedding is configured', () => {
|
||||
warnSpy.mockClear();
|
||||
resetGateway();
|
||||
configureGateway({ env: {} });
|
||||
let messages = warnSpy.mock.calls.map(c => String(c[0] ?? ''));
|
||||
expect(
|
||||
messages.some(m => m.includes('"google"') && m.includes('without max_batch_tokens')),
|
||||
'google should not warn while OpenAI default is configured',
|
||||
).toBe(false);
|
||||
|
||||
test('configureGateway does NOT warn for google now that it declares batch caps (#970)', () => {
|
||||
warnSpy.mockClear();
|
||||
resetGateway();
|
||||
configureGateway({
|
||||
@@ -69,11 +60,20 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
embedding_dimensions: 768,
|
||||
env: { GOOGLE_GENERATIVE_AI_API_KEY: 'fake' },
|
||||
});
|
||||
messages = warnSpy.mock.calls.map(c => String(c[0] ?? ''));
|
||||
const messages = warnSpy.mock.calls.map(c => String(c[0] ?? ''));
|
||||
expect(
|
||||
messages.some(m => m.includes('"google"') && m.includes('without max_batch_tokens')),
|
||||
'google should warn when configured because it has fixed-cap models',
|
||||
).toBe(true);
|
||||
'google declares max_batch_tokens/max_batch_count since #970 — no warning',
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('google recipe declares its derived batch caps (#970)', () => {
|
||||
const e = getRecipe('google')!.touchpoints.embedding!;
|
||||
// Count cap is the REAL Gemini limit (batchEmbedContents: 100 inputs);
|
||||
// the token budget is derived (100 × 2048 per-input tokens), NOT the
|
||||
// 2048 per-input limit — copying that verbatim would over-split 50×.
|
||||
expect(e.max_batch_count).toBe(100);
|
||||
expect(e.max_batch_tokens).toBe(204_800);
|
||||
});
|
||||
|
||||
test('every recipe with empty models[] declares user_provided_models OR has openai-fast-path', () => {
|
||||
|
||||
@@ -55,6 +55,11 @@ describe('recipe: dashscope', () => {
|
||||
expect(r.touchpoints.embedding!.chars_per_token).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('declares max_batch_count: 10 — DashScope rejects larger batches (#1199)', () => {
|
||||
const r = getRecipe('dashscope')!;
|
||||
expect(r.touchpoints.embedding!.max_batch_count).toBe(10);
|
||||
});
|
||||
|
||||
test('dimsProviderOptions threads dimensions for text-embedding-v3 (Matryoshka)', async () => {
|
||||
// Codex finding #1: DashScope text-embedding-v3 is Matryoshka 64-1024.
|
||||
// Without `dimensions` on the wire, user-selected non-default dims are
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* #1818: embedBatch dispatches its 100-input sub-batches through a bounded
|
||||
* worker pool (the embed-stale.ts concurrency pattern) instead of a serial
|
||||
* `for` loop. This file pins:
|
||||
*
|
||||
* - output order matches input order regardless of completion order
|
||||
* (index-addressed results)
|
||||
* - parallelism actually happens (max in-flight > 1) and stays bounded
|
||||
* (max in-flight <= configured concurrency)
|
||||
* - concurrency: 1 restores the serial pre-#1818 dispatch
|
||||
* - GBRAIN_EMBED_BATCH_CONCURRENCY env is honored when the option is unset
|
||||
* - onBatchComplete reports a monotonic completed count ending at total
|
||||
*
|
||||
* Transport is stubbed via the gateway's __setEmbedTransportForTests seam
|
||||
* (same pattern as test/ai/adaptive-embed-batch.test.ts). OpenAI recipe =
|
||||
* fast path (no pre-split), so each embedBatch sub-batch is exactly one
|
||||
* transport call.
|
||||
*/
|
||||
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
configureGateway,
|
||||
resetGateway,
|
||||
__setEmbedTransportForTests,
|
||||
} from '../src/core/ai/gateway.ts';
|
||||
import { embedBatch } from '../src/core/embedding.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
const DIMS = 1536;
|
||||
|
||||
function configureOpenAI(): void {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
embedding_dimensions: DIMS,
|
||||
env: { OPENAI_API_KEY: 'sk-fake' },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a transport whose returned embedding encodes the GLOBAL input
|
||||
* index in dim 0 (texts are `t<N>`), so order can be asserted end-to-end.
|
||||
* Tracks the max number of concurrently in-flight transport calls.
|
||||
*/
|
||||
function installTrackingTransport(delayMs = 5): { maxInFlight: () => number } {
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
|
||||
inFlight++;
|
||||
maxInFlight = Math.max(maxInFlight, inFlight);
|
||||
await new Promise(r => setTimeout(r, delayMs));
|
||||
inFlight--;
|
||||
return {
|
||||
embeddings: values.map(v => {
|
||||
const idx = Number(v.slice(1));
|
||||
return Array.from({ length: DIMS }, (_, j) => (j === 0 ? idx : 0.1));
|
||||
}),
|
||||
};
|
||||
}) as any);
|
||||
return { maxInFlight: () => maxInFlight };
|
||||
}
|
||||
|
||||
const texts = Array.from({ length: 250 }, (_, i) => `t${i}`);
|
||||
|
||||
afterAll(() => resetGateway());
|
||||
|
||||
describe('embedBatch bounded parallelism (#1818)', () => {
|
||||
beforeEach(() => {
|
||||
resetGateway();
|
||||
configureOpenAI();
|
||||
});
|
||||
afterEach(() => {
|
||||
__setEmbedTransportForTests(null);
|
||||
});
|
||||
|
||||
test('default pool dispatches sub-batches in parallel, order preserved', async () => {
|
||||
const tracker = installTrackingTransport();
|
||||
const result = await embedBatch(texts, { onBatchComplete: () => {} });
|
||||
expect(result).toHaveLength(250);
|
||||
for (let i = 0; i < 250; i++) {
|
||||
expect(result[i][0]).toBe(i);
|
||||
}
|
||||
// 250 texts → 3 sub-batches; default concurrency 4 → all 3 in flight.
|
||||
expect(tracker.maxInFlight()).toBeGreaterThan(1);
|
||||
expect(tracker.maxInFlight()).toBeLessThanOrEqual(4);
|
||||
});
|
||||
|
||||
test('concurrency: 1 keeps the serial dispatch', async () => {
|
||||
const tracker = installTrackingTransport();
|
||||
const result = await embedBatch(texts, { concurrency: 1, onBatchComplete: () => {} });
|
||||
expect(result).toHaveLength(250);
|
||||
expect(tracker.maxInFlight()).toBe(1);
|
||||
});
|
||||
|
||||
test('GBRAIN_EMBED_BATCH_CONCURRENCY env bounds the pool when option unset', async () => {
|
||||
const tracker = installTrackingTransport();
|
||||
await withEnv({ GBRAIN_EMBED_BATCH_CONCURRENCY: '2' }, async () => {
|
||||
await embedBatch(texts, { onBatchComplete: () => {} });
|
||||
});
|
||||
expect(tracker.maxInFlight()).toBeGreaterThan(1);
|
||||
expect(tracker.maxInFlight()).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
test('onBatchComplete reports a monotonic count ending at total', async () => {
|
||||
installTrackingTransport();
|
||||
const seen: number[] = [];
|
||||
await embedBatch(texts, {
|
||||
onBatchComplete: (done, total) => {
|
||||
expect(total).toBe(250);
|
||||
seen.push(done);
|
||||
},
|
||||
});
|
||||
expect(seen).toHaveLength(3); // 100 + 100 + 50 sub-batches
|
||||
for (let i = 1; i < seen.length; i++) {
|
||||
expect(seen[i]).toBeGreaterThan(seen[i - 1]);
|
||||
}
|
||||
expect(seen[seen.length - 1]).toBe(250);
|
||||
});
|
||||
|
||||
test('a failing sub-batch rejects the whole call', async () => {
|
||||
let call = 0;
|
||||
__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
|
||||
call++;
|
||||
if (call === 2) throw new Error('boom');
|
||||
await new Promise(r => setTimeout(r, 2));
|
||||
return { embeddings: values.map(() => Array.from({ length: DIMS }, () => 0.1)) };
|
||||
}) as any);
|
||||
await expect(embedBatch(texts, { onBatchComplete: () => {} })).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('after a failure, surviving workers stop dispatching new slices', async () => {
|
||||
// 1000 texts → 10 slices, concurrency 2. First call fails immediately;
|
||||
// without the `failed` flag the second worker would keep draining all
|
||||
// 10 slices in the background AFTER embedBatch already rejected —
|
||||
// burning provider spend and firing onBatchComplete post-rejection.
|
||||
let calls = 0;
|
||||
const completions: number[] = [];
|
||||
__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
|
||||
calls++;
|
||||
if (calls === 1) throw new Error('boom');
|
||||
await new Promise(r => setTimeout(r, 5));
|
||||
return { embeddings: values.map(() => Array.from({ length: DIMS }, () => 0.1)) };
|
||||
}) as any);
|
||||
const many = Array.from({ length: 1000 }, (_, i) => `t${i}`);
|
||||
await expect(
|
||||
embedBatch(many, { concurrency: 2, onBatchComplete: d => completions.push(d) }),
|
||||
).rejects.toThrow('boom');
|
||||
const callsAtRejection = calls;
|
||||
await new Promise(r => setTimeout(r, 50)); // would-be background drain window
|
||||
expect(calls).toBe(callsAtRejection); // no new dispatch after rejection
|
||||
expect(calls).toBeLessThanOrEqual(2); // only the in-flight sibling ran
|
||||
expect(completions).toHaveLength(0); // no progress reported after failure
|
||||
});
|
||||
|
||||
test('single small batch without callback stays on the one-call fast path', async () => {
|
||||
const tracker = installTrackingTransport(1);
|
||||
const result = await embedBatch(['t0', 't1', 't2']);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[1][0]).toBe(1);
|
||||
expect(tracker.maxInFlight()).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
* overwrites this preload.
|
||||
*/
|
||||
import { configureGateway, getEmbeddingDimensions } from '../../src/core/ai/gateway.ts';
|
||||
import { beforeEach } from 'bun:test';
|
||||
import { afterEach, beforeEach } from 'bun:test';
|
||||
|
||||
const LEGACY_CONFIG = {
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
@@ -52,7 +52,7 @@ applyLegacy();
|
||||
// 2. file-local beforeAll → may overwrite to ZE/1280
|
||||
// Since beforeAll runs once per file BEFORE the first beforeEach,
|
||||
// file-local beforeAll wins for that file's tests. ✓
|
||||
beforeEach(() => {
|
||||
function applyLegacyIfEmpty() {
|
||||
try {
|
||||
// Only re-apply if the gateway was reset (or never configured).
|
||||
// Tests that explicitly configured a different model in their
|
||||
@@ -62,4 +62,28 @@ beforeEach(() => {
|
||||
} catch {
|
||||
applyLegacy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(applyLegacyIfEmpty);
|
||||
|
||||
// PR #3130 shard-order fix: beforeEach alone leaves ONE window open — a file
|
||||
// whose LAST afterEach calls resetGateway() poisons the NEXT file's
|
||||
// beforeAll, which runs BEFORE any beforeEach fires. A beforeAll there that
|
||||
// does engine.initSchema() then sizes the embedding column from the gateway
|
||||
// DEFAULTS (zembed-1/1280d) instead of the pinned legacy 1536, and every
|
||||
// 1536-d Float32Array fixture in that file dies with
|
||||
// "expected 1280 dimensions, not 1536". Which file pair collides is a
|
||||
// function of shard composition, so adding/removing ANY test file can
|
||||
// surface it (that is exactly how it bit shard 9).
|
||||
//
|
||||
// Preload hooks are registered before any file-local hooks, and bun runs
|
||||
// after-hooks inside-out (file-local afterEach first, then this one), so
|
||||
// this repairs the empty slot immediately after the poisoning reset —
|
||||
// before the next file's beforeAll can observe it.
|
||||
//
|
||||
// Known remaining window: a file whose afterAll() resets the gateway (no
|
||||
// hook runs between its afterAll and the next file's beforeAll). Files
|
||||
// that reset in afterAll and can precede a schema-creating file should
|
||||
// re-apply their own config, or the victim file should configureGateway()
|
||||
// explicitly in its beforeAll.
|
||||
afterEach(applyLegacyIfEmpty);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* #1207: `gbrain import` without `--workers` used to hardcode workerCount=1,
|
||||
* so a large Postgres import paid one serial embedding round-trip per file.
|
||||
* runImport now routes the default through the shared autoConcurrency policy
|
||||
* (PGLite → 1, >100 files on Postgres → DEFAULT_PARALLEL_WORKERS), while an
|
||||
* explicit `--workers N` still wins.
|
||||
*
|
||||
* The engine here is a minimal postgres-kind stub with no database_url in
|
||||
* config — runImport's parallel branch then falls back to serial processing
|
||||
* (its PR #490 guard) but the WORKER-COUNT DECISION (the thing #1207 fixes)
|
||||
* is still observable via the "Using N parallel workers" log line. Per-file
|
||||
* imports fail against the stub engine and are swallowed by runImport's
|
||||
* per-file catch; that's fine — this test pins the policy, not the import.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, writeFileSync, mkdirSync, rmSync, realpathSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
import { runImport } from '../src/commands/import.ts';
|
||||
|
||||
const fakePostgresEngine = {
|
||||
kind: 'postgres',
|
||||
executeRaw: async () => [],
|
||||
logIngest: async () => {},
|
||||
setConfig: async () => {},
|
||||
getConfig: async () => null,
|
||||
} as any;
|
||||
|
||||
let workspace: string;
|
||||
let brainDir: string;
|
||||
let logs: string[];
|
||||
const realLog = console.log;
|
||||
|
||||
beforeEach(() => {
|
||||
workspace = mkdtempSync(join(tmpdir(), 'gbrain-import-workers-home-'));
|
||||
mkdirSync(join(workspace, '.gbrain'), { recursive: true });
|
||||
brainDir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-import-workers-brain-')));
|
||||
// 101 files: one past AUTO_CONCURRENCY_FILE_THRESHOLD (100).
|
||||
for (let i = 0; i < 101; i++) {
|
||||
writeFileSync(join(brainDir, `page-${i}.md`), `# Page ${i}\n\nbody ${i}\n`);
|
||||
}
|
||||
logs = [];
|
||||
console.log = (msg?: unknown) => logs.push(String(msg));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.log = realLog;
|
||||
rmSync(workspace, { recursive: true, force: true });
|
||||
rmSync(brainDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('import default worker count (#1207)', () => {
|
||||
test('no --workers flag → autoConcurrency picks 4 for >100 files on Postgres', async () => {
|
||||
await withEnv({ GBRAIN_HOME: join(workspace, '.gbrain'), GBRAIN_SOURCE: undefined }, async () => {
|
||||
await runImport(fakePostgresEngine, [brainDir, '--no-embed'], { sourceId: 'default' });
|
||||
});
|
||||
expect(logs.some(l => l.includes('Using 4 parallel workers'))).toBe(true);
|
||||
});
|
||||
|
||||
test('explicit --workers 2 still wins over the auto policy', async () => {
|
||||
await withEnv({ GBRAIN_HOME: join(workspace, '.gbrain'), GBRAIN_SOURCE: undefined }, async () => {
|
||||
await runImport(fakePostgresEngine, [brainDir, '--no-embed', '--workers', '2'], { sourceId: 'default' });
|
||||
});
|
||||
expect(logs.some(l => l.includes('Using 2 parallel workers'))).toBe(true);
|
||||
expect(logs.some(l => l.includes('Using 4 parallel workers'))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -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