Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(pages): 24 MiB page ceiling, per-page embedding cap, linear delimiter split

garrytana22a36d2246c
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts
index 3e1aa69ead..5a50319e16 100644
--- a/src/cli/commands/embed.ts
+++ b/src/cli/commands/embed.ts
@@ -80,8 +80,10 @@ async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<{ au
/** `gbrain embed --help` (answered without a brain) and the usage error. */
const EMBED_USAGE = [
- 'Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --facts',
+ 'Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --facts',
' Embeds chunks without a vector (--stale; --catch-up keeps going until the backlog is empty) or re-embeds pages (--all, a slug, --slugs).',
+ ' A page over 1 MiB spends at most embed.max_usd_per_page (default $2) and embeds its newest chunks first; --held lists the pages a cap or a',
+ ' pending approval stopped, with the cost to finish, and --held --max-usd N (or --slugs <slug> --max-usd N) approves N more per page.',
' It calls the configured embedding provider, which bills per token: without a terminal it stops with exit 3 and the consent payload',
' unless --yes (cap: the estimate x1.5), --max-usd N, spend.posture=tokenmax or a per-run preapproval covers it. Pass those only after',
' the user agrees. --dry-run previews with no provider calls. Local providers that bill nothing (ollama, llama-server, lmstudio) need no approval.',
diff --git a/src/cli/main.ts b/src/cli/main.ts
index bbc5bcb8ba..4225c2c7f4 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -48,6 +48,7 @@ import { curatedFlagError } from './help/validate.ts';
import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli-error.ts';
import type { Notice } from '../core/agent-output.ts';
import { opError, opOwnsSource } from '../core/ops/contract.ts';
+import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
import { opParamValue } from './op-param-values.ts';
import { serializeMarkdown } from '../core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';
@@ -1156,7 +1157,7 @@ export async function applyStdinParam(
params: Record<string, unknown>,
): Promise<void> {
// Branch shape (stdin hint + missing param + `!process.stdin.isTTY` gate +
- // 5MB cap) is pinned by the R4 regression test for PR #1325's Windows fix
+ // page-ceiling cap) is pinned by the R4 regression test for PR #1325's Windows fix
// (test/cycle/regression-pr-wave-r1-r2-r4.test.ts) — keep the spelling.
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
const content = await readStdinBounded();
@@ -1167,9 +1168,10 @@ export async function applyStdinParam(
// empty write; leaving the param unset makes the required-param usage
// error fire instead (same fail-fast as the #3513 timeout path).
if (content.trim() === '') return;
- const MAX_STDIN = 5_000_000; // 5MB
+ const MAX_STDIN = PAGE_MAX_BYTES; // the 24 MiB page ceiling
if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
- exitCliError(opError('payload_too_large', `stdin content exceeds ${MAX_STDIN} bytes.`, 'Split the content into smaller inputs.'), op.cliHints?.name ?? op.name);
+ exitCliError(opError('payload_too_large', `stdin content exceeds ${MAX_STDIN} bytes (the 24 MiB page ceiling).`,
+ 'Nothing was written. A page larger than the ceiling cannot be stored in this version; see docs/guides/memory-boundaries.md#large-pages.'), op.cliHints?.name ?? op.name);
}
params[op.cliHints.stdin] = content;
}
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 5f6a3314c3..36e1e81ef1 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -50,6 +50,7 @@ import { resolveEmbedConcurrency } from '../core/embed-concurrency.ts';
export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } from '../core/embed-concurrency.ts';
import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';
import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';
+import { estimatePageEmbedUsd, listBudgetLimitedPages, planPageEmbedding, type PageEmbedGrant } from '../core/page-embedding-budget.ts';
import {
restampIfDemotedToTitleTier,
embedBatchWithBackoff,
@@ -148,6 +149,12 @@ export interface EmbedOpts {
slugs?: string[];
/** Embed a single page. */
slug?: string;
+ /**
+ * The user's explicit `--max-usd N` on a `--slugs`/`--held` run: lifts a
+ * large page's embedding hold and raises its per-page cap by N
+ * (page-embedding-budget.ts). Set only by the foreground CLI.
+ */
+ approvedPageCapUsd?: number;
/**
* v0.31.12: scope to a specific source. When set, only pages from this
* source are embedded. When omitted, all sources are processed (but
@@ -478,7 +485,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
for (const s of opts.slugs) {
if (isAborted(opts.signal)) break; // #1737: stop the per-slug loop on abort
try {
- await embedPage(engine, s, !!opts.dryRun, result, opts.sourceId, opts.signal, opts.quiet);
+ await embedPage(engine, s, !!opts.dryRun, result, opts.sourceId, opts.signal, opts.quiet, opts.approvedPageCapUsd);
} catch (e: unknown) {
if (isAborted(opts.signal)) break; // shutdown, not a failure
// #3037: a page-level error (not found, DB write) must not exit 0.
@@ -813,7 +820,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
return result;
}
if (opts.slug) {
- await embedPage(engine, opts.slug, !!opts.dryRun, result, opts.sourceId, opts.signal, opts.quiet);
+ await embedPage(engine, opts.slug, !!opts.dryRun, result, opts.sourceId, opts.signal, opts.quiet, opts.approvedPageCapUsd);
return result;
}
throw new Error('No embed target specified. Pass { slug }, { slugs }, { all }, or { stale }.');
@@ -905,6 +912,31 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
};
}
+ if (args.includes('--held')) {
+ const say = args.includes('--json') ? serr : slog;
+ if (args.includes('--background')) {
+ serr('[embed] --held runs in the foreground: the per-page approval is not carried into background jobs.');
+ process.exit(1);
+ }
+ const heldSourceIdx = args.indexOf('--source');
+ const limited = await listBudgetLimitedPages(engine, heldSourceIdx >= 0 ? { sourceId: args[heldSourceIdx + 1] } : {});
+ if (limited.length === 0) {
+ say('[embed] No large pages are held or capped by embed.max_usd_per_page.');
+ return { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun: args.includes('--dry-run'), chunkless_pages_healed: 0 };
+ }
+ const heldSignature = currentEmbeddingSignature();
+ for (const row of limited) {
+ say(`[embed] ${row.slug} (${row.source_id}): ${row.state}${row.reason ? ` (${row.reason})` : ''}, ${row.pending_chunks} chunk(s) without a vector, `
+ + `spent $${row.spent_usd.toFixed(2)}, about $${estimatePageEmbedUsd(row.pending_chars, heldSignature).toFixed(2)} to finish`);
+ }
+ const sources = [...new Set(limited.map(row => row.source_id))];
+ if (sources.length > 1) {
+ serr(`[embed] Held pages span ${sources.length} sources; one approval covers one source. Run per source: ${sources.map(id => `gbrain embed --held --source ${id} --max-usd <N>`).join('; ')}`);
+ process.exit(1);
+ }
+ const rest = args.filter((a, i) => a !== '--held' && a !== '--source' && args[i - 1] !== '--source');
+ return runEmbed(engine, [...rest, '--source', sources[0], '--slugs', ...limited.map(row => row.slug)], selectedConfig, consent);
+ }
const authorization = consent?.authorization ?? null;
const costCap = args.includes('--dry-run') || args.includes('--background') ? null : embedCostCap(authorization?.cap_usd, authorization?.cap_source);
if (args.includes('--images')) return (await import('../core/embed-stale-images.ts')).runEmbedStaleImagesCli(engine, args, costCap); // lazy: keeps import-file out of embed's graph
@@ -971,14 +1003,15 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
let opts: EmbedOpts;
if (slugsIdx >= 0) {
- opts = { slugs: slugsAfter(args, slugsIdx), dryRun, sourceId, batchSize, priority, catchUp };
+ const approvedPageCapUsd = authorization?.via === 'max_usd' && authorization.cap_usd !== null ? authorization.cap_usd : undefined;
+ opts = { slugs: slugsAfter(args, slugsIdx), dryRun, sourceId, batchSize, priority, catchUp, ...(approvedPageCapUsd !== undefined && { approvedPageCapUsd }) };
} else if (all || stale) {
// E-2: CLI-only single-flight for stale runs (the minion path locks itself).
opts = { all, stale, dryRun, sourceId, batchSize, priority, catchUp, ...(pace && { pace }), ...(stale && { singleFlight: true }), ...(includeNullSignature && { includeNullSignature: true }) };
} else {
const slug = args.find(a => !a.startsWith('--'));
if (!slug) {
- serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--yes | --max-usd N] | --stale --images (gbrain embed --help: paid runs need the user\'s approval)');
+ serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--yes | --max-usd N] | --stale --images (gbrain embed --help: paid runs need the user\'s approval)');
process.exit(1);
}
opts = { slug, dryRun, sourceId, batchSize, priority, catchUp };
@@ -1061,6 +1094,7 @@ async function embedPage(
sourceId?: string,
signal?: AbortSignal,
quiet?: boolean,
+ approvedPageCapUsd?: number,
) {
const opts = sourceId ? { sourceId } : undefined;
const initial = await engine.readPageSnapshot(slug, opts);
@@ -1124,7 +1158,7 @@ async function embedPage(
// keying on embedded_at alone silently no-ops ("all chunks already
// embedded") on a rebuild-darkened page. Older callers that selected chunks
// without the boolean fall back to embedded_at.
- const toEmbed = chunks.filter(c => !c.embedded_at || c.embedding_is_null === true);
+ let toEmbed = chunks.filter(c => !c.embedded_at || c.embedding_is_null === true);
result.total_chunks += chunks.length;
result.skipped += chunks.length - toEmbed.length;
@@ -1156,6 +1190,24 @@ async function embedPage(
recordFailure(result, toEmbed.length, slug, EMBED_UNAVAILABLE_MESSAGE);
return;
}
+ // A large page is metered as a whole under embed.max_usd_per_page (page-embedding-budget.ts).
+ const decision = await planPageEmbedding(engine, prepared.snapshot.page, toEmbed,
+ { signature: currentEmbeddingSignature(), ...(approvedPageCapUsd !== undefined && { approvedCapUsd: approvedPageCapUsd }) });
+ if (decision.kind === 'held') {
+ serr(` ${slug}: embedding held (${decision.reason}); the page stays keyword-searchable. Approve with: gbrain embed --slugs ${slug} --max-usd <N>`);
+ result.pages_processed++;
+ return;
+ }
+ const grant = decision.kind === 'grant' ? decision.grant : undefined;
+ if (grant) {
+ toEmbed = toEmbed.filter(c => grant.chunkIndexes.has(c.chunk_index));
+ if (grant.deferred) serr(` ${slug}: per-page cap $${grant.capUsd} reached; ${grant.deferred} older chunk(s) stay keyword-only until it rises (gbrain embed --slugs ${slug} --max-usd <N>)`);
+ if (toEmbed.length === 0) {
+ await grant.settle({ ok: true });
+ result.pages_processed++;
+ return;
+ }
+ }
let embeddings: (Float32Array | null)[];
let failed = 0;
let firstError: unknown;
@@ -1164,7 +1216,9 @@ async function embedPage(
wrapChunkTextsForStoredMode(prepared.snapshot.page, toEmbed),
signal ? { abortSignal: signal } : {},
));
+ await grant?.settle({ ok: true });
} catch (e: unknown) {
+ await grant?.settle({ ok: false }).catch(() => {});
if (isAborted(signal)) throw e;
recordFailure(result, toEmbed.length, slug, e);
result.pages_processed++;
@@ -2008,6 +2062,7 @@ async function embedAllStale(
async function embedOneKey(key: string) {
let stale = byKey.get(key)!;
+ let grant: PageEmbedGrant | undefined;
const census = stale.length;
const keySourceId = stale[0]?.source_id ?? 'default';
const slug = stale[0].slug;
@@ -2054,8 +2109,20 @@ async function embedAllStale(
.map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
if (!stale.length) return;
const pageRow = prepared.snapshot.page;
+ // Large pages are metered as a whole under embed.max_usd_per_page (page-embedding-budget.ts).
+ const decision = await planPageEmbedding(engine, pageRow, existing.filter(c => !c.embedded_at), { signature });
+ if (decision.kind === 'held') return;
+ grant = decision.kind === 'grant' ? decision.grant : undefined;
+ if (grant) {
+ const granted = grant.chunkIndexes;
+ stale = existing.filter(c => granted.has(c.chunk_index)).map(c => ({ ...(selected.get(c.chunk_index) ?? { source_id: keySourceId, slug, page_id: pageRow.id }), ...c }));
+ if (grant.deferred) serr(`\n ${slug}: per-page cap reached; ${grant.deferred} older chunk(s) stay keyword-only until it rises (gbrain embed --slugs ${slug} --max-usd <N>)`);
+ if (!stale.length) { await grant.settle({ ok: true }); grant = undefined; return; }
+ }
const { embeddings, failed, firstError } = await embedPageTexts(
wrapChunkTextsForStoredMode(pageRow, stale), { abortSignal: effectiveSignal });
+ await grant?.settle({ ok: true });
+ grant = undefined;
const staleIdxToEmbedding = new Map<number, Float32Array>();
for (let j = 0; j < stale.length; j++) {
const emb = embeddings[j];
@@ -2093,6 +2160,8 @@ async function embedAllStale(
// embed failure throws) — progress, so the quarantine counter resets.
_embedFailureCounts.delete(key);
} catch (e: unknown) {
+ await grant?.settle({ ok: false }).catch(() => {});
+ grant = undefined;
// Budget/abort-fired cancellations are expected on the way out; don't
// spam per-page "Error embedding" lines when we're shutting down.
if (effectiveSignal.aborted) return;
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index 39f53e0822..a9ca0e2fb4 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -18,7 +18,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { serr } from '../../core/console-prefix.ts';
import { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';
import { RECOVERY_VERSION } from '../../core/frontmatter-recovery.ts';
-import { MAX_FILE_SIZE, contentRefusalFromReceipt, isContentRefusal, type ContentRefusal } from '../../core/import-screen.ts';
+import { importSizeLimit, contentRefusalFromReceipt, isContentRefusal, type ContentRefusal } from '../../core/import-screen.ts';
import { slugConflictHoldMessage, type ImportResult } from '../../core/import-file.ts';
import { classifyImportHold, parseMarkdown } from '../../core/markdown.ts';
import { readSourceFileSync } from '../../core/minions/source-filesystem.ts';
@@ -85,7 +85,7 @@ export async function openLegacyHolds(engine: BrainEngine, sourceId: string | un
/** sha256 of the exact string legacy import reads (BOM stripped), or null when the file is over the size limit. */
function readImportContent(filePath: string): { content: string; upstreamVersion: string } | null {
- if (lstatSync(filePath).size > MAX_FILE_SIZE) return null;
+ if (lstatSync(filePath).size > importSizeLimit(filePath)) return null;
const content = readSourceFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
return { content, upstreamVersion: createHash('sha256').update(content).digest('hex') };
}
@@ -138,7 +138,7 @@ export function screenLegacyFile(filePath: string, relPath: string, activePack?:
} catch {
return { refusal: null, upstreamVersion: null };
}
- if (!read) return { refusal: { code: 'file_too_large', message: `File too large (${lstatSync(filePath).size} bytes, max ${MAX_FILE_SIZE}).` }, upstreamVersion: null };
+ if (!read) return { refusal: { code: 'file_too_large', message: `File too large (${lstatSync(filePath).size} bytes, max ${importSizeLimit(filePath)}).` }, upstreamVersion: null };
if (hasMalformedPathSegment(relPath) || isCodeFilePath(relPath)) return { refusal: null, upstreamVersion: read.upstreamVersion };
const parsed = parseMarkdown(read.content, relPath, { validate: true, ...(activePack ? { activePack } : {}) });
const refusal = classifyImportHold(parsed, { expectedSlug: slugifyPath(relPath) || null, slugConflictMessage: (_found, expected) => slugConflictHoldMessage(relPath, expected) });
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.ts
index ea571de735..1aca5f2b20 100644
--- a/src/core/chunkers/recursive.ts
+++ b/src/core/chunkers/recursive.ts
@@ -264,42 +264,34 @@ function recursiveSplit(text: string, level: number, target: number): string[] {
/**
* Split text at delimiter boundaries, preserving delimiters at the end
* of the piece that precedes them (lossless).
+ *
+ * Linear: each delimiter's next occurrence is cached and searched again only
+ * once the cursor passes it, so a delimiter absent from the text costs one
+ * scan, not one per piece (a 24 MiB single-paragraph page used to rescan the
+ * whole remainder for every sentence).
*/
function splitAtDelimiters(text: string, delimiters: string[]): string[] {
const pieces: string[] = [];
- let remaining = text;
+ const next = delimiters.map(delim => text.indexOf(delim));
+ let cursor = 0;
- while (remaining.length > 0) {
+ while (cursor < text.length) {
let earliest = -1;
- let earliestDelim = '';
-
- for (const delim of delimiters) {
- const idx = remaining.indexOf(delim);
- if (idx !== -1 && (earliest === -1 || idx < earliest)) {
- earliest = idx;
- earliestDelim = delim;
+ let earliestLength = 0;
+ for (let d = 0; d < delimiters.length; d++) {
+ if (next[d] !== -1 && next[d] < cursor) next[d] = text.indexOf(delimiters[d], cursor);
+ if (next[d] !== -1 && (earliest === -1 || next[d] < earliest)) {
+ earliest = next[d];
+ earliestLength = delimiters[d].length;
}
}
-
- if (earliest === -1) {
- pieces.push(remaining);
- break;
- }
-
- // Include the delimiter with the preceding text
- const piece = remaining.slice(0, earliest + earliestDelim.length);
- if (piece.trim().length > 0) {
- pieces.push(piece);
- }
- remaining = remaining.slice(earliest + earliestDelim.length);
- }
-
- // Handle trailing content
- if (remaining.trim().length > 0 && !pieces.includes(remaining)) {
- // Already added above
+ const end = earliest === -1 ? text.length : earliest + earliestLength;
+ const piece = text.slice(cursor, end);
+ if (piece.trim().length > 0) pieces.push(piece);
+ cursor = end;
}
- return pieces.filter(p => p.trim().length > 0);
+ return pieces;
}
/**
diff --git a/src/core/content-sanity.ts b/src/core/content-sanity.ts
index 68a820160d..d5f5420a05 100644
--- a/src/core/content-sanity.ts
+++ b/src/core/content-sanity.ts
@@ -44,6 +44,7 @@
* is honored by the CALLER (import-file.ts), not by this module. The
* assessor stays pure so unit tests don't need env mutation.
*/
+import { isLargePageBytes, PAGE_MAX_BYTES } from './page-size-policy.ts';
/** Maximum number of body bytes scanned for pattern matches. The body
* is sliced to this size before regex/substring evaluation so pattern
@@ -58,12 +59,12 @@ export const SCAN_HEAD_BYTES = 2048;
* stderr warn. Page still writes. */
export const DEFAULT_BYTES_WARN = 50_000;
-/** Default block threshold. Operator override via
+/** Default block threshold: the page ceiling (page-size-policy.ts), so size
+ * alone never decides searchability below it. Operator override via
* `content_sanity.bytes_block` config key or `GBRAIN_PAGE_BLOCK_BYTES`
- * env var. Above this, page writes but `frontmatter.embed_skip` is set
- * and the embedder skips on next sweep. Page is still queryable; just
- * not searchable until manually re-embedded or split. */
-export const DEFAULT_BYTES_BLOCK = 500_000;
+ * env var. Above an operator's lower value the page writes with
+ * `frontmatter.embed_skip` and zero chunks, as before. */
+export const DEFAULT_BYTES_BLOCK = PAGE_MAX_BYTES;
/** Default max markup ratio. When the prose pass runs (warn-tier window,
* `prose_check_enabled`, non-code page) and `markup_ratio` exceeds this,
@@ -325,6 +326,55 @@ export function assessProse(body: string): ProseAssessment {
return { prose_chars, total_chars, markup_ratio: ratio };
}
+/** Characters in each head / middle / tail window of a large-page sample. */
+export const JUNK_SAMPLE_CHARS = 65_536;
+
+/** The head, middle and tail windows of `body` (the whole body when it is shorter than three windows). */
+export function sampleWindows(body: string, size = JUNK_SAMPLE_CHARS): string[] {
+ if (body.length <= size * 3) return [body];
+ const middle = Math.floor((body.length - size) / 2);
+ return [body.slice(0, size), body.slice(middle, middle + size), body.slice(body.length - size)];
+}
+
+/** assessProse over the sample windows: their summed prose and character counts. */
+function sampledProse(body: string): ProseAssessment {
+ const parts = sampleWindows(body).map(assessProse);
+ const total_chars = parts.reduce((n, part) => n + part.total_chars, 0);
+ const prose_chars = parts.reduce((n, part) => n + part.prose_chars, 0);
+ return { prose_chars, total_chars, markup_ratio: total_chars ? Math.min(1, Math.max(0, (total_chars - prose_chars) / total_chars)) : 0 };
+}
+
+export interface SampledJunkAssessment {
+ junk: boolean;
+ /** `sampled_markup_heavy` when every window is over the markup ratio; `sampled_junk_pattern` when two or more windows open with a junk pattern or operator literal. */
+ reasons: Array<'sampled_markup_heavy' | 'sampled_junk_pattern'>;
+ /** Markup ratio of each window, in head / middle / tail order. */
+ markup_ratios: number[];
+}
+
+/**
+ * The junk check a large page gets before it is embedded (the import-time
+ * scan reads only the first 2 KB). Boilerplate walls (the 890K-char nav dump
+ * the 500 KB block was first written for) read as markup in every window;
+ * a scraped error page repeats its pattern through the body. One hit in one
+ * window is not enough: a conversation may quote any of the patterns.
+ */
+export function assessSampledJunk(body: string, opts: { max_markup_ratio?: number;
+ extra_literals?: ReadonlyArray<OperatorLiteral>; disabled_patterns?: ReadonlyArray<string> }): SampledJunkAssessment {
+ const windows = sampleWindows(body);
+ const markup_ratios = windows.map(window => assessProse(window).markup_ratio);
+ const max = opts.max_markup_ratio ?? DEFAULT_MAX_MARKUP_RATIO;
+ const hits = windows.filter(window => {
+ const r = assessContentSanity({ compiled_truth: window, timeline: '', title: '', bytes_warn: Infinity, bytes_block: Infinity,
+ prose_check_enabled: false, extra_literals: opts.extra_literals, disabled_patterns: opts.disabled_patterns });
+ return r.junk_pattern_matches.length + r.literal_substring_matches.length > 0;
+ }).length;
+ const reasons: SampledJunkAssessment['reasons'] = [];
+ if (windows.length === 3 && markup_ratios.every(ratio => ratio > max)) reasons.push('sampled_markup_heavy');
+ if (hits >= 2) reasons.push('sampled_junk_pattern');
+ return { junk: reasons.length > 0, reasons, markup_ratios };
+}
+
/**
* Assess a parsed page against the size + junk-pattern + prose surface.
*
@@ -444,7 +494,9 @@ export function assessContentSanity(opts: {
let high_markup = false;
const inProseWindow = bytes > bytes_warn && bytes <= bytes_block;
if (prose_check_enabled && inProseWindow && opts.page_kind !== 'code') {
- const prose = assessProse(body);
+ // A large page is judged on its head, middle and tail windows, so the
+ // regex pass stays bounded however big the page is.
+ const prose = isLargePageBytes(bytes) ? sampledProse(body) : assessProse(body);
prose_chars = prose.prose_chars;
markup_ratio = prose.markup_ratio;
high_markup = markup_ratio > max_markup_ratio;
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 48ac03ba14..b1af07a50b 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -104,6 +104,7 @@ const ROWS: readonly Row[] = [
['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],
['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],
['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],
+ ['page_embedding_budget', 'out_of_scope', 'no_memory_text', 'state reason embedding_signature'],
['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],
['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],
['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index ee819e3305..89d205e953 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -34,6 +34,7 @@ import {
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';
import { AbortError } from './abort-check.ts';
+import { planPageEmbedding, type PageEmbedGrant } from './page-embedding-budget.ts';
/**
* W0 fix-wave (Tier-1 #3, CONFIRMED): the ONE carry-through field list for
@@ -520,6 +521,7 @@ export async function embedStaleForSource(
async function embedOneKey(key: string): Promise<void> {
let stale = byKey.get(key)!;
+ let grant: PageEmbedGrant | undefined;
const keySourceId = stale[0]?.source_id ?? sourceId;
const slug = stale[0].slug;
try {
@@ -554,9 +556,21 @@ export async function embedStaleForSource(
.map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
if (!stale.length) return;
const pageRow = prepared.snapshot.page;
+ // A large page is metered as a whole (page-embedding-budget.ts): its
+ // newest stale chunks that fit the per-page cap, whatever batch listed it.
+ const decision = await planPageEmbedding(engine, pageRow, existing.filter(c => !c.embedded_at), { signature });
+ if (decision.kind === 'held') return;
+ grant = decision.kind === 'grant' ? decision.grant : undefined;
+ if (grant) {
+ const granted = grant.chunkIndexes;
+ stale = existing.filter(c => granted.has(c.chunk_index)).map(c => ({ ...(selected.get(c.chunk_index) ?? { source_id: keySourceId, slug, page_id: pageRow.id }), ...c }));
+ if (!stale.length) { await grant.settle({ ok: true }); grant = undefined; return; }
+ }
await opts.assertOwned?.();
if (stopped()) return;
const embeddings = await embedFn(wrapChunkTextsForStoredMode(pageRow, stale), { abortSignal: signal });
+ await grant?.settle({ ok: true });
+ grant = undefined;
if (stopped()) return;
const dimensions = signature ? splitEmbeddingSignature(signature).dims
: prepared.embeddingColumn.name === 'embedding' ? (await readContentChunksEmbeddingDim(engine)).dims : prepared.embeddingColumn.dimensions;
@@ -590,6 +604,8 @@ export async function embedStaleForSource(
result.embedded += stale.length;
result.pagesProcessed += 1;
} catch (e: unknown) {
+ await grant?.settle({ ok: false }).catch(() => {});
+ grant = undefined;
result.failures = (result.failures ?? 0) + stale.length;
// Aborted mid-fetch is expected; treat as graceful exit.
if (stopped()) return;
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index a9ae56e996..0655d50ead 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -90,6 +90,7 @@ export function falseStampPageWhere(colId: string, signatureParam = 1, modelPara
p.embedding_signature = $${signatureParam}
AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND EXISTS (
SELECT 1 FROM content_chunks c
WHERE c.page_id = p.id AND c.${colId} IS NOT NULL
@@ -173,6 +174,7 @@ export async function countRestampOnlyChunks(
`SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
WHERE p.deleted_at IS NULL AND ${sigClause}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND ($4::text IS NULL OR p.source_id = $4)
AND ${currentSpaceChunkPredicate(colId, 2, 3)}`,
[opts.signature, model, dims, opts.sourceId ?? null],
@@ -206,6 +208,7 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
AND cc.${colId} IS NOT NULL
AND NOT ${currentChunk}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND p.deleted_at IS NULL
AND p.text_projection_revision = p.knowledge_revision
AND ${sigClause}${srcClause}
@@ -219,6 +222,7 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
AND p.deleted_at IS NULL
AND p.text_projection_revision = p.knowledge_revision
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
AND NOT EXISTS (
SELECT 1 FROM content_chunks cc
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 01d96262e0..b7da3454b4 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -386,6 +386,8 @@ function staleChunkWhere(column: string, opts?: StaleChunkOpts): SqlFragment {
conds.push(sqlFragment`${staleColRef} IS NULL`);
}
conds.push(sqlFragment`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
+ // Large pages held for approval or at their spend cap (page-embedding-budget.ts) leave the queue until it changes.
+ conds.push(sqlFragment`NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')`);
if (opts?.sourceId !== undefined) conds.push(sqlFragment`p.source_id = ${opts.sourceId}`);
return joinFragments(conds, ' AND ');
}
@@ -491,7 +493,7 @@ export async function invalidateContentDriftEmbeddings(
AND cc.${colId} IS NOT NULL
AND cc.embedded_text_hash IS NOT NULL
AND cc.embedded_text_hash <> md5(cc.chunk_text)
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')${srcClause}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')${srcClause}
RETURNING cc.page_id`);
return (await tx.executeRaw(text, params)).length;
});
@@ -528,7 +530,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
LIMIT ${limit}
`) : read(sqlFragment`
@@ -538,7 +540,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND (
p.updated_at < ${afterUpdated}::timestamptz
OR (p.updated_at = ${afterUpdated}::timestamptz AND p.id > ${afterPid})
@@ -556,7 +558,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
LIMIT ${limit}
`) : read(sqlFragment`
@@ -567,7 +569,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND (
p.updated_at < ${afterUpdated}::timestamptz
OR (p.updated_at = ${afterUpdated}::timestamptz AND p.id > ${afterPid})
@@ -585,7 +587,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
ORDER BY cc.page_id, cc.chunk_index
LIMIT ${limit}
@@ -598,7 +600,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
JOIN pages p ON p.id = cc.page_id
WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
ORDER BY cc.page_id, cc.chunk_index
LIMIT ${limit}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0915a8057b..e450b639b0 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -10,7 +10,8 @@ import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
import { classifyImportHold, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
-import { MAX_FILE_SIZE, screenImportContent, settleContentDisposition, stripGateOwnedMarkers, type ContentRefusal, type FenceScreen } from './import-screen.ts';
+import { CODE_FILE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';
+import { importSizeLimit, MAX_FILE_SIZE, screenImportContent, settleContentDisposition, stripGateOwnedMarkers, type ContentRefusal, type FenceScreen } from './import-screen.ts';
import type { WriteGateAssessment, WriteGateInput } from './write-gate.ts';
import { applyImportFences } from './fence-repair/import-step.ts';
import type { FenceIssueWire } from './fence-repair/tier1.ts';
@@ -631,7 +632,12 @@ export async function importFromContent(
// it reuses inside its publication transaction, under the page guard, from
// the chunks it is about to replace; only the chunks left without a vector
// reach the provider.
- const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !opts.onPostCommitEmbedding && chunks.length > 0
+ // A page above the inline threshold commits with NULL vectors and embeds
+ // after the write through the stale sweep, where the per-page spend cap and
+ // the sampled junk check apply: its provider calls never hold the write.
+ const largePage = isLargePageBytes(Buffer.byteLength(parsed.compiled_truth, 'utf-8') + Buffer.byteLength(parsed.timeline ?? '', 'utf-8'));
+ const postCommitEmbedding = largePage ? undefined : opts.onPostCommitEmbedding;
+ const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !postCommitEmbedding && chunks.length > 0
&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);
const reuseCtx = { slug, sourceId: sourceId ?? 'default', title: parsed.title, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' as const : 'none' as const };
const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[], keepUnembedded = false) => reuseStoredChunkVectors(exec, into, { ...reuseCtx, prepared: !!opts.prepare, keepUnembedded });
@@ -661,8 +667,8 @@ export async function importFromContent(
// commit with NULL vectors and no embedding signature, and the stale sweep
// (`gbrain embed --stale`, sync's embed pass, the cycle) embeds them once
// the provider recovers.
- let embeddingDeferred = false;
- if (!opts.onPostCommitEmbedding) {
+ let embeddingDeferred = largePage && !opts.noEmbed && chunks.length > 0;
+ if (!opts.onPostCommitEmbedding && !largePage) {
try {
await embedChunks();
if (embeddingPartial) {
@@ -783,7 +789,7 @@ export async function importFromContent(
// embedded (not --no-embed), so a later model/dims swap is detectable
// as stale via embed --stale. The deferred/backfill + per-slug embed
// paths stamp too; this covers the inline import/sync path.
- if (!opts.noEmbed && !opts.onPostCommitEmbedding && !embeddingDeferred) {
+ if (!opts.noEmbed && !postCommitEmbedding && !embeddingDeferred) {
// D9: signature is null when the gateway is unconfigured — skip the
// stamp (a wrong signature is worse than none).
const importSig = currentEmbeddingSignature();
@@ -837,7 +843,7 @@ export async function importFromContent(
if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
await disposition.persistReceipt(tx, { existed: !!existing });
- if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
+ if (postCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
// Capture the complete installed projection before releasing the page
// guard. Deferred provider results cannot replace newer text or chunks.
persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);
@@ -869,8 +875,8 @@ export async function importFromContent(
});
- if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
- opts.onPostCommitEmbedding(async () => {
+ if (postCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
+ postCommitEmbedding(async () => {
try {
if (!persistedProjection) return { status: 'superseded' };
const signature = currentEmbeddingSignature();
@@ -993,9 +999,10 @@ export async function importFromFile(
}
const stat = statSync(filePath);
- if (stat.size > MAX_FILE_SIZE) {
+ const maxBytes = importSizeLimit(relativePath);
+ if (stat.size > maxBytes) {
return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)`,
- refusal: { code: 'file_too_large', message: `File too large (${stat.size} bytes, max ${MAX_FILE_SIZE}).` }, skip_reason: 'file_too_large' };
+ refusal: { code: 'file_too_large', message: `File too large (${stat.size} bytes, max ${maxBytes}).` }, skip_reason: 'file_too_large' };
}
let content = readSourceFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // #4798: a BOM is encoding noise, not content
@@ -1194,7 +1201,7 @@ export async function importCodeFile(
const storageContent = sanitizeText(content.replaceAll('\0', '\\0'));
const byteLength = Buffer.byteLength(content, 'utf-8');
- if (byteLength > MAX_FILE_SIZE) {
+ if (byteLength > CODE_FILE_MAX_BYTES) {
return { slug, status: 'skipped', chunks: 0, error: `Code file too large (${byteLength} bytes)`, refusal: { code: 'file_too_large', message: `Code file too large (${byteLength} bytes)` }, skip_reason: 'file_too_large' };
}
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index e14be2e2f6..8e35d59732 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -35,8 +35,15 @@ import type { FenceMessageLocation } from './fence-repair/reasons.ts';
import { fenceIssuesWire, fenceStep, type FenceIssueWire } from './fence-repair/tier1.ts';
import type { FenceCtx, FenceFix, FencePage, FenceReason } from './fence-repair/types.ts';
import { effectiveVisibility } from './search/private-visibility.ts';
+import { CODE_FILE_MAX_BYTES, PAGE_MAX_BYTES } from './page-size-policy.ts';
-export const MAX_FILE_SIZE = 5_000_000; // 5MB
+/** Largest Markdown page import admits: the Wave A ceiling (page-size-policy.ts). */
+export const MAX_FILE_SIZE = PAGE_MAX_BYTES;
+
+/** The size bound for a file at `path`: code keeps its own 5 MB bound (no content sanity, tree-sitter and edge extraction). */
+export function importSizeLimit(path: string): number {
+ return isCodeFilePath(path) ? CODE_FILE_MAX_BYTES : MAX_FILE_SIZE;
+}
type ContentSanityConfig = NonNullable<NonNullable<ReturnType<typeof loadConfig>>['content_sanity']>;
@@ -396,7 +403,7 @@ export function screenNormalized(result: ImportScreenResult): boolean {
export function screenImportContent(input: ImportScreenInput): ImportScreenResult {
if (input.published?.()) return { status: 'published' };
const codeFile = isCodeFilePath(input.path);
- const size = contentSizeHold(input.byteLength ?? Buffer.byteLength(input.content, 'utf-8'), MAX_FILE_SIZE, codeFile);
+ const size = contentSizeHold(input.byteLength ?? Buffer.byteLength(input.content, 'utf-8'), codeFile ? CODE_FILE_MAX_BYTES : MAX_FILE_SIZE, codeFile);
if (size) return { status: 'refused', refusal: size };
if (codeFile) return { status: 'importable', parsed: null };
const parsed = parseMarkdown(input.content, input.path, { validate: true, ...(input.activePack ? { activePack: input.activePack } : {}) });
diff --git a/src/core/interaction.ts b/src/core/interaction.ts
index 02ea35aea9..ad82312cf4 100644
--- a/src/core/interaction.ts
+++ b/src/core/interaction.ts
@@ -11,6 +11,7 @@
import { fstatSync, readFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
+import { PAGE_MAX_BYTES } from './page-size-policy.ts';
export interface InteractiveProbe {
env?: NodeJS.ProcessEnv;
@@ -194,7 +195,7 @@ export interface StdinReadOptions {
const DEFAULT_FIRST_BYTE_MS = 30_000;
const FIRST_BYTE_NOTICE_MS = 5_000;
const DEFAULT_INACTIVITY_MS = 60_000;
-export const DEFAULT_STDIN_MAX_BYTES = 5_000_000;
+export const DEFAULT_STDIN_MAX_BYTES = PAGE_MAX_BYTES;
function firstByteDeadlineMs(explicit: number | undefined): number {
if (explicit !== undefined) return explicit;
@@ -203,7 +204,7 @@ function firstByteDeadlineMs(explicit: number | undefined): number {
}
const tooLarge = (maxBytes: number, bytes: number): StdinRead =>
- ({ kind: 'error', error: new Error(`stdin exceeds ${maxBytes} bytes; split the input into smaller pieces`), bytes });
+ ({ kind: 'error', error: new Error(`stdin exceeds ${maxBytes} bytes, the input limit`), bytes });
/**
* fd 0 as a regular file or a non-TTY character device (`< file`, `< /dev/null`)
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
new file mode 100644
index 0000000000..f454f6fee6
--- /dev/null
+++ b/src/core/page-embedding-budget.ts
@@ -0,0 +1,175 @@
+/**
+ * The per-page embedding spend cap for large pages (`embed.max_usd_per_page`,
+ * default $2), with its durable ledger `page_embedding_budget` (migration
+ * v244).
+ *
+ * Scope: pages above `pages.inline_max_bytes` (page-size-policy.ts). A page at
+ * or under it costs a few cents at most to embed whole and is not metered.
+ *
+ * Lifetime: spend accumulates per page for one embedding signature (model and
+ * dimensions); a model change starts a new ledger. The cap bounds that
+ * lifetime spend, so re-embed churn on a live page (boundary drift, rebuilds)
+ * can never spend more than the cap on it.
+ *
+ * Composition: every paid embedding entrypoint asks `planPageEmbedding` for a
+ * grant before it calls the provider. The grant takes the newest stale chunks
+ * whose estimated cost fits the page's remaining budget and reserves that
+ * estimate under a row lock, so concurrent sweeps never overspend. The run's
+ * own caps (the CLI consent cap `--max-usd`, `embed.backfill_max_usd`,
+ * `embed.backfill_max_usd_per_source_24h`) still meter the same provider calls
+ * through the gateway's budget tracker, so the lowest cap wins.
+ *
+ * States: `open`; `capped` once the cap stopped a run with stale chunks left
+ * (the page stays keyword-searchable and partially embedded); `held` while a
+ * page waits for the user's approval (the oversized-page upgrade backfill, or
+ * a sampled junk hit). Held and capped pages leave the stale-chunk queue
+ * (engine-sql/chunks.ts staleChunkWhere) so the sweep never retries them; an explicit
+ * approval (`gbrain embed --slugs <slug> --max-usd N`, `gbrain embed --held
+ * --max-usd N`) passes `approvedCapUsd`, lifts the hold and raises the cap.
+ *
+ * Crash safety: a reservation older than an hour (the provider call never
+ * settled) is counted as spent, never released, so a crash cannot reopen
+ * budget it may already have used.
+ */
+import type { BrainEngine } from './engine.ts';
+import { assessSampledJunk } from './content-sanity.ts';
+import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';
+import { isLargePageBytes } from './page-size-policy.ts';
+import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';
+
+export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';
+export const DEFAULT_PAGE_EMBED_CAP_USD = 2;
+/** Price assumed for a model with no known rate (the conservative OpenAI large rate). */
+const UNPRICED_RATE_PER_MTOK = 0.13;
+
+export type PageBudgetState = 'open' | 'held' | 'capped';
+
+/** The configured cap: `embed.max_usd_per_page`, else unlimited under `spend.posture tokenmax`, else $2. `off` is Infinity. */
+export async function resolvePageEmbedCapUsd(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<number> {
+ const raw = await engine.getConfig(PAGE_EMBED_CAP_KEY).catch(() => null);
+ if (raw === null || raw === undefined || raw === '') {
+ return await resolveSpendPosture(engine as BrainEngine).catch(() => 'gated') === 'tokenmax' ? Infinity : DEFAULT_PAGE_EMBED_CAP_USD;
+ }
+ return parseUsdLimit(raw, DEFAULT_PAGE_EMBED_CAP_USD);
+}
+
+export interface PageEmbedGrant {
+ /** chunk_index values this run may embed: the newest stale chunks that fit the remaining budget. */
+ chunkIndexes: ReadonlySet<number>;
+ reservedUsd: number;
+ /** Stale chunks left without a vector because the cap was reached. */
+ deferred: number;
+ capUsd: number;
+ /** Book the reservation as spent (`ok`) or release it (the provider call failed before billing). */
+ settle(outcome: { ok: boolean }): Promise<void>;
+}
+
+export type PageEmbedDecision =
+ | { kind: 'unmetered' }
+ | { kind: 'held'; reason: string }
+ | { kind: 'grant'; grant: PageEmbedGrant };
+
+interface BudgetRow { state: PageBudgetState; reason: string | null; embedding_signature: string | null; spent_usd: number; reserved_usd: number; stale_reservation: boolean; cap_usd: number | null }
+
+type BudgetPage = { id: number; compiled_truth: string; timeline?: string | null };
+
+function pageBytes(page: BudgetPage): number {
+ return Buffer.byteLength(page.compiled_truth, 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');
+}
+
+function currentPricePerMTok(signature: string | null | undefined): { rate: number; priced: boolean } {
+ if (!signature) return { rate: UNPRICED_RATE_PER_MTOK, priced: false };
+ const hit = lookupEmbeddingPrice(signature.slice(0, signature.lastIndexOf(':')) || signature);
+ return hit.kind === 'known' ? { rate: hit.pricePerMTok, priced: true } : { rate: UNPRICED_RATE_PER_MTOK, priced: false };
+}
+
+/** Hold a large page's embedding until the user approves it (`reason` names why). Idempotent; never touches open spend. */
+export async function holdPageEmbedding(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, reason: string): Promise<void> {
+ await engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'held', $2)
+ ON CONFLICT (page_id) DO UPDATE SET state = 'held', reason = EXCLUDED.reason, updated_at = now()`, [pageId, reason]);
+}
+
+/**
+ * Decide what one embedding run may spend on `page`. Small pages are
+ * unmetered. A held page returns `held` unless the caller carries the user's
+ * approval. Otherwise the newest stale chunks that fit the remaining budget are
+ * granted and their estimated cost is reserved.
+ */
+export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,
+ stale: ReadonlyArray<{ chunk_index: number; chunk_text: string }>,
+ opts: { signature?: string | null; approvedCapUsd?: number; maxMarkupRatio?: number } = {}): Promise<PageEmbedDecision> {
+ if (!isLargePageBytes(pageBytes(page)) || stale.length === 0) return { kind: 'unmetered' };
+ const approved = opts.approvedCapUsd !== undefined;
+ const configured = await resolvePageEmbedCapUsd(engine);
+ const { rate, priced } = currentPricePerMTok(opts.signature);
+ return engine.transaction(async tx => {
+ await tx.executeRaw('INSERT INTO page_embedding_budget (page_id) VALUES ($1) ON CONFLICT (page_id) DO NOTHING', [page.id]);
+ const [row] = await tx.executeRaw<BudgetRow>(`SELECT state, reason, embedding_signature, spent_usd, reserved_usd, cap_usd,
+ (reserved_usd > 0 AND reserved_at < now() - interval '1 hour') AS stale_reservation
+ FROM page_embedding_budget WHERE page_id = $1 FOR UPDATE`, [page.id]);
+ if (!row) return { kind: 'unmetered' } as const;
+ if (row.state === 'held' && !approved) return { kind: 'held', reason: row.reason ?? 'awaiting_approval' } as const;
+ if (!approved && row.state === 'open') {
+ const junk = assessSampledJunk(`${page.compiled_truth}\n${page.timeline ?? ''}`, { max_markup_ratio: opts.maxMarkupRatio });
+ if (junk.junk) {
+ const reason = junk.reasons.join(',');
+ await tx.executeRaw(`UPDATE page_embedding_budget SET state = 'held', reason = $2, updated_at = now() WHERE page_id = $1`, [page.id, reason]);
+ return { kind: 'held', reason } as const;
+ }
+ }
+ const sameLedger = !row.embedding_signature || !opts.signature || row.embedding_signature === opts.signature;
+ const spent = sameLedger ? Number(row.spent_usd) + (row.stale_reservation ? Number(row.reserved_usd) : 0) : 0;
+ let reserved = sameLedger && !row.stale_reservation ? Number(row.reserved_usd) : 0;
+ const stored = row.cap_usd === null ? configured : Number(row.cap_usd);
+ const capUsd = approved ? Math.max(stored, spent + reserved + opts.approvedCapUsd!) : stored;
+ const remaining = Math.max(0, capUsd - spent - reserved);
+ const chunkIndexes = new Set<number>();
+ let reservedUsd = 0;
+ for (const chunk of [...stale].sort((a, b) => b.chunk_index - a.chunk_index)) {
+ const cost = estimateCostFromChars(chunk.chunk_text.length, rate);
+ if (reservedUsd + cost > remaining) break;
+ reservedUsd += cost;
+ chunkIndexes.add(chunk.chunk_index);
+ }
+ const deferred = stale.length - chunkIndexes.size;
+ reserved += reservedUsd;
+ const state: PageBudgetState = deferred > 0 ? 'capped' : 'open';
+ await tx.executeRaw(`UPDATE page_embedding_budget SET state = $2, reason = $3, embedding_signature = COALESCE($4, embedding_signature),
+ spent_usd = $5, reserved_usd = $6, reserved_at = CASE WHEN $6 > 0 THEN now() ELSE NULL END,
+ cap_usd = $7, updated_at = now() WHERE page_id = $1`,
+ [page.id, state, deferred > 0 ? 'cap_reached' : null, opts.signature ?? null, spent, reserved,
+ approved && Number.isFinite(capUsd) ? capUsd : row.cap_usd]);
+ const grant: PageEmbedGrant = {
+ chunkIndexes, reservedUsd, deferred, capUsd,
+ settle: async ({ ok }) => {
+ if (reservedUsd === 0) return;
+ await engine.executeRaw(`UPDATE page_embedding_budget SET reserved_usd = GREATEST(0, reserved_usd - $2),
+ spent_usd = spent_usd + $3, unpriced_calls = unpriced_calls + $4, updated_at = now() WHERE page_id = $1`,
+ [page.id, reservedUsd, ok ? reservedUsd : 0, ok && !priced ? 1 : 0]);
+ },
+ };
+ return { kind: 'grant', grant } as const;
+ });
+}
+
+export interface PageBudgetReport { slug: string; source_id: string; state: Exclude<PageBudgetState, 'open'>; reason: string | null;
+ spent_usd: number; cap_usd: number | null; pending_chunks: number; pending_chars: number }
+
+/** Estimated provider cost of embedding `chars` of chunk text with the model in `signature` (unknown models use the conservative rate). */
+export function estimatePageEmbedUsd(chars: number, signature: string | null | undefined): number {
+ return estimateCostFromChars(chars, currentPricePerMTok(signature).rate);
+}
+
+/** Held and capped pages with their stale chunk counts (doctor `partial_embedding`, `gbrain embed --held`). */
+export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: { state?: 'held' | 'capped'; sourceId?: string; limit?: number } = {}): Promise<PageBudgetReport[]> {
+ const params: unknown[] = [opts.limit ?? 1000];
+ const filters = [`b.state <> 'open'`, 'p.deleted_at IS NULL'];
+ if (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);
+ if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);
+ const rows = await engine.executeRaw<PageBudgetReport>(`SELECT p.slug, p.source_id, b.state, b.reason, b.spent_usd, b.cap_usd,
+ (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL) AS pending_chunks,
+ (SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL) AS pending_chars
+ FROM page_embedding_budget b JOIN pages p ON p.id = b.page_id
+ WHERE ${filters.join(' AND ')} ORDER BY b.updated_at DESC, p.id LIMIT $1`, params);
+ return rows.map(row => ({ ...row, spent_usd: Number(row.spent_usd), cap_usd: row.cap_usd === null ? null : Number(row.cap_usd), pending_chunks: Number(row.pending_chunks), pending_chars: Number(row.pending_chars) }));
+}
diff --git a/src/core/page-size-policy.ts b/src/core/page-size-policy.ts
new file mode 100644
index 0000000000..d4b68e3b3d
--- /dev/null
+++ b/src/core/page-size-policy.ts
@@ -0,0 +1,39 @@
+/**
+ * Large-page policy (Wave A): the one ceiling every raisable ingress bound
+ * derives from, and the inline threshold above which a page is treated as
+ * large (post-commit embedding, title-tier context, bounded history).
+ *
+ * The ceiling is 24 MiB, not 32 MB: the journal and the local persistence IPC
+ * count escaped JSON against 32 MiB caps, and the pre-push secret scan skips
+ * (and so refuses to push) any file over 25 MiB. A page at the ceiling plus
+ * its frontmatter stays under every one of them. Code files keep their own
+ * 5 MB bound (they skip content sanity and run tree-sitter plus the edge
+ * extractor). The per-entry-point table lives in
+ * docs/guides/memory-boundaries.md ("Large pages").
+ */
+
+/** Largest Markdown page body (UTF-8 bytes) any ingress admits in Wave A. */
+export const PAGE_MAX_BYTES = 24 * 1024 ** 2;
+
+/**
+ * The pre-push secret scan skips (and so the push gate refuses) any file over
+ * this many bytes; no canonical file write may produce one (secret-scan.ts).
+ */
+export const PUSH_SCAN_MAX_FILE_BYTES = 25 * 1024 * 1024;
+
+/** Largest code file (UTF-8 bytes) import and sync admit. */
+export const CODE_FILE_MAX_BYTES = 5_000_000;
+
+/**
+ * `pages.inline_max_bytes`: pages above this many body bytes are large. They
+ * commit with NULL vectors and embed after the write through the stale sweep
+ * under the per-page spend cap, use the title context tier, get a sampled junk
+ * check before embedding, and keep a bounded number of version snapshots.
+ * Fixed in Wave A; Wave B makes it the segmented-storage threshold.
+ */
+export const PAGE_INLINE_MAX_BYTES = 1024 ** 2;
+
+/** True when a page body of this many UTF-8 bytes is above the inline threshold. */
+export function isLargePageBytes(bytes: number): boolean {
+ return bytes > PAGE_INLINE_MAX_BYTES;
+}
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 739c4a77b3..b2040a84b8 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -44,6 +44,7 @@ import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';
import { declarePersistenceProtocol } from './protocol.ts';
+import { PERSISTENCE_IPC_MAX_BYTES } from './ipc.ts';
import type { GoogleSourceConfig } from '../google/types.ts';
interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }
@@ -363,7 +364,7 @@ export class ManagedConnectorSync {
}
const limits = await readJournalLimits(this.engine);
this.outstandingCap = Math.max(1, Math.min(90, limits.principalOutstanding - 10));
- this.intentByteCap = Math.max(1024 ** 2, Math.floor(limits.principalIntentBytes / 2));
+ this.intentByteCap = Math.max(1024 ** 2, Math.floor(Math.min(limits.principalIntentBytes, PERSISTENCE_IPC_MAX_BYTES) / 2));
this.connectorState = await readManagedConnectorState(this.engine, this.sourceId, this.source.incarnation);
await this.resolvePendingSet();
const [row] = await this.engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [this.checkpointKey]);
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index c2834fa565..5e093f1683 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -103,6 +103,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),
carry('open_loops', 'user_data', 'Open loops and their status.'),
carry('page_aliases', 'user_data', 'Page aliases.'),
+ carry('page_embedding_budget', 'operational', 'Large-page embedding spend ledger: per-page spend, holds awaiting approval and caps; without it held pages would embed without consent.'),
carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),
carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),
carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 0efb1d98e1..c132120714 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -4,13 +4,13 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
import { ownerGateInput, ownerImportTrust } from '../trust/channel.ts';
-import { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_FILE_SIZE, MAX_IMAGE_BYTES, verifyPageReadable } from '../import-file.ts';
+import { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_IMAGE_BYTES, verifyPageReadable } from '../import-file.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { getCompanyBrainProfile } from '../company-brain/profile.ts';
import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath } from '../sync.ts';
import { OperationError, opError } from '../ops/contract.ts';
-import { contentRefusalError, screenImportContent, type ContentRefusal } from '../import-screen.ts';
+import { contentRefusalError, importSizeLimit, screenImportContent, type ContentRefusal } from '../import-screen.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
import { isWriteTargetContained } from '../path-confine.ts';
@@ -51,7 +51,7 @@ export function readImportBytes(path: string): Buffer {
throw opError('source_changed', 'Managed import refuses symlinked files or ancestors. Use the real source path.',
`${path} is a symlink or sits under one, so it was not imported. Import the file at its real location (or copy it into the source) instead.`);
}
- const maxBytes = isImageFilePath(path) ? MAX_IMAGE_BYTES : MAX_FILE_SIZE;
+ const maxBytes = isImageFilePath(path) ? MAX_IMAGE_BYTES : importSizeLimit(path);
if (lstatSync(path).size > maxBytes) throw opError('invalid_params', `File too large (max ${maxBytes} bytes).`,
`${basename(path)} is over the ${maxBytes}-byte import limit and was not imported. Split it into smaller files or leave it out of the import.`);
return readFileSync(path);
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 2b50f73877..0c288909de 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -114,10 +114,13 @@ export interface JournalLimits {
* (the reported autopilot workload) runs at least one year: lifetime IDs last
* about 417 days; receipt bytes hold a 30-day window of 16 KiB reservations
* plus about 4 KiB retained per compacted receipt for about 590 days.
+ * Outstanding intent per principal holds two page-ceiling writes
+ * (page-size-policy.ts, 24 MiB each, JSON-escaped) plus headroom, so one
+ * large write never refuses another from the same principal.
*/
export const DEFAULT_JOURNAL_LIMITS: Readonly<JournalLimits> = Object.freeze({
principalOutstanding: 100, brainOutstanding: 1000,
- principalIntentBytes: 32 * 1024 ** 2, brainIntentBytes: 256 * 1024 ** 2,
+ principalIntentBytes: 64 * 1024 ** 2, brainIntentBytes: 256 * 1024 ** 2,
principalLifetimeIds: 250_000, brainLifetimeIds: 1_000_000,
principalTerminalBytes: 1536 * 1024 ** 2, brainTerminalBytes: 8 * 1024 ** 3,
brainRecoveryBytes: 1024 ** 3, worktreeRecoveryBytes: 256 * 1024 ** 2,
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7b0a07762d..938b606c42 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -63,6 +63,7 @@ import { withTrustKeep } from './context.ts';
import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
import { suppliedTrustMarkerView } from '../trust/channel.ts';
import { gateField, gateInput } from '../trust/gate-outcomes.ts';
+import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -161,6 +162,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */
sharedOrigin?: { onShared: (shared: SharedOrigin) => void } } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
+ // A canonical file over the pre-push secret-scan cap would block every later push of the brain repo.
+ if (content !== null && Buffer.byteLength(content, 'utf-8') > PUSH_SCAN_MAX_FILE_BYTES) throw opError('request_too_large', 'The canonical file would exceed the pre-push secret-scan cap.',
+ `Nothing was written. The rendered file of ${row.slug} is over ${PUSH_SCAN_MAX_FILE_BYTES} bytes, which the pre-push secret scan cannot scan, so it would block every push of source ${row.source_id}. Keep the page under the 24 MiB page ceiling (docs/guides/memory-boundaries.md#large-pages).`);
// #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded
// source_uri or source_path may name the file of another page, such as the one sync now slugs it to.
if (!isOpPageSlug(row.slug)) return undefined;
diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.ts
index ebf423c9b8..000a47dd58 100644
--- a/src/core/persistence/sync-blobs.ts
+++ b/src/core/persistence/sync-blobs.ts
@@ -9,9 +9,10 @@
*/
import { execFileSync } from 'node:child_process';
import { gitChildEnv } from '../git-env.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
-/** The sync read bound (`readSyncFile`): bigger files are held without being read. */
-export const SYNC_READ_BOUND = 10 * 1024 ** 2;
+/** The sync read bound (`readSyncFile`): bigger files are held without being read. The page ceiling (page-size-policy.ts), which also covers MAX_IMAGE_BYTES. */
+export const SYNC_READ_BOUND = PAGE_MAX_BYTES;
export interface TreeBlob { oid: string; size: number }
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index f2441bb7d7..a6f09f3096 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -23,7 +23,7 @@ import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, selectOrig
import { assertManagedSyncActive } from './sync-authority.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
-import { readBlobContents, readTreeBlobs } from './sync-blobs.ts';
+import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
import { gitChildEnv } from '../git-env.ts';
import { readSyncSlice, sliceEntries, syncCursorOptions, type SyncSliceCursor, type SyncSliceState } from './sync-slices.ts';
@@ -101,8 +101,8 @@ export function readSyncFile(root: string, path: string): Buffer | null {
}
if (!lstatSync(absolute).isFile()) throw syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
`${path} is not a regular file.`);
- if (lstatSync(absolute).size > 10 * 1024 ** 2) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
- `${path} is larger than the 10 MiB sync import bound, so nothing was imported from it. Shrink or split the file, or add it to the sync.exclude config, then sync its source again.`);
+ if (lstatSync(absolute).size > SYNC_READ_BOUND) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
+ `${path} is larger than the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling, so nothing was imported from it. Pages up to that size are chunked and searchable; above it, add the file to the sync.exclude config (or keep it outside the brain repo), then sync its source again. See docs/guides/memory-boundaries.md#large-pages.`);
return readFileSync(absolute);
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
}
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 0961b17cbd..3669ea8753 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -177,7 +177,7 @@ export function managedImageHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' |
/** #5988: the hold of a file over the sync read bound, whose content is never read (#6529: shared with the image freeze). */
export function oversizeHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null, size: number | null, blob: TreeBlob | null | undefined): HeldEntry {
return heldEntry(entry, slug, pageId, { code: 'file_too_large',
- message: `File too large (${size ?? 'over 10485760'} bytes; the sync read bound is ${SYNC_READ_BOUND} bytes). Split the content into smaller files or leave it out of the source.` }, null, blob);
+ message: `File too large (${size ?? `over ${SYNC_READ_BOUND}`} bytes; the sync read bound is the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling). Pages up to the ceiling are chunked and searchable; leave this file out of the source (sync.exclude) or keep it outside the brain repo. See docs/guides/memory-boundaries.md#large-pages.` }, null, blob);
}
const purgeTombstonesByRun = new WeakMap<SyncScreenRun, Promise<Map<string, string>>>();
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 4a0fe95b8d..1211475a77 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1193,6 +1193,19 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx
ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);
+CREATE TABLE IF NOT EXISTS page_embedding_budget (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'held', 'capped')),
+ reason TEXT,
+ embedding_signature TEXT,
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ unpriced_calls INTEGER NOT NULL DEFAULT 0 CHECK (unpriced_calls >= 0),
+ cap_usd DOUBLE PRECISION CHECK (cap_usd IS NULL OR cap_usd >= 0),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS page_embedding_budget_state_idx ON page_embedding_budget (state) WHERE state <> 'open';
CREATE TABLE IF NOT EXISTS chronicle_page_state (
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 03157f03b1..0459b86906 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1908,6 +1908,22 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx
ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);
+-- (migration v244) Per-page embedding spend ledger for large pages
+-- (page-embedding-budget.ts): held pages wait for approval, capped pages are
+-- partially embedded up to embed.max_usd_per_page.
+CREATE TABLE IF NOT EXISTS page_embedding_budget (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'held', 'capped')),
+ reason TEXT,
+ embedding_signature TEXT,
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ unpriced_calls INTEGER NOT NULL DEFAULT 0 CHECK (unpriced_calls >= 0),
+ cap_usd DOUBLE PRECISION CHECK (cap_usd IS NULL OR cap_usd >= 0),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS page_embedding_budget_state_idx ON page_embedding_budget (state) WHERE state <> 'open';
-- #5876 (migration chronicle_page_state): Life Chronicle ledger, the durable
-- record of each page content's automatic-extraction decision and outcome.
CREATE TABLE IF NOT EXISTS chronicle_page_state (
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index a73fbd1589..fe278501ec 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 243;
+export const LATEST_SCHEMA_VERSION = 244;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 129cf41721..377fb79fee 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -244,6 +244,7 @@ import { v240 } from './v240-pages-name-lookup-indexes.ts';
import { v241 } from './v241-persistence-request-slug-intent-index.ts';
import { v242 } from './v242-extract-atoms-partial-input.ts';
import { v243 } from './v243-persistence-consumer-process-start.ts';
+import { v244 } from './v244-page-embedding-budget.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -486,4 +487,5 @@ export const MIGRATIONS: Migration[] = [
v241,
v242,
v243,
+ v244,
];
diff --git a/src/core/schema-migrations/v244-page-embedding-budget.ts b/src/core/schema-migrations/v244-page-embedding-budget.ts
new file mode 100644
index 0000000000..1212485a44
--- /dev/null
+++ b/src/core/schema-migrations/v244-page-embedding-budget.ts
@@ -0,0 +1,30 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install
+// copy in src/schema.sql carries the same table.
+export const v244: Migration = {
+ version: 244,
+ name: 'page_embedding_budget',
+ // Large pages (above pages.inline_max_bytes): the durable per-page embedding
+ // spend ledger behind embed.max_usd_per_page (page-embedding-budget.ts).
+ // `held` pages wait for the user's approval (the oversized-page upgrade
+ // backfill, a sampled junk hit); `capped` pages reached their cap and stay
+ // partially embedded until it rises. Spend counts per embedding signature.
+ // DDL only: a new table, nothing to backfill.
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS page_embedding_budget (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'held', 'capped')),
+ reason TEXT,
+ embedding_signature TEXT,
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ unpriced_calls INTEGER NOT NULL DEFAULT 0 CHECK (unpriced_calls >= 0),
+ cap_usd DOUBLE PRECISION CHECK (cap_usd IS NULL OR cap_usd >= 0),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ CREATE INDEX IF NOT EXISTS page_embedding_budget_state_idx ON page_embedding_budget (state) WHERE state <> 'open';
+ `,
+};
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index 6e6f6eb215..be286edd91 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -95,6 +95,7 @@ export {
SCAN_ALLOW_FILENAME, ALLOWLIST_FINGERPRINT_MIN_HEX, loadWorkspaceAllowlist, globToRegExp, matchesGlob, valueAllowlisted, pathAllowlisted,
} from './secret-scan-allowlist.ts';
import { valueAllowlisted, pathAllowlisted } from './secret-scan-allowlist.ts';
+import { PUSH_SCAN_MAX_FILE_BYTES } from './page-size-policy.ts';
import type { ScanWork } from './secret-scan-work.ts';
export { createScanWork, type ScanWork } from './secret-scan-work.ts';
@@ -1106,7 +1107,7 @@ export function scanText(text: string, opts: ScanOpts = {}): SecretFinding[] {
export const BINARY_SNIFF_BYTES = 8192;
/** scanFiles skips anything larger (the push gate applies the same cap). */
-export const SCAN_MAX_FILE_BYTES = 25 * 1024 * 1024;
+export const SCAN_MAX_FILE_BYTES = PUSH_SCAN_MAX_FILE_BYTES;
/** True when the first BINARY_SNIFF_BYTES of the buffer contain a NUL byte. */
export function looksBinaryBuffer(buf: Uint8Array): boolean {
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index ca60246a99..87ef80fe3c 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -30,6 +30,7 @@ import { isRelativeFileUri, serializePageToMarkdown, resolvePageFilePath, resolv
import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';
import { readSlugRootMode, resolveSlugRootMode, type SlugRootMode } from './sync-anchor.ts';
import { resolveSlugForPath } from './sync.ts';
+import { PUSH_SCAN_MAX_FILE_BYTES } from './page-size-policy.ts';
import {
isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,
type PushLogOutcome,
@@ -91,8 +92,10 @@ export interface WriteThroughResult {
* - file_changed: the caller passed `expectedFileBytes` and the file on
* disk no longer holds them (an edit landed after the caller read it) —
* the edit is kept and nothing is written.
+ * - over_push_scan_cap: the rendered file is over the pre-push secret-scan
+ * cap (PUSH_SCAN_MAX_FILE_BYTES), so committing it would block every push.
*/
- skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed';
+ skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap';
/** Caller-visible advisory when a permitted DB-only outcome is still risky. */
warning?: string;
/** Set when the render/write/rename itself threw (EACCES, ENOTDIR, disk full). */
@@ -431,6 +434,12 @@ export async function writePageThrough(
const md = serializePageToMarkdown(writtenPage, tags, {
frontmatterOverrides: opts.frontmatterOverrides,
});
+ // The pre-push secret scan refuses to push any file it cannot scan, so a
+ // file over its cap would block every later push of the brain repo.
+ if (Buffer.byteLength(md, 'utf-8') > PUSH_SCAN_MAX_FILE_BYTES) {
+ opts.logger?.warn(`[write-through] ${slug}: the rendered file is over the ${PUSH_SCAN_MAX_FILE_BYTES}-byte pre-push secret-scan cap — file not written (DB row is intact)`);
+ return { written: false, skipped: 'over_push_scan_cap' };
+ }
// #2831: two distinct DB slugs differing only by case (FOO vs foo) resolve
// to the SAME file on a case-insensitive filesystem — the second write
diff --git a/src/schema.sql b/src/schema.sql
index 6afd1c311e..77e8b2e3f3 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1904,6 +1904,22 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx
ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;
CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);
+-- (migration v244) Per-page embedding spend ledger for large pages
+-- (page-embedding-budget.ts): held pages wait for approval, capped pages are
+-- partially embedded up to embed.max_usd_per_page.
+CREATE TABLE IF NOT EXISTS page_embedding_budget (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'held', 'capped')),
+ reason TEXT,
+ embedding_signature TEXT,
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ unpriced_calls INTEGER NOT NULL DEFAULT 0 CHECK (unpriced_calls >= 0),
+ cap_usd DOUBLE PRECISION CHECK (cap_usd IS NULL OR cap_usd >= 0),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS page_embedding_budget_state_idx ON page_embedding_budget (state) WHERE state <> 'open';
-- #5876 (migration chronicle_page_state): Life Chronicle ledger, the durable
-- record of each page content's automatic-extraction decision and outcome.
CREATE TABLE IF NOT EXISTS chronicle_page_state (
diff --git a/test/chunkers/recursive.test.ts b/test/chunkers/recursive.test.ts
index cb5e91daae..2ee2f9df74 100644
--- a/test/chunkers/recursive.test.ts
+++ b/test/chunkers/recursive.test.ts
@@ -214,3 +214,16 @@ describe('CJK chunking (v0.32.7)', () => {
expect(chunks.every(c => /^[\x20-\x7e\s]+$/.test(c.text))).toBe(true);
});
});
+
+describe('large pages: delimiter splitting is linear', () => {
+ test('a 4 MiB single-paragraph page chunks in well under a second per MiB', () => {
+ const sentence = 'Plain prose about acme-example. ';
+ const text = sentence.repeat(Math.floor((4 * 1024 * 1024) / sentence.length));
+ const started = performance.now();
+ const chunks = chunkText(text);
+ const elapsed = performance.now() - started;
+ expect(chunks.length).toBeGreaterThan(1000);
+ expect(chunks.every(c => c.text.length <= 6000)).toBe(true);
+ expect(elapsed).toBeLessThan(3000);
+ });
+});
diff --git a/test/content-sanity.test.ts b/test/content-sanity.test.ts
index 28d6df9bae..4245617644 100644
--- a/test/content-sanity.test.ts
+++ b/test/content-sanity.test.ts
@@ -69,6 +69,7 @@ describe('assessContentSanity — size boundaries', () => {
compiled_truth: 'a'.repeat(600_000),
timeline: '',
title: '',
+ bytes_block: 500_000,
});
expect(r.oversize).toBe(true);
expect(r.reasons).toContain('oversize_block');
@@ -77,17 +78,31 @@ describe('assessContentSanity — size boundaries', () => {
expect(r.shouldHardBlock).toBe(false);
});
- test('the original 890K reproduction trips block alone (no junk)', () => {
+ test('the original 890K reproduction trips block alone (no junk) under a 500 KB bytes_block', () => {
// 890K of clean text (no Cloudflare phrases) → soft-block only.
const r = assessContentSanity({
compiled_truth: 'normal prose. '.repeat(70_000), // ~890K bytes
timeline: '',
title: 'A Long Article',
+ bytes_block: 500_000,
});
expect(r.shouldSkipEmbed).toBe(true);
expect(r.shouldHardBlock).toBe(false);
});
+ test('large pages: the default bytes_block is the 24 MiB page ceiling, so 890K of clean prose is chunked and embedded', () => {
+ const r = assessContentSanity({
+ compiled_truth: 'normal prose. '.repeat(70_000),
+ timeline: '',
+ title: 'A Long Article',
+ });
+ expect(r.oversize).toBe(false);
+ expect(r.reasons).toContain('oversize_warn');
+ expect(r.shouldSkipEmbed).toBe(false);
+ expect(r.shouldHardBlock).toBe(false);
+ expect(r.shouldQuarantine).toBe(false);
+ });
+
test('custom thresholds override defaults', () => {
const r = assessContentSanity({
compiled_truth: 'a'.repeat(150),
@@ -101,7 +116,7 @@ describe('assessContentSanity — size boundaries', () => {
test('defaults are exported and reasonable', () => {
expect(DEFAULT_BYTES_WARN).toBe(50_000);
- expect(DEFAULT_BYTES_BLOCK).toBe(500_000);
+ expect(DEFAULT_BYTES_BLOCK).toBe(24 * 1024 * 1024);
});
});
@@ -358,6 +373,7 @@ describe('assessContentSanity — reason ordering', () => {
compiled_truth: 'a'.repeat(600_000),
timeline: '',
title: '',
+ bytes_block: 500_000,
});
const joined = r.reason_messages.join(' ');
expect(joined).toContain('PAGE_OVERSIZED:');
@@ -372,6 +388,7 @@ describe('assessContentSanity — reason ordering', () => {
compiled_truth: 'Cloudflare Ray ID: abc\n' + 'a'.repeat(600_000),
timeline: '',
title: '',
+ bytes_block: 500_000,
});
expect(r.reasons).toContain('oversize_block');
expect(r.reasons).toContain('junk_pattern');
@@ -619,7 +636,7 @@ describe('assessContentSanity — confidence split (Q1=A)', () => {
});
test('oversize → shouldSkipEmbed + shouldFlag(oversized), pure-prose 890K stays NOT-quarantined', () => {
- const r = assessContentSanity({ compiled_truth: 'normal prose. '.repeat(70_000), timeline: '', title: 'book' });
+ const r = assessContentSanity({ compiled_truth: 'normal prose. '.repeat(70_000), timeline: '', title: 'book', bytes_block: 500_000 });
expect(r.oversize).toBe(true);
expect(r.shouldSkipEmbed).toBe(true);
expect(r.shouldFlag).toBe(true);
@@ -634,6 +651,7 @@ describe('assessContentSanity — confidence split (Q1=A)', () => {
compiled_truth: 'Cloudflare Ray ID: x\n' + 'a'.repeat(600_000),
timeline: '',
title: 't',
+ bytes_block: 500_000,
});
expect(r.shouldQuarantine).toBe(true);
expect(r.shouldSkipEmbed).toBe(false);
diff --git a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts b/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
index d5d0f22f83..ab504a8e80 100644
--- a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
+++ b/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
@@ -139,15 +139,15 @@ describe('R4 — cross-platform stdin via fd 0 (PR #1325 regression pin)', () =>
// import time and brittle to stub safely without mock.module). The
// source-grep above is the primary regression guard; this test asserts
// the surrounding shape of the parseOpArgs stdin-reading branch hasn't
- // drifted (existence of the branch + 5MB cap), since the branch itself
+ // drifted (existence of the branch + page-ceiling cap), since the branch itself
// is what was modified by PR #1325.
const path = join(import.meta.dir ?? '.', '..', '..', 'src', 'cli', 'main.ts');
const src = readFileSync(path, 'utf-8');
// Stdin reading branch still exists in parseOpArgs.
expect(src).toMatch(/op\.cliHints\?\.stdin/);
- // 5MB cap is still in place.
- expect(src).toMatch(/MAX_STDIN\s*=\s*5_000_000/);
+ // The page-ceiling cap is still in place.
+ expect(src).toMatch(/MAX_STDIN\s*=\s*PAGE_MAX_BYTES/);
// isTTY check still gates stdin reading.
expect(src).toMatch(/!process\.stdin\.isTTY/);
});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index f94b5a044f..d1e6fa366b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -205,6 +205,13 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +683,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1146,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2534,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 545b92cf9a..bdcd659bf6 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -205,6 +205,13 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +683,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1146,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2534,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 5a06338969..6c121caffa 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -205,6 +205,13 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +683,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1142,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2518,6 +2530,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index f492a7603e..a74589f76a 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -140,6 +140,13 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +488,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -810,6 +820,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
@@ -1838,6 +1850,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 384e9c888f..cfcfda8252 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -140,6 +140,13 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +488,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -810,6 +820,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
@@ -1838,6 +1850,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 9e912dbff9..a666eea8dc 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -140,6 +140,13 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +488,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -809,6 +819,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
@@ -1837,6 +1849,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index ef3d235035..47b762de82 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 238,
+ "count": 239,
"gaps": [
17,
18,
@@ -54,7 +54,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 243,
+ "latest": 244,
"records": [
{
"handler": {
@@ -3697,6 +3697,19 @@
"transaction": "absent",
"verify": "absent",
"version": 243
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "page_embedding_budget",
+ "sql": {
+ "length": 785,
+ "sha256": "ec11068c49b813afcfb5c4497f5423f8bf71eb5f24c0ae196326bb2175f66680"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 244
}
],
"versions": [
@@ -3937,7 +3950,8 @@
240,
241,
242,
- 243
+ 243,
+ 244
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 57e79115c3..ed49eb9d7a 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -205,6 +205,13 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
+ "page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
+ "page_embedding_budget.page_embedding_budget_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
+ "page_embedding_budget.page_embedding_budget_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'held'::text, 'capped'::text])))",
+ "page_embedding_budget.page_embedding_budget_unpriced_calls_check": "c CHECK ((unpriced_calls >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +683,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_embedding_budget": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1146,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
+ "page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2534,21 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_embedding_budget": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 state text/text NOT NULL DEFAULT 'open'::text",
+ "3 reason text/text NULL",
+ "4 embedding_signature text/text NULL",
+ "5 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "6 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "7 reserved_at timestamp with time zone/timestamptz NULL",
+ "8 unpriced_calls integer/int4 NOT NULL DEFAULT 0",
+ "9 cap_usd double precision/float8 NULL",
+ "10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 0f2618f67c..c7ac494f1b 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 122, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 123, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/import-file-content-sanity.test.ts b/test/import-file-content-sanity.test.ts
index e8ab76cb3b..70e4dfdec1 100644
--- a/test/import-file-content-sanity.test.ts
+++ b/test/import-file-content-sanity.test.ts
@@ -1,4 +1,4 @@
-import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -229,6 +229,11 @@ describe('importFromContent — markup-heavy FLAG (Q1=A: warn, stay searchable)'
});
describe('importFromContent — soft-block (D9 transition + embed_skip)', () => {
+ // The default bytes_block is the 24 MiB page ceiling; an operator who lowers
+ // it gets the soft-block below.
+ beforeEach(async () => { await engine.setConfig('content_sanity.bytes_block', '500000'); });
+ afterEach(async () => { await engine.unsetConfig('content_sanity.bytes_block'); });
+
test('soft-block writes page with embed_skip frontmatter marker', async () => {
await withIsolatedHome(async () => {
// 600K of clean text → soft-block (oversize but no junk pattern).
@@ -297,6 +302,20 @@ describe('importFromContent — soft-block (D9 transition + embed_skip)', () =>
});
});
+describe('importFromContent — large pages under the default ceiling', () => {
+ test('a 600K page is chunked with no embed_skip marker or oversized flag', async () => {
+ await withIsolatedHome(async () => {
+ const content = FRONTMATTER + 'Plain prose about acme-example. '.repeat(19_000);
+ const result = await importFromContent(engine, 'test/large-default', content, { noEmbed: true });
+ expect(result.status).toBe('imported');
+ expect(result.flag_reason).not.toBe('oversized');
+ const page = await engine.getPage('test/large-default');
+ expect(isEmbedSkipped(page!.frontmatter as Record<string, unknown>)).toBe(false);
+ expect((await engine.getChunks('test/large-default')).length).toBeGreaterThan(100);
+ });
+ });
+});
+
describe('importFromContent — stale size-gate recovery', () => {
test('trusted export with an obsolete oversized marker regains chunks', async () => {
await withIsolatedHome(async () => {
diff --git a/test/import-file.test.ts b/test/import-file.test.ts
index 1756da1fae..9d8f9b4a06 100644
--- a/test/import-file.test.ts
+++ b/test/import-file.test.ts
@@ -4,6 +4,7 @@ import { join } from 'path';
import { importFile, importFromContent } from '../src/core/import-file.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';
+import { CODE_FILE_MAX_BYTES, PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
const TMP = join(import.meta.dir, '.tmp-import-test');
@@ -163,9 +164,9 @@ This is the compiled truth.
expect(putCall.args[1].compiled_truth).not.toContain('\uFEFF');
});
- test('skips files larger than MAX_FILE_SIZE (5MB)', async () => {
+ test('skips files larger than MAX_FILE_SIZE (the 24 MiB page ceiling)', async () => {
const filePath = join(TMP, 'big-file.md');
- const bigContent = '---\ntitle: Big\n---\n' + 'x'.repeat(5_100_000);
+ const bigContent = '---\ntitle: Big\n---\n' + 'x'.repeat(PAGE_MAX_BYTES + 100_000);
writeFileSync(filePath, bigContent);
const engine = mockEngine();
@@ -438,7 +439,7 @@ Content to chunk but not embed.
// must trigger BEFORE parseMarkdown / chunkText / embedBatch — if it doesn't,
// an authenticated attacker can force the owner to pay for embedding a
// multi-megabyte string.
- const bigContent = '---\ntitle: Big\n---\n' + 'x'.repeat(5_100_000);
+ const bigContent = '---\ntitle: Big\n---\n' + 'x'.repeat(PAGE_MAX_BYTES + 100_000);
const engine = mockEngine();
const result = await importFromContent(engine, 'big-slug', bigContent, { noEmbed: true });
@@ -451,10 +452,11 @@ Content to chunk but not embed.
});
test('uses UTF-8 byte length, not JS string length, for the size check', async () => {
- // 2.6M 4-byte codepoints = ~10.4 MB UTF-8 but only 2.6M JS UTF-16 code units.
+ // 6.5M 4-byte codepoints = 26 MB UTF-8 but only 13M JS UTF-16 code units.
// A length-based check would let this through; a byteLength check catches it.
const fourByteChar = '\u{1F600}'; // emoji, 4 bytes in UTF-8
- const bigContent = fourByteChar.repeat(2_600_000);
+ const bigContent = fourByteChar.repeat(6_500_000);
+ expect(bigContent.length).toBeLessThan(PAGE_MAX_BYTES);
const engine = mockEngine();
const result = await importFromContent(engine, 'emoji-slug', bigContent, { noEmbed: true });
@@ -467,12 +469,28 @@ Content to chunk but not embed.
test('accepts in-memory content just under MAX_FILE_SIZE', async () => {
// Sanity: content exactly at the limit must still import. If this test
// fails, the guard is off-by-one and will break legitimate large imports.
- const content = '---\ntitle: Borderline\n---\n' + 'x'.repeat(4_900_000);
+ const head = '---\ntitle: Borderline\n---\n';
+ const sentence = 'Normal prose about acme-example. ';
+ const body = sentence.repeat(Math.floor((PAGE_MAX_BYTES - head.length) / sentence.length));
+ const content = head + body + 'x'.repeat(PAGE_MAX_BYTES - head.length - body.length);
+ expect(Buffer.byteLength(content, 'utf-8')).toBe(PAGE_MAX_BYTES);
const engine = mockEngine();
const result = await importFromContent(engine, 'borderline-slug', content, { noEmbed: true });
expect(result.status).toBe('imported');
+ }, 60_000);
+
+ test('a code file keeps the 5 MB code limit while Markdown takes the page ceiling', async () => {
+ const filePath = join(TMP, 'big.ts');
+ writeFileSync(filePath, `export const blob = "${'x'.repeat(CODE_FILE_MAX_BYTES)}";\n`);
+
+ const engine = mockEngine();
+ const result = await importFile(engine, filePath, 'big.ts', { noEmbed: true });
+
+ expect(result.status).toBe('skipped');
+ expect(result.error).toContain('too large');
+ expect((engine as any)._calls.length).toBe(0);
});
test('assigns sequential chunk_index values', async () => {
diff --git a/test/import-screen.test.ts b/test/import-screen.test.ts
index 8734bff7b3..7e2edb88f2 100644
--- a/test/import-screen.test.ts
+++ b/test/import-screen.test.ts
@@ -17,6 +17,7 @@ import { importFromContent, MAX_FILE_SIZE } from '../src/core/import-file.ts';
import { isContentRefusal, screenImportContent, type ImportSanityConfig } from '../src/core/import-screen.ts';
import { managedImportContent, readImportBytes } from '../src/core/persistence/import-prepare.ts';
import { readSyncFile } from '../src/core/persistence/sync-discovery.ts';
+import { SYNC_READ_BOUND } from '../src/core/persistence/sync-blobs.ts';
import { frontmatterSlugConflictMessage } from '../src/core/persistence/verb-errors.ts';
import { OperationError } from '../src/core/ops/contract.ts';
@@ -122,7 +123,7 @@ describe('isContentRefusal', () => {
try { readImportBytes(big); } catch (error) { importRefusal = error as OperationError; }
expect(isContentRefusal(importRefusal!.code, importRefusal!.message)).toBe(true);
const huge = join(dir, 'huge.md');
- writeFileSync(huge, Buffer.alloc(10 * 1024 ** 2 + 1, 'a'));
+ writeFileSync(huge, Buffer.alloc(SYNC_READ_BOUND + 1, 'a'));
let syncRefusal: OperationError | null = null;
try { readSyncFile(dir, 'huge.md'); } catch (error) { syncRefusal = error as OperationError; }
expect(syncRefusal!.code).toBe('request_too_large');
diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.ts
index c96d952ad7..75ca8f382c 100644
--- a/test/managed-maintenance.test.ts
+++ b/test/managed-maintenance.test.ts
@@ -301,7 +301,7 @@ test('consolidation retains a bounded semantic intent and honors configured admi
await seed(engine, sourceId);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
const limits = await readJournalLimits(engine);
- expect(limits.principalIntentBytes).toBe(32 * 1024 ** 2);
+ expect(limits.principalIntentBytes).toBe(64 * 1024 ** 2);
expect(limits.brainIntentBytes).toBe(256 * 1024 ** 2);
const key = 'persistence.limits.principal_intent_bytes';
const original = await engine.getConfig(key);
diff --git a/test/managed-sync-pinned-reads.test.ts b/test/managed-sync-pinned-reads.test.ts
index bb00a1b087..69dcda1c09 100644
--- a/test/managed-sync-pinned-reads.test.ts
+++ b/test/managed-sync-pinned-reads.test.ts
@@ -32,6 +32,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { __setPinnedWindowForTests } from '../src/core/persistence/sync-blobs.ts';
import { syncGitTopLevel } from '../src/core/persistence/sync-prepare.ts';
import { withEnv } from './helpers/with-env.ts';
+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-pinned-reads-'));
const SOURCE = 'pinned-reads';
@@ -76,7 +77,7 @@ const corpus = (): Record<string, string> => ({
'vault/notes/crlf.md': '---\r\ntitle: Line endings\r\ntype: note\r\n---\r\nWritten with CRLF line endings.\r\n',
'vault/notes/conflict.md': '---\ntitle: Conflict\nslug: notes/somewhere-else\n---\nDeclares a slug its path does not have.\n',
'vault/notes/broken.md': '---\ntitle: first line of a title\nsecond line of the title\n---\nA synthetic note.\n',
- 'vault/big/oversize.md': `---\ntitle: Oversize\n---\n${'x'.repeat(10 * 1024 ** 2 + 64)}\n`,
+ 'vault/big/oversize.md': `---\ntitle: Oversize\n---\n${'x'.repeat(PAGE_MAX_BYTES + 64)}\n`,
'outside/readme.md': '# Not in the source\n',
});
function secondRound(root: string) {