Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

embed: declare hosted per-input caps; split chunks a provider rejects as too long (PR #5922, PR #5347)

garrytan6291936e5dab
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index f5e96d191c..8924b934ce 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -34,7 +34,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. `decorateEmbeddingDimError(err, slug)`: maps pgvector's bare "expected N dimensions, not M" write rejection to a named `OperationError('embedding_plane_split', …)` carrying the consequence (page NOT written, transaction rolled back) + recovery command; applied at `importFromContent`'s transaction boundary so `gbrain put` fails loudly instead of echoing an unexplained provider string; every other error passes through untouched. Pinned by `test/embedding-dim-check-facts.test.ts` + `test/put-page-embedding-plane-split.test.ts`. `embeddingMismatchMessage` on PGLite offers, in order, keeping the existing width when the requested model supports it (in-place `init --force … --path <active>`), a previewed `gbrain migrate embeddings --to … --dim … --dry-run` that keeps pages and DB-only facts, and `gbrain reinit-pglite` as the labelled last resort; it never prints a hand-run wipe.
- `src/commands/embeddings.ts` — `gbrain embeddings enable --embedding-model <p:m> [--embedding-dimensions N] [--brain <id>] [--json]`: turns embeddings on in place for the selected brain, including a mount (where `init --force` would repoint the host config at the mount's datastore). Opens the datastore, reads the vector column width (default for `--embedding-dimensions`) and stored identity; refuses with `embedding_width_mismatch` or `embedding_model_mismatch` (fix Action, nothing changed); refuses a mount whose host already embeds with another model (the model is host-wide). Writes the host file-plane `embedding_model`/`embedding_dimensions`, clears `embedding_disabled`, and reports `queued_chunks`/`queued_facts` plus `gbrain embed --stale [--brain]`. The fix readiness emits for mounted brains; exercised by `test/readiness-embedding-enablement.serial.test.ts`.
-- `src/core/embedding-input-limit.ts` — per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep). `resolveMaxChunkTokens(env?)` resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts: `GBRAIN_MAX_CHUNK_TOKENS` env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model `max_input_tokens` × `EMBED_INPUT_SAFETY` (0.6 — covers the cl100k-based `estimateEmbedTokens` overestimate vs BERT-wordpiece tokenizer mismatch) → `DEFAULT_MAX_CHUNK_TOKENS` (2000 for every other provider). `MIN_CHUNK_TOKENS` floor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs). `maxInputTokensForModel(recipe, modelId)` mirrors `model_dims`' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at `import-file.ts`'s chunk step. Pinned by `test/embedding-input-limit.test.ts`.
+- `src/core/embed-overlength-heal.ts` — [R13] (PR #5347): a chunk the embedder rejects as too long on a model with NO declared `max_input_tokens` is SPLIT, not parked and not retried identically forever. `isSingleInputOverLengthError` (status 400/413/422, one of the field-seen message shapes, never a batch-shaped message or the gateway's `isTokenLimitError`), `overLengthLimitFromMessage`, `deriveOverLengthChunkCap` (named limit × `EMBED_INPUT_SAFETY`, else half the largest failed text's estimate; null when not below the current cap or below `MIN_USEFUL_CHUNK_TOKENS` = 128), `healPageAfterOverLength` (learns the cap for the model, heals the page at that cap at once; `skipped` with a reason — `not_overlength`, `unresolved_model`, `declared_cap` (recipe or `GBRAIN_MAX_CHUNK_TOKENS`: the declaration is what to fix), `attempts_exhausted` (`MAX_OVERLENGTH_HEAL_ATTEMPTS` = 3 per page per process), `cap_floor`, `nothing_to_split`, `heal_failed` — leaves the page untouched) and `describeOverLengthOutcome` (the operator line naming the fix). `healAndReportOverLength` is the one-liner every failure site calls: `src/commands/embed.ts` (embedPage total/partial failure, embedAll, embedAllStale) and `src/core/embed-stale.ts` (`embedStaleForSource` catch). `statusFromCause` moved here from embed.ts (one home). Pinned by `test/embed-overlength-heal.test.ts` and `test/embed-overlength-drain.serial.test.ts`.
+
+- `src/core/embedding-input-limit.ts` — per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep). `resolveMaxChunkTokens(env?)` resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts: `GBRAIN_MAX_CHUNK_TOKENS` env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model `max_input_tokens` × `EMBED_INPUT_SAFETY` (0.6 — covers the cl100k-based `estimateEmbedTokens` overestimate vs BERT-wordpiece tokenizer mismatch) → `DEFAULT_MAX_CHUNK_TOKENS` (2000 for every other provider). `MIN_CHUNK_TOKENS` floor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs). `maxInputTokensForModel(recipe, modelId)` mirrors `model_dims`' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at `import-file.ts`'s chunk step. Pinned by `test/embedding-input-limit.test.ts`. Declared limits ([R13] audit, PR #5922): NVIDIA `nvidia/nv-embedqa-e5-v5` 512; DashScope `text-embedding-v1`/`v2` 2048, `v3` 8192; Google `gemini-embedding-001` 2048 (the endpoint truncates silently past it); Zhipu `embedding-2` 512, `embedding-3` 3072; OpenAI `text-embedding-3-*` 8191 and Mistral `mistral-embed` 8192 (above the default, so no chunking change). Pinned by `test/embedding-input-limit-hosted-caps.test.ts`. **Learned caps** (`learnChunkCap` / `learnedChunkCap` / `_resetLearnedChunkCapsForTest`): a process-lifetime per-`provider:model` chunk cap that `src/core/embed-overlength-heal.ts` derives from a provider's single-input over-length rejection when the model declares nothing; `resolveMaxChunkTokens` applies it after the env override and the recipe declaration (both win over it), clamped to the same floor/ceiling.
- `src/core/embedding-invalidation.ts` — signature-truth guards shared by migration and embed paths, using identical SQL on both engines. `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})` adds the stale selectors' embed-skip and projection-seal fences to raw engine invalidation. Current model/hash/width chunks survive interrupted batches; fully current active pages can be restamped without another embedding call. Source `FOR SHARE` locks precede mutation in short transactions, serializing both signature writes, raw engine signature/content-drift invalidation, false-stamp clearing and final reconciliation against archive. Archived vectors and page signatures are never mutated. The shared `falseStampPageWhere` and `countFalseStampedChunks` remain archive-visible for retention, plan and completion diagnostics; only the clearing write is fenced. Bare provider-less model aliases retain their existing exemption. Provider dispatch and completion smoke run outside source locks and revalidate live, safe snapshots before sending text. Pinned by `test/embedding-migration.test.ts` and the shared `test/embedding-recovery.serial.test.ts` suite: PGLite runs in the serial lane, while `test/e2e/embedding-recovery-parity.test.ts` selects PostgreSQL.
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index ef0e649718..7674323b01 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -118,6 +118,8 @@ Set `GOOGLE_GENERATIVE_AI_API_KEY` (the AI Studio public API key). Models: `gemi
GCP service-account / Vertex AI auth (Vertex ADC) is not supported; only the AI Studio API key path is wired.
+`gemini-embedding-001` takes at most 2,048 tokens per input and the endpoint truncates longer inputs silently (`autoTruncate` defaults on), which embeds a lossy vector rather than failing. gbrain declares the cap so chunks on `-001` are capped at 1,228 estimated tokens and split instead (see [Per-input token caps](#per-input-token-caps)). `gemini-embedding-2`'s per-input limit is not declared yet.
+
### OpenRouter
Single OpenAI-compatible API for fan-out to OpenAI, Anthropic, Google, DeepSeek, Meta Llama, Qwen, and dozens of other hosted providers. One key, many models. Set `OPENROUTER_API_KEY` or `openrouter_api_key` in `~/.gbrain/config.json`, then use `openrouter:<provider>/<model>` (e.g. `openrouter:openai/gpt-5.2`, `openrouter:anthropic/claude-sonnet-4.6`).
@@ -148,14 +150,18 @@ MiniMax's API takes a `type: 'db' | 'query'` field for asymmetric retrieval. gbr
### DashScope (Alibaba)
-Set `DASHSCOPE_API_KEY`. International endpoint at `dashscope-intl.aliyuncs.com` by default; override `provider_base_urls.dashscope` for the China endpoint. Models: `text-embedding-v3` (current; Matryoshka 64-1024 dims), `text-embedding-v2`.
+Set `DASHSCOPE_API_KEY`. International endpoint at `dashscope-intl.aliyuncs.com` by default; override `provider_base_urls.dashscope` for the China endpoint. Models: `text-embedding-v3` (current; Matryoshka 64-1024 dims), `text-embedding-v2`, `text-embedding-v1`.
CJK-dominant content tokenizes denser than OpenAI tiktoken; gbrain declares `chars_per_token: 2` so the batch pre-split leaves headroom.
+Per-input caps are declared (see [Per-input token caps](#per-input-token-caps)): `text-embedding-v1` / `v2` take at most 2,048 tokens per input (one over-length item fails the whole request with a 400), `v3` takes 8,192. New chunks on v1/v2 are capped at 1,228 estimated tokens instead of 2,000; a brain chunked before this declaration is split on its next `gbrain embed` / `embed --stale` pass and the split pieces re-embed.
+
### Zhipu AI (BigModel)
Set `ZHIPUAI_API_KEY`. Models: `embedding-3` (current; Matryoshka 256-2048 dims), `embedding-2`. The default is 1024 (HNSW-compatible). The 2048-dim option works but falls into the exact-scan branch (see Voyage 4 Large note above).
+Per-input caps are declared: `embedding-3` takes at most 3,072 tokens per string (chunks capped at 1,843 estimated tokens), `embedding-2` 512 (chunks capped at 307). See [Per-input token caps](#per-input-token-caps).
+
### Ollama (local)
No env required — Ollama runs unauthenticated locally. Optional `OLLAMA_BASE_URL` (default `http://localhost:11434/v1`) and `OLLAMA_API_KEY` (for auth-enabled deployments).
@@ -223,6 +229,12 @@ Three numbers matter:
For most users: **stay at 1024 or 1536**. Bigger isn't better below the noise floor; smaller saves disk + RAM with marginal recall loss on Matryoshka providers.
+## Per-input token caps
+
+Some hosted encoders reject (or silently truncate) any SINGLE input over a per-input token limit, far below their batch budget. A recipe declares the documented limit per model (`max_input_tokens`), and the chunker caps new chunks at `floor(limit × 0.6)` estimated tokens, never above the 2,000-token default, splitting rather than truncating; `gbrain embed` and `embed --stale` split already-stored chunks the same way before sending them. Declared today: NVIDIA `nvidia/nv-embedqa-e5-v5` 512; Zhipu `embedding-2` 512, `embedding-3` 3,072; DashScope `text-embedding-v1` / `v2` 2,048, `v3` 8,192; Google `gemini-embedding-001` 2,048; OpenAI `text-embedding-3-*` 8,191; Mistral `mistral-embed` 8,192 (the last three are above the default chunk cap, so chunking is unchanged). `GBRAIN_MAX_CHUNK_TOKENS` overrides the resolved cap for a model no recipe declares.
+
+When a model declares no cap and the provider answers a single input with an over-length 400 (`input length exceeds the context length`, `exceeds maximum allowed token size N`, `Range of input length should be [1, N]`, …), the embed pass derives a smaller cap from the failure (the limit the message names × 0.6, otherwise half the largest failed chunk's estimate), keeps it for that model for the rest of the process, and splits the failing page at once; the pieces embed on the next pass, and later pages are split before their first request. The descent is finite: three attempts per page per process and never below 128 tokens, after which the failure is reported with the fix (`GBRAIN_MAX_CHUNK_TOKENS=<limit>`, a recipe `max_input_tokens` entry, or `embed_skip` on the page). A model whose cap IS declared gets no derived cap: the declaration is what to correct. Unrelated 400s (bad key, unknown model) and batch-level token errors never rewrite a chunk.
+
## Bulk-embed failure knobs
Two env vars tune how bulk embeds (`gbrain embed --stale` and the autopilot/minion cycles that ride the same stale path) behave under sustained failures. Both matter most against local serial servers (Ollama at `-np 1`, llama-server), where re-sending doomed requests compounds into congestion collapse:
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 0f61b7bd2e..24987a92f2 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -142,6 +142,7 @@ test/embed-exit-code-3037.serial.test.ts global-state global-state: binds local
test/embed-input-type-wire.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
test/embed-lock-skipped.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/embed-max-usd-metered.serial.test.ts global-state global-state: configureGateway and __setEmbedTransportForTests change the process-wide AI gateway; replaces globalThis.fetch for the Voyage multimodal stub
+test/embed-overlength-drain.serial.test.ts R2 R2: mock.module(src/core/embedding.ts) fake embedder; R1: mutates process.env (GBRAIN_MAX_CHUNK_TOKENS)
test/embed-null-signature-warning-5527.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.error
test/embed-oversize-heal-drain.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
test/embed-partial-failure-3037.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index a53d3fe1bf..5a73066e1a 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -16,6 +16,7 @@ import { carryChunkMetadata, probeEmbedder, resolveProvenanceStamp, stampIfPageP
import type { StaleImageSweepResult } from '../core/embed-stale-images.ts';
import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from '../core/embed-oversize-heal.ts';
+import { healAndReportOverLength, statusFromCause } from '../core/embed-overlength-heal.ts';
import {
createEmbedStallWatchdog,
resolveEmbedStallAbortSeconds,
@@ -1166,6 +1167,7 @@ async function embedPage(
recordFailure(result, toEmbed.length, slug, e);
result.pages_processed++;
serr(` Error embedding ${slug}: ${e instanceof Error ? e.message : e}`);
+ await healAndReportOverLength(engine, slug, page.source_id, e, toEmbed.map(c => c.chunk_text), serr);
return;
}
const embeddingMap = new Map<number, Float32Array>();
@@ -1197,6 +1199,7 @@ async function embedPage(
if (failed > 0) {
recordFailure(result, failed, slug, firstError);
serr(` ${slug}: ${failed} chunk(s) failed to embed; embedded the other ${toEmbed.length - failed}`);
+ await healAndReportOverLength(engine, slug, page.source_id, firstError, toEmbed.map(c => c.chunk_text), serr);
}
result.pages_processed++;
if (!quiet) slog(`${slug}: embedded ${toEmbed.length - failed} chunks`);
@@ -1379,12 +1382,14 @@ async function embedAll(
if (failed > 0) {
recordFailure(result, failed, page.slug, firstError);
serr(`\n ${page.slug}: ${failed} chunk(s) failed to embed; embedded the other ${toEmbed.length - failed}`);
+ await healAndReportOverLength(engine, page.slug, pageSourceId, firstError, toEmbed.map(c => c.chunk_text), serr);
}
} catch (e: unknown) {
// #3037: count the darkened page so the run can't exit 0 (abort is a
// shutdown, not a failure).
if (!isAborted(signal)) recordFailure(result, toEmbed.length, page.slug, e);
serr(`\n Error embedding ${page.slug}: ${e instanceof Error ? e.message : e}`);
+ if (!isAborted(signal)) await healAndReportOverLength(engine, page.slug, pageSourceId, e, toEmbed.map(c => c.chunk_text), serr);
}
processed++;
@@ -2077,6 +2082,7 @@ async function embedAllStale(
if (failed > 0) {
recordFailure(result, failed, slug, firstError);
serr(`\n ${slug}: ${failed} chunk(s) failed to embed; embedded the other ${stale.length - failed}`);
+ await healAndReportOverLength(engine, slug, keySourceId, firstError, stale.map(c => c.chunk_text), serr);
}
// #3622: reaching here means at least one chunk persisted (a total
// embed failure throws) — progress, so the quarantine counter resets.
@@ -2088,6 +2094,7 @@ async function embedAllStale(
recordFailure(result, stale.length, slug, e);
serr(`\n Error embedding ${slug}: ${e instanceof Error ? e.message : e}`);
noteEmbedQuarantineFailure(key, slug);
+ await healAndReportOverLength(engine, slug, keySourceId, e, stale.map(c => c.chunk_text), serr);
}
processedPageKeys.add(key);
result.pages_processed++;
@@ -2158,18 +2165,6 @@ async function embedAllStale(
}
}
-/** Walk the cause chain (like detect429FromCause) for the first HTTP status. */
-function statusFromCause(e: unknown): number | undefined {
- let cur: unknown = e;
- for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
- const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
- if (typeof obj.status === 'number') return obj.status;
- if (typeof obj.statusCode === 'number') return obj.statusCode;
- cur = obj.cause;
- }
- return undefined;
-}
-
/**
* #3037: embed one page's chunk texts with per-chunk failure isolation.
*
diff --git a/src/core/ai/recipes/dashscope.ts b/src/core/ai/recipes/dashscope.ts
index 01f76ad1b3..9285ccba0c 100644
--- a/src/core/ai/recipes/dashscope.ts
+++ b/src/core/ai/recipes/dashscope.ts
@@ -22,6 +22,7 @@ export const dashscope: Recipe = {
unpriced_models: [
'text-embedding-v3',
'text-embedding-v2',
+ 'text-embedding-v1',
],
base_url_default: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
auth_env: {
@@ -30,8 +31,18 @@ export const dashscope: Recipe = {
},
touchpoints: {
embedding: {
- models: ['text-embedding-v3', 'text-embedding-v2'],
+ models: ['text-embedding-v3', 'text-embedding-v2', 'text-embedding-v1'],
default_dims: 1024,
+ // PR #5922 / #4530: DashScope's documented per-INPUT caps (Model Studio
+ // "Synchronous API for text embedding", read 2026-10-11): v1/v2 reject
+ // any single input over 2,048 tokens with a 400 that fails the whole
+ // batch; v3 accepts 8,192. The chunker splits to floor(cap × 0.6)
+ // (resolveMaxChunkTokens) and the heal pass splits stored rows.
+ max_input_tokens: {
+ 'text-embedding-v1': 2048,
+ 'text-embedding-v2': 2048,
+ 'text-embedding-v3': 8192,
+ },
dims_options: [64, 128, 256, 512, 768, 1024],
// Alibaba doesn't publish a hard batch-token cap for the OpenAI-compat
// path. Conservative declaration so the gateway pre-splits before
diff --git a/src/core/ai/recipes/google.ts b/src/core/ai/recipes/google.ts
index cc9a37ff0c..3f9d3518ab 100644
--- a/src/core/ai/recipes/google.ts
+++ b/src/core/ai/recipes/google.ts
@@ -46,6 +46,12 @@ export const google: Recipe = {
// allowlist — see assertTouchpoint. Its vector space is incompatible
// with -001: switching an existing brain needs `gbrain migrate embeddings`.
models: ['gemini-embedding-001', 'gemini-embedding-2'],
+ // [R13] audit: gemini-embedding-001's documented input limit is 2,048
+ // tokens and the endpoint TRUNCATES silently past it (autoTruncate
+ // defaults on), so an over-length chunk embeds as a lossy vector, not
+ // an error. Declaring it makes the chunker split instead.
+ // gemini-embedding-2's limit is not declared here until confirmed.
+ max_input_tokens: { 'gemini-embedding-001': 2048 },
default_dims: 768,
dims_options: [768, 1536, 3072],
cost_per_1m_tokens_usd: 0.15,
diff --git a/src/core/ai/recipes/mistral.ts b/src/core/ai/recipes/mistral.ts
index 3b0d235a81..3d1741b97a 100644
--- a/src/core/ai/recipes/mistral.ts
+++ b/src/core/ai/recipes/mistral.ts
@@ -49,6 +49,9 @@ export const mistral: Recipe = {
touchpoints: {
embedding: {
models: ['mistral-embed', 'mistral-embed-2312'],
+ // [R13] audit: mistral-embed's 8,192-token per-input context. Above the
+ // default chunk cap, so chunking is unchanged.
+ max_input_tokens: { 'mistral-embed': 8192, 'mistral-embed-2312': 8192 },
default_dims: 1024,
// Mistral's published list price. Advisory only — canonical embedding
// spend accounting lives in src/core/embedding-pricing.ts.
diff --git a/src/core/ai/recipes/openai.ts b/src/core/ai/recipes/openai.ts
index c07092972a..33edfeed60 100644
--- a/src/core/ai/recipes/openai.ts
+++ b/src/core/ai/recipes/openai.ts
@@ -52,6 +52,10 @@ export const openai: Recipe = {
touchpoints: {
embedding: {
models: ['text-embedding-3-large', 'text-embedding-3-small'],
+ // [R13] audit: documented 8,191-token per-input limit. Above the
+ // 2000-token default chunk cap, so chunking is unchanged; it bounds the
+ // per-request reservation and names the cap for the heal pass.
+ max_input_tokens: { 'text-embedding-3-large': 8191, 'text-embedding-3-small': 8191 },
default_dims: 1536,
dims_options: [256, 512, 768, 1024, 1536, 3072],
cost_per_1m_tokens_usd: 0.13,
diff --git a/src/core/ai/recipes/zhipu.ts b/src/core/ai/recipes/zhipu.ts
index de3137de5f..51bcfd1dee 100644
--- a/src/core/ai/recipes/zhipu.ts
+++ b/src/core/ai/recipes/zhipu.ts
@@ -66,6 +66,10 @@ export const zhipu: Recipe = {
},
embedding: {
models: ['embedding-3', 'embedding-2'],
+ // [R13] audit: BigModel's documented per-INPUT caps (text-embedding API
+ // reference, read 2026-10-11): embedding-2 takes 512 tokens per string,
+ // embedding-3 takes 3,072.
+ max_input_tokens: { 'embedding-3': 3072, 'embedding-2': 512 },
default_dims: 1024,
// 2048 exposed but breaks HNSW (exact-scan fallback). 1024/512/256
// stay HNSW-compatible.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 38eb70527b..e1b27c3095 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -439,6 +439,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
// Fix wave 15 G6 (GBRA-79).
{ since: '0.60.176.0', text: 'A subagent job whose final model turn produced no answer (an empty or whitespace-only body, a thinking-only turn) now ends with `stop_reason: error`, and a turn the provider stopped with `refusal` ends `refusal`; both used to be reported as a clean `end_turn`. A resumed job whose stored transcript already ends on such a turn is answered from the transcript with that stop reason instead of sending the turn back to the provider as an assistant prefill (which Haiku 5.5 and Sonnet 4.6+ reject with HTTP 400). The queue\'s terminal-state policy is unchanged; `require_writes` jobs that produced nothing already failed.' },
+ { since: '0.60.176.0', text: 'Embedding chunks are now capped at the documented per-input limit of four more hosted encoders: DashScope `text-embedding-v1` / `v2` (2,048 tokens; new chunks at most 1,228 estimated tokens instead of 2,000), Google `gemini-embedding-001` (2,048; it used to truncate long chunks silently), Zhipu `embedding-3` (3,072; chunks at most 1,843) and `embedding-2` (512; chunks at most 307). On a brain using one of them, the next `gbrain embed` or `embed --stale` pass splits stored chunks over the cap and re-embeds the pieces (billed as ordinary embedding tokens); other models chunk as before. A model with no declared cap whose provider rejects one chunk as too long is now split to a cap derived from that rejection and retried on the next pass, at most three times per page, instead of failing identically on every pass; the failure line names the fix when the descent stops.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/embed-overlength-heal.ts b/src/core/embed-overlength-heal.ts
new file mode 100644
index 0000000000..010c0740d5
--- /dev/null
+++ b/src/core/embed-overlength-heal.ts
@@ -0,0 +1,218 @@
+/**
+ * [R13] (PR #5347) — split a chunk the embedder rejected as too long when the
+ * model declares NO per-input cap.
+ *
+ * `healOversizedPageChunks` splits stored chunks to the active model's cap
+ * (`resolveMaxChunkTokens`). With no recipe declaration that cap is the
+ * 2000-token default, so a provider whose real limit is lower keeps
+ * answering the same 400 ("input length exceeds the context length") on
+ * every sweep and the page never embeds. Writing `embed_skip` from a sweep is
+ * not an option (it advances the page revision outside the write lock), so
+ * the answer is a SPLIT, not a park:
+ *
+ * 1. recognise a single-input over-length rejection (400/413/422 plus one
+ * of the message shapes below; batch-level token errors, which the
+ * gateway's adaptive shrink owns, are excluded);
+ * 2. derive a deterministic smaller cap: the limit the message names ×
+ * EMBED_INPUT_SAFETY, else half the largest failed text's estimate;
+ * 3. learn it for the model for the rest of the process
+ * (`learnChunkCap`), so every later heal and import splits the same way;
+ * 4. heal the failing page at once with that cap — the pieces are stale
+ * and embed on the next pass through the ordinary chunk upsert.
+ *
+ * The descent is finite: MAX_OVERLENGTH_HEAL_ATTEMPTS per page per process,
+ * never below MIN_USEFUL_CHUNK_TOKENS, and a model whose cap IS declared
+ * (recipe `max_input_tokens` or GBRAIN_MAX_CHUNK_TOKENS) is terminal here
+ * because the declaration, not the chunking, is what needs fixing.
+ */
+
+import { estimateEmbedTokens } from './chunkers/token-estimate.ts';
+import { getEmbeddingModel, isTokenLimitError } from './ai/gateway.ts';
+import { resolveRecipe } from './ai/model-resolver.ts';
+import {
+ EMBED_INPUT_SAFETY,
+ learnChunkCap,
+ maxInputTokensForModel,
+ resolveMaxChunkTokens,
+} from './embedding-input-limit.ts';
+import { healOversizedPageChunks } from './embed-oversize-heal.ts';
+import type { BrainEngine } from './engine.ts';
+
+/** Below this a chunk carries too little context to be worth a vector. */
+export const MIN_USEFUL_CHUNK_TOKENS = 128;
+/** Halvings a page gets per process before the failure is reported as terminal. */
+export const MAX_OVERLENGTH_HEAL_ATTEMPTS = 3;
+
+export type OverLengthHealOutcome =
+ | { kind: 'healed'; cap: number; splitCount: number }
+ | { kind: 'skipped'; reason: 'not_overlength' | 'unresolved_model' | 'declared_cap' | 'attempts_exhausted' | 'cap_floor' | 'nothing_to_split' | 'heal_failed' };
+
+/** Walk the cause chain (like detect429FromCause) for the first HTTP status. */
+export function statusFromCause(e: unknown): number | undefined {
+ let cur: unknown = e;
+ for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
+ const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
+ if (typeof obj.status === 'number') return obj.status;
+ if (typeof obj.statusCode === 'number') return obj.statusCode;
+ cur = obj.cause;
+ }
+ return undefined;
+}
+
+const OVER_LENGTH_STATUSES = new Set([400, 413, 422]);
+
+const OVER_LENGTH_PATTERNS: readonly RegExp[] = [
+ // NVIDIA NIM: "Input length 1460 exceeds maximum allowed token size 512"
+ /exceeds?\s+(?:the\s+)?max(?:imum)?[^.\n]{0,40}(?:token|context|length|limit)/i,
+ // llama.cpp / Ollama: "input length exceeds the context length"
+ /(?:input|prompt|text|sequence)[^.\n]{0,30}exceeds?[^.\n]{0,30}(?:context|length|limit)/i,
+ // OpenAI-compatible: "This model's maximum context length is 8192 tokens, however you requested …"
+ /max(?:imum)?\s+context\s+length\s+is\s+\d+/i,
+ // DashScope: "Range of input length should be [1, 2048]"
+ /range\s+of\s+input\s+length/i,
+ // Generic: "input text is too long", "text too long for this model"
+ /(?:input|prompt|text|sequence)[^.\n]{0,30}too\s+long/i,
+];
+
+const BATCH_SHAPED = /\b(?:batch|per\s+request|overall|request\s+size)\b/i;
+
+function messageOf(e: unknown): string {
+ let cur: unknown = e;
+ const parts: string[] = [];
+ for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
+ const obj = cur as { message?: unknown; cause?: unknown };
+ if (typeof obj.message === 'string') parts.push(obj.message);
+ cur = obj.cause;
+ }
+ return parts.join(' | ');
+}
+
+/**
+ * True for a permanent request-shaped rejection whose message says ONE input
+ * is too long. Batch-level token errors (the gateway's `isTokenLimitError`,
+ * or any message about the batch / request as a whole) are not: shrinking
+ * the batch, not the chunk, is their fix.
+ */
+export function isSingleInputOverLengthError(e: unknown): boolean {
+ const status = statusFromCause(e);
+ if (status === undefined || !OVER_LENGTH_STATUSES.has(status)) return false;
+ if (isTokenLimitError(e)) return false;
+ const msg = messageOf(e);
+ if (BATCH_SHAPED.test(msg)) return false;
+ return OVER_LENGTH_PATTERNS.some((re) => re.test(msg));
+}
+
+/** The token limit an over-length message names, when it names one. */
+export function overLengthLimitFromMessage(msg: string): number | undefined {
+ const m =
+ msg.match(/(?:token\s+size|context\s+length\s+is|limit\s+of|maximum\s+of|up\s+to)\s+(\d{2,7})/i)
+ ?? msg.match(/\[\s*\d+\s*,\s*(\d{2,7})\s*\]/)
+ ?? msg.match(/(\d{2,7})\s+tokens?\b(?!\s*\()/i);
+ if (!m) return undefined;
+ const n = Number(m[1]);
+ return Number.isFinite(n) && n > 0 ? n : undefined;
+}
+
+/**
+ * The next chunk cap to try, or null when no useful smaller cap exists: the
+ * named limit × EMBED_INPUT_SAFETY when the message names one, else half the
+ * largest failed text's estimate. Deterministic for the same error and
+ * texts. Null when the result is not below `currentCap` (the rejection is
+ * not about our chunk size) or below MIN_USEFUL_CHUNK_TOKENS.
+ */
+export function deriveOverLengthChunkCap(e: unknown, texts: ReadonlyArray<string>, currentCap: number): number | null {
+ const named = overLengthLimitFromMessage(messageOf(e));
+ const largest = texts.reduce((max, t) => Math.max(max, estimateEmbedTokens(t)), 0);
+ const cap = named !== undefined ? Math.floor(named * EMBED_INPUT_SAFETY) : Math.floor(largest / 2);
+ if (cap >= currentCap || cap < MIN_USEFUL_CHUNK_TOKENS) return null;
+ return cap;
+}
+
+const _attempts = new Map<string, number>();
+
+/** Test seam: forget every page's attempt count. */
+export function _resetOverLengthHealForTest(): void {
+ _attempts.clear();
+}
+
+/**
+ * After an embed failure on `slug`: when `err` is a single-input over-length
+ * rejection and the active model declares no cap, learn a smaller cap and
+ * split the page's chunks to it now. Every other case is `skipped` with the
+ * reason, and the page is left exactly as it was.
+ */
+export async function healPageAfterOverLength(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+ err: unknown,
+ texts: ReadonlyArray<string>,
+ env: Record<string, string | undefined> = process.env,
+): Promise<OverLengthHealOutcome> {
+ if (!isSingleInputOverLengthError(err)) return { kind: 'skipped', reason: 'not_overlength' };
+ let model: string;
+ let resolved: ReturnType<typeof resolveRecipe>;
+ try {
+ model = getEmbeddingModel();
+ resolved = resolveRecipe(model);
+ } catch {
+ return { kind: 'skipped', reason: 'unresolved_model' };
+ }
+ const { parsed, recipe } = resolved;
+ const pinned = env.GBRAIN_MAX_CHUNK_TOKENS;
+ if ((pinned !== undefined && pinned.trim() !== '') || maxInputTokensForModel(recipe, parsed.modelId) !== undefined) {
+ return { kind: 'skipped', reason: 'declared_cap' };
+ }
+ const key = `${model}::${sourceId}::${slug}`;
+ const attempts = _attempts.get(key) ?? 0;
+ if (attempts >= MAX_OVERLENGTH_HEAL_ATTEMPTS) return { kind: 'skipped', reason: 'attempts_exhausted' };
+ const cap = deriveOverLengthChunkCap(err, texts, resolveMaxChunkTokens(env, model));
+ if (cap === null) return { kind: 'skipped', reason: 'cap_floor' };
+ _attempts.set(key, attempts + 1);
+ learnChunkCap(model, cap);
+ let healed: Awaited<ReturnType<typeof healOversizedPageChunks>>;
+ try {
+ healed = await healOversizedPageChunks(engine, slug, { sourceId, maxTokens: cap });
+ } catch {
+ // The page moved or the store refused: the next pass heals at the learned cap.
+ return { kind: 'skipped', reason: 'heal_failed' };
+ }
+ if (!healed.changed) return { kind: 'skipped', reason: 'nothing_to_split' };
+ return { kind: 'healed', cap, splitCount: healed.splitCount };
+}
+
+/** One operator-facing line for the outcome, or null when there is nothing to say. */
+export function describeOverLengthOutcome(outcome: OverLengthHealOutcome, slug: string): string | null {
+ if (outcome.kind === 'healed') {
+ return ` ${slug}: embedder rejected a chunk as too long; split ${outcome.splitCount} chunk(s) to ${outcome.cap} estimated tokens (learned for ${getEmbeddingModel()} this process). The pieces embed on the next pass.`;
+ }
+ switch (outcome.reason) {
+ case 'not_overlength':
+ case 'unresolved_model':
+ return null;
+ case 'heal_failed':
+ return ` ${slug}: embedder rejected a chunk as too long; the split could not be stored this pass and is retried at the learned cap on the next one.`;
+ case 'declared_cap':
+ return ` ${slug}: embedder rejected a chunk as too long although the model's cap is declared (recipe max_input_tokens or GBRAIN_MAX_CHUNK_TOKENS); lower that declaration — the chunker already splits to it.`;
+ case 'attempts_exhausted':
+ case 'cap_floor':
+ return ` ${slug}: embedder keeps rejecting a chunk as too long and no useful smaller cap is left (${outcome.reason}); set GBRAIN_MAX_CHUNK_TOKENS to the model's real per-input limit or declare max_input_tokens in its recipe, or mark the page embed_skip.`;
+ case 'nothing_to_split':
+ return ` ${slug}: embedder rejected a chunk as too long but every stored chunk already fits the derived cap; the estimate is under-counting for this model — set GBRAIN_MAX_CHUNK_TOKENS lower.`;
+ }
+}
+
+/** The embed paths' one-liner: heal when the failure is an over-length rejection and print the outcome. */
+export async function healAndReportOverLength(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+ err: unknown,
+ texts: ReadonlyArray<string>,
+ log: (line: string) => void,
+): Promise<OverLengthHealOutcome> {
+ const outcome = await healPageAfterOverLength(engine, slug, sourceId, err, texts);
+ const line = describeOverLengthOutcome(outcome, slug);
+ if (line) log(line);
+ return outcome;
+}
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 5eb806901a..ee819e3305 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -25,6 +25,7 @@ import type { Chunk, ChunkInput } from './types.ts';
import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from './embed-retry.ts';
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from './embed-oversize-heal.ts';
+import { healAndReportOverLength } from './embed-overlength-heal.ts';
import { invalidateStaleSignatureEmbeddingsGuarded, splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
import {
resolveActiveEmbeddingColumnFromEngine,
@@ -599,6 +600,7 @@ export async function embedStaleForSource(
e instanceof Error ? e.message : String(e)
}\n`,
);
+ await healAndReportOverLength(engine, slug, keySourceId, e, stale.map(c => c.chunk_text), line => process.stderr.write(`${line}\n`));
}
}
diff --git a/src/core/embedding-input-limit.ts b/src/core/embedding-input-limit.ts
index be887ae28c..5d5e834e26 100644
--- a/src/core/embedding-input-limit.ts
+++ b/src/core/embedding-input-limit.ts
@@ -61,6 +61,31 @@ export function maxInputTokensForModel(recipe: Recipe, modelId: string): number
return undefined;
}
+/**
+ * [R13] (PR #5347): chunk caps LEARNED from a provider's single-input
+ * over-length rejection for a model that declares no `max_input_tokens`
+ * (`src/core/embed-overlength-heal.ts` derives them). Process-lifetime by
+ * design, like the embed quarantine: a long-lived sweep splits every later
+ * page the same way, a restart re-derives the same cap from the same
+ * failure. Keyed by the full `provider:model` string; an operator
+ * GBRAIN_MAX_CHUNK_TOKENS and a recipe declaration both win over it.
+ */
+const _learnedChunkCaps = new Map<string, number>();
+
+export function learnChunkCap(model: string, cap: number): void {
+ const current = _learnedChunkCaps.get(model);
+ if (current === undefined || cap < current) _learnedChunkCaps.set(model, cap);
+}
+
+export function learnedChunkCap(model: string): number | undefined {
+ return _learnedChunkCaps.get(model);
+}
+
+/** Test seam: forget every learned cap. */
+export function _resetLearnedChunkCapsForTest(): void {
+ _learnedChunkCaps.clear();
+}
+
/**
* Effective chunk-token cap for the active embedding model (or `model`). See module doc.
* Never exceeds DEFAULT_MAX_CHUNK_TOKENS (existing downstream sizing —
@@ -84,7 +109,8 @@ export function resolveMaxChunkTokens(env: Record<string, string | undefined> =
}
}
try {
- const { parsed, recipe } = resolveRecipe(model ?? getEmbeddingModel());
+ const modelStr = model ?? getEmbeddingModel();
+ const { parsed, recipe } = resolveRecipe(modelStr);
const declared = maxInputTokensForModel(recipe, parsed.modelId);
if (declared !== undefined) {
return Math.min(
@@ -92,6 +118,8 @@ export function resolveMaxChunkTokens(env: Record<string, string | undefined> =
Math.max(MIN_CHUNK_TOKENS, Math.floor(declared * EMBED_INPUT_SAFETY)),
);
}
+ const learned = _learnedChunkCaps.get(modelStr);
+ if (learned !== undefined) return Math.min(DEFAULT_MAX_CHUNK_TOKENS, Math.max(MIN_CHUNK_TOKENS, learned));
} catch {
// Gateway not configured (tests, engine-free paths) or unknown provider —
// keep the historical default.
diff --git a/test/embed-overlength-drain.serial.test.ts b/test/embed-overlength-drain.serial.test.ts
new file mode 100644
index 0000000000..af64c999b8
--- /dev/null
+++ b/test/embed-overlength-drain.serial.test.ts
@@ -0,0 +1,183 @@
+/**
+ * [R13] (PR #5347) drain-integration pins — an embedder's single-input
+ * over-length 400 on a model with NO declared cap must make the drains SPLIT
+ * the page (deterministically, at once) instead of re-sending the same
+ * doomed chunk every pass; an unrelated 400 must leave every stored chunk
+ * byte-identical.
+ *
+ * test/embed-overlength-heal.test.ts covers the helper; these tests seed a
+ * REAL PGLite page and run the actual drains against a fake embedder that
+ * rejects any input over a hidden limit the way a hosted encoder does:
+ * - `runEmbedCore({stale})` → embedAllStale (src/commands/embed.ts)
+ * - `embedStaleForSource` (src/core/embed-stale.ts)
+ *
+ * Serial: uses mock.module and the gateway's embedding model
+ * (module-registry quarantine per docs/TESTING.md).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, mock } from 'bun:test';
+
+const HIDDEN_LIMIT = 500;
+let embedBatchTexts: string[] = [];
+let rejection: 'overlength' | 'unrelated' = 'overlength';
+
+function fakeEmbed(texts: string[]): Float32Array[] {
+ embedBatchTexts.push(...texts);
+ for (const t of texts) {
+ if (estimateEmbedTokens(t) > HIDDEN_LIMIT) {
+ const message = rejection === 'overlength'
+ ? `Input length ${estimateEmbedTokens(t)} exceeds maximum allowed token size ${HIDDEN_LIMIT}`
+ : 'Incorrect API key provided';
+ throw Object.assign(new Error(message), { status: 400 });
+ }
+ }
+ return texts.map(() => { const v = new Float32Array(768); v[0] = 9; return v; });
+}
+
+mock.module('../src/core/embedding.ts', () => ({
+ embedBatch: async (texts: string[]) => fakeEmbed(texts),
+ currentEmbeddingSignature: () => null,
+ embedMultimodal: async (inputs: unknown[]) => inputs.map(() => new Float32Array(512)),
+}));
+
+const { runEmbedCore, _resetEmbedQuarantineForTest } = await import('../src/commands/embed.ts');
+const { embedStaleForSource } = await import('../src/core/embed-stale.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+const { resetPgliteState } = await import('./helpers/reset-pglite.ts');
+const { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } = await import('../src/core/chunkers/token-estimate.ts');
+const { __setEmbedTransportForTests, configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');
+const { resolveMaxChunkTokens, learnedChunkCap, _resetLearnedChunkCapsForTest } = await import('../src/core/embedding-input-limit.ts');
+const { _resetOverLengthHealForTest, MIN_USEFUL_CHUNK_TOKENS } = await import('../src/core/embed-overlength-heal.ts');
+const { installFixtureChunks } = await import('./helpers/page-projection.ts');
+import type { ChunkInput } from '../src/core/types.ts';
+
+__setEmbedTransportForTests(async () => ({ embeddings: [], usage: { tokens: 0 } } as never));
+
+/** No recipe declaration and no GBRAIN_MAX_CHUNK_TOKENS: the case this fix exists for. */
+const UNDECLARED_MODEL = 'ollama:nomic-embed-text';
+const EXPECTED_CAP = Math.floor(HIDDEN_LIMIT * 0.6); // 300
+const SIBLING_TEXT = 'short sibling that already has a vector';
+const OVERSIZED =
+ 'The quarterly operating review covers hiring plans, infrastructure spend, customer renewals ' +
+ 'and the product roadmap for the next two quarters in considerable detail. '.repeat(60);
+
+let engine: InstanceType<typeof PGLiteEngine>;
+const priorChunkTokens = process.env.GBRAIN_MAX_CHUNK_TOKENS;
+
+beforeAll(async () => {
+ delete process.env.GBRAIN_MAX_CHUNK_TOKENS;
+ resetGateway();
+ configureGateway({ embedding_model: UNDECLARED_MODEL, embedding_dimensions: 768, env: {} });
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ // Between the hidden limit and the default cap: the stored row fits OUR cap and fails THEIRS.
+ expect(estimateEmbedTokens(OVERSIZED)).toBeGreaterThan(HIDDEN_LIMIT);
+ expect(estimateEmbedTokens(OVERSIZED)).toBeLessThanOrEqual(DEFAULT_MAX_CHUNK_TOKENS);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 30000);
+
+afterAll(async () => {
+ if (priorChunkTokens === undefined) delete process.env.GBRAIN_MAX_CHUNK_TOKENS;
+ else process.env.GBRAIN_MAX_CHUNK_TOKENS = priorChunkTokens;
+ __setEmbedTransportForTests(null);
+ _resetLearnedChunkCapsForTest();
+ _resetOverLengthHealForTest();
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ embedBatchTexts = [];
+ rejection = 'overlength';
+ _resetLearnedChunkCapsForTest();
+ _resetOverLengthHealForTest();
+ _resetEmbedQuarantineForTest();
+ process.env.GBRAIN_EMBED_CONCURRENCY = '1';
+});
+
+async function seedPage(slug: string): Promise<void> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nseeded` });
+ const siblingVec = new Float32Array(768);
+ siblingVec[0] = 0.5;
+ const chunks: ChunkInput[] = [
+ { chunk_index: 0, chunk_text: SIBLING_TEXT, chunk_source: 'compiled_truth', token_count: 8, embedding: siblingVec },
+ { chunk_index: 1, chunk_text: OVERSIZED, chunk_source: 'compiled_truth', token_count: 600, embedding: undefined },
+ ];
+ await installFixtureChunks(engine, slug, chunks);
+}
+
+async function assertSplitAtLearnedCap(slug: string): Promise<void> {
+ // The observable first: the stored oversized row was split in the failing pass itself.
+ const after = await engine.getChunks(slug, { includeEmbedding: true });
+ expect(after.length).toBeGreaterThan(2);
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBe(EXPECTED_CAP);
+ expect(resolveMaxChunkTokens()).toBe(EXPECTED_CAP);
+ for (const c of after) expect(estimateEmbedTokens(c.chunk_text)).toBeLessThanOrEqual(EXPECTED_CAP);
+ expect(after.map(c => c.chunk_text).join('')).toContain('product roadmap');
+ const sibling = after.find(c => c.chunk_index === 0)!;
+ expect(sibling.chunk_text).toBe(SIBLING_TEXT);
+ expect(sibling.embedding_is_null).toBe(false);
+ expect(EXPECTED_CAP).toBeGreaterThanOrEqual(MIN_USEFUL_CHUNK_TOKENS);
+}
+
+describe('[R13]: an over-length rejection on an undeclared model splits the page', () => {
+ test('runEmbedCore({stale}): the failing pass reports the failure, learns the cap and splits; the next pass embeds every piece', async () => {
+ await seedPage('notes/overlength-cli');
+
+ const first = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(first.failures).toBe(1);
+ expect(embedBatchTexts).toContain(OVERSIZED);
+ await assertSplitAtLearnedCap('notes/overlength-cli');
+
+ embedBatchTexts = [];
+ const second = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(second.failures).toBe(0);
+ expect(second.embedded).toBeGreaterThanOrEqual(2);
+ expect(embedBatchTexts).not.toContain(OVERSIZED);
+ for (const t of embedBatchTexts) expect(estimateEmbedTokens(t)).toBeLessThanOrEqual(HIDDEN_LIMIT);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+ });
+
+ test('embedStaleForSource: same split through the shared drain', async () => {
+ await seedPage('notes/overlength-source');
+ const first = await embedStaleForSource(engine, 'default', { embedFn: async (texts) => fakeEmbed(texts) });
+ expect(first.failures).toBe(1);
+ await assertSplitAtLearnedCap('notes/overlength-source');
+
+ const second = await embedStaleForSource(engine, 'default', { embedFn: async (texts) => fakeEmbed(texts) });
+ expect(second.failures ?? 0).toBe(0);
+ expect(second.embedded).toBeGreaterThanOrEqual(2);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+ });
+
+ test('a later page in the same process is healed BEFORE its embed call at the learned cap (no second 400)', async () => {
+ await seedPage('notes/overlength-first');
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBe(EXPECTED_CAP);
+
+ await seedPage('notes/overlength-later');
+ embedBatchTexts = [];
+ const result = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(result.failures).toBe(0);
+ expect(embedBatchTexts).not.toContain(OVERSIZED);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+ });
+
+ test('an unrelated 400 never rewrites a chunk and learns nothing', async () => {
+ rejection = 'unrelated';
+ await seedPage('notes/overlength-unrelated');
+ const before = await engine.getChunks('notes/overlength-unrelated', { includeEmbedding: true });
+
+ const result = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(result.failures).toBe(1);
+ expect(result.failure_samples[0]).toContain('Incorrect API key');
+ const after = await engine.getChunks('notes/overlength-unrelated', { includeEmbedding: true });
+ expect(after.map(c => [c.id, c.chunk_index, c.chunk_text, c.embedding_is_null]))
+ .toEqual(before.map(c => [c.id, c.chunk_index, c.chunk_text, c.embedding_is_null]));
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBeUndefined();
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ });
+});
diff --git a/test/embed-overlength-heal.test.ts b/test/embed-overlength-heal.test.ts
new file mode 100644
index 0000000000..f8348a97c8
--- /dev/null
+++ b/test/embed-overlength-heal.test.ts
@@ -0,0 +1,246 @@
+/**
+ * PR #5347 takeover ([R13]) — a chunk the embedder rejects as too long for a
+ * model that declares NO `max_input_tokens` must be split, not retried
+ * forever and not parked.
+ *
+ * Master's heal (`healOversizedPageChunks`) splits stored chunks to the
+ * ACTIVE model's cap, but with no declared cap that is the 2000-token
+ * default — the provider's 400 ("input length exceeds the context length")
+ * comes back on every sweep and the page never embeds. The fix derives a
+ * deterministic smaller cap from the failure (the limit the message names ×
+ * EMBED_INPUT_SAFETY, else half the largest failed text's estimate), learns
+ * it for the model for the rest of the process so later heals split the
+ * same way, runs the heal on that page at once, and stops after a finite
+ * number of attempts or below a minimum useful cap with an explicit terminal
+ * outcome. Unrelated 400s never rewrite a chunk.
+ */
+import { describe, test, expect, beforeAll, beforeEach, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import {
+ isSingleInputOverLengthError,
+ overLengthLimitFromMessage,
+ deriveOverLengthChunkCap,
+ healPageAfterOverLength,
+ describeOverLengthOutcome,
+ statusFromCause,
+ MIN_USEFUL_CHUNK_TOKENS,
+ MAX_OVERLENGTH_HEAL_ATTEMPTS,
+ _resetOverLengthHealForTest,
+} from '../src/core/embed-overlength-heal.ts';
+import {
+ resolveMaxChunkTokens,
+ learnedChunkCap,
+ _resetLearnedChunkCapsForTest,
+} from '../src/core/embedding-input-limit.ts';
+import { DEFAULT_MAX_CHUNK_TOKENS, estimateEmbedTokens } from '../src/core/chunkers/token-estimate.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/** A local recipe with no per-input declaration: the case this fix exists for. */
+const UNDECLARED_MODEL = 'ollama:nomic-embed-text';
+
+function http(status: number, message: string): Error & { status: number } {
+ return Object.assign(new Error(message), { status });
+}
+
+function fatParagraph(n: number): string {
+ const para =
+ 'The quarterly operating review covers hiring plans, infrastructure spend, customer renewals and the product roadmap for the next two quarters in considerable detail. ';
+ return Array.from({ length: n }, () => para).join('\n\n');
+}
+
+const withoutChunkTokenEnv = <T>(fn: () => T | Promise<T>) =>
+ withEnv({ GBRAIN_MAX_CHUNK_TOKENS: undefined }, fn);
+
+beforeEach(() => {
+ resetGateway();
+ _resetOverLengthHealForTest();
+ _resetLearnedChunkCapsForTest();
+ configureGateway({ embedding_model: UNDECLARED_MODEL, embedding_dimensions: 768, env: {} });
+});
+
+afterAll(() => {
+ resetGateway();
+ _resetOverLengthHealForTest();
+ _resetLearnedChunkCapsForTest();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });
+});
+
+describe('recognising a single-input over-length rejection', () => {
+ test('provider shapes seen in the field are recognised at 400/413/422', () => {
+ expect(isSingleInputOverLengthError(http(400, 'Input length 1460 exceeds maximum allowed token size 512'))).toBe(true);
+ expect(isSingleInputOverLengthError(http(400, 'input length exceeds the context length'))).toBe(true);
+ expect(isSingleInputOverLengthError(http(400, "This model's maximum context length is 8192 tokens, however you requested 9211 tokens (9211 in your prompt; 0 for the completion). Please reduce your prompt; or completion length."))).toBe(true);
+ expect(isSingleInputOverLengthError(http(400, 'Range of input length should be [1, 2048]'))).toBe(true);
+ expect(isSingleInputOverLengthError(http(413, 'Payload too large: text exceeds the model limit of 2048 tokens'))).toBe(true);
+ expect(isSingleInputOverLengthError(http(422, 'Input text is too long for this model'))).toBe(true);
+ });
+
+ test('the status is read through the cause chain, like the fan-out does', () => {
+ const wrapped = new Error('embed failed', { cause: http(400, 'input length exceeds the context length') });
+ expect(statusFromCause(wrapped)).toBe(400);
+ expect(isSingleInputOverLengthError(wrapped)).toBe(true);
+ });
+
+ test('batch-level token errors, other 400s, transport errors and rate limits are NOT over-length chunks', () => {
+ expect(isSingleInputOverLengthError(http(400, 'Too many tokens overall, split into more batches.'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(400, "Invalid 'input': maximum request size is 300000 tokens per request."))).toBe(false);
+ expect(isSingleInputOverLengthError(http(400, 'max allowed tokens per batch is 120000'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(400, 'Incorrect API key provided'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(400, 'model not found: nomic-embed-text'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(404, 'input length exceeds the context length'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(500, 'input length exceeds the context length'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(429, 'rate limit exceeded; token limit exceeded for the minute'))).toBe(false);
+ expect(isSingleInputOverLengthError(new Error('input length exceeds the context length'))).toBe(false);
+ expect(isSingleInputOverLengthError(null)).toBe(false);
+ });
+
+ test('the limit the message names is parsed; prose without a limit yields undefined', () => {
+ expect(overLengthLimitFromMessage('Input length 1460 exceeds maximum allowed token size 512')).toBe(512);
+ expect(overLengthLimitFromMessage("This model's maximum context length is 8192 tokens, however you requested 9211 tokens")).toBe(8192);
+ expect(overLengthLimitFromMessage('Range of input length should be [1, 2048]')).toBe(2048);
+ expect(overLengthLimitFromMessage('text exceeds the model limit of 2048 tokens')).toBe(2048);
+ expect(overLengthLimitFromMessage('input length exceeds the context length')).toBeUndefined();
+ });
+});
+
+describe('deriving a deterministic smaller cap', () => {
+ const texts = [fatParagraph(60), 'short'];
+ const largest = Math.max(...texts.map(estimateEmbedTokens));
+
+ test('a named limit gives floor(limit × 0.6); otherwise half the largest failed estimate', () => {
+ expect(deriveOverLengthChunkCap(http(400, 'Input length 1460 exceeds maximum allowed token size 512'), texts, DEFAULT_MAX_CHUNK_TOKENS)).toBe(307);
+ expect(deriveOverLengthChunkCap(http(400, 'input length exceeds the context length'), texts, DEFAULT_MAX_CHUNK_TOKENS)).toBe(Math.floor(largest / 2));
+ expect(deriveOverLengthChunkCap(http(400, 'input length exceeds the context length'), texts, DEFAULT_MAX_CHUNK_TOKENS))
+ .toBe(deriveOverLengthChunkCap(http(400, 'input length exceeds the context length'), texts, DEFAULT_MAX_CHUNK_TOKENS));
+ });
+
+ test('a cap that is not smaller than the current one, or below the useful minimum, is null (terminal)', () => {
+ expect(deriveOverLengthChunkCap(http(400, 'maximum context length is 8192 tokens'), texts, DEFAULT_MAX_CHUNK_TOKENS)).toBeNull();
+ expect(deriveOverLengthChunkCap(http(400, 'maximum context length is 100 tokens'), texts, DEFAULT_MAX_CHUNK_TOKENS)).toBeNull();
+ expect(deriveOverLengthChunkCap(http(400, 'input length exceeds the context length'), ['tiny'], DEFAULT_MAX_CHUNK_TOKENS)).toBeNull();
+ expect(MIN_USEFUL_CHUNK_TOKENS).toBeGreaterThanOrEqual(64);
+ expect(deriveOverLengthChunkCap(http(400, `maximum context length is ${Math.ceil(MIN_USEFUL_CHUNK_TOKENS / 0.6)} tokens`), texts, DEFAULT_MAX_CHUNK_TOKENS)).toBe(MIN_USEFUL_CHUNK_TOKENS);
+ });
+});
+
+describe('healPageAfterOverLength against a PGLite brain', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ async function seed(slug: string, body: string) {
+ await engine.putPage(slug, { type: 'note', title: 'Example', compiled_truth: body });
+ const prepared = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;
+ await installPageProjection(engine, prepared,
+ [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }], { seal: true });
+ return prepared.snapshot;
+ }
+
+ test('a recognised over-length 400 on an undeclared model learns the cap, splits the page now, and the pieces fit', async () => {
+ await withoutChunkTokenEnv(async () => {
+ const body = fatParagraph(40);
+ const snapshot = await seed('overlength-a', body);
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ const err = http(400, 'Input length 1460 exceeds maximum allowed token size 512');
+ const outcome = await healPageAfterOverLength(engine, 'overlength-a', 'default', err, [body]);
+ expect(outcome).toMatchObject({ kind: 'healed', cap: 307 });
+ expect(outcome.kind === 'healed' && outcome.splitCount).toBe(1);
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBe(307);
+ expect(resolveMaxChunkTokens()).toBe(307);
+ const chunks = await engine.getChunks('overlength-a');
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks) {
+ expect(estimateEmbedTokens(c.chunk_text)).toBeLessThanOrEqual(307);
+ expect(c.embedded_at).toBeNull();
+ }
+ expect(chunks.map(c => c.chunk_text).join('')).toContain('product roadmap');
+ expect((await engine.readPageSnapshot('overlength-a'))!.revision).toBe(snapshot.revision);
+ expect(describeOverLengthOutcome(outcome, 'overlength-a')).toContain('307');
+ });
+ });
+
+ test('without a named limit the cap halves deterministically per attempt and stops after the attempt budget', async () => {
+ await withoutChunkTokenEnv(async () => {
+ const body = fatParagraph(40);
+ await seed('overlength-b', body);
+ const err = http(400, 'input length exceeds the context length');
+ const caps: number[] = [];
+ let outcome = await healPageAfterOverLength(engine, 'overlength-b', 'default', err, [body]);
+ expect(outcome.kind).toBe('healed');
+ if (outcome.kind === 'healed') caps.push(outcome.cap);
+ for (let i = 1; i < MAX_OVERLENGTH_HEAL_ATTEMPTS; i++) {
+ const texts = (await engine.getChunks('overlength-b')).map(c => c.chunk_text);
+ outcome = await healPageAfterOverLength(engine, 'overlength-b', 'default', err, texts);
+ if (outcome.kind === 'healed') caps.push(outcome.cap);
+ else break;
+ }
+ for (let i = 1; i < caps.length; i++) expect(caps[i]!).toBeLessThan(caps[i - 1]!);
+ const texts = (await engine.getChunks('overlength-b')).map(c => c.chunk_text);
+ const after = await healPageAfterOverLength(engine, 'overlength-b', 'default', err, texts);
+ expect(after.kind).toBe('skipped');
+ if (after.kind === 'skipped') expect(['attempts_exhausted', 'cap_floor']).toContain(after.reason);
+ expect(describeOverLengthOutcome(after, 'overlength-b')).toContain('GBRAIN_MAX_CHUNK_TOKENS');
+ });
+ });
+
+ test('an unrelated 400, a 5xx and a batch-level token error never rewrite the page', async () => {
+ await withoutChunkTokenEnv(async () => {
+ const body = fatParagraph(40);
+ const snapshot = await seed('overlength-c', body);
+ const before = await engine.getChunks('overlength-c');
+ for (const err of [
+ http(400, 'Incorrect API key provided'),
+ http(500, 'input length exceeds the context length'),
+ http(400, 'Too many tokens overall, split into more batches.'),
+ new Error('socket hang up'),
+ ]) {
+ const outcome = await healPageAfterOverLength(engine, 'overlength-c', 'default', err, [body]);
+ expect(outcome).toEqual({ kind: 'skipped', reason: 'not_overlength' });
+ expect(describeOverLengthOutcome(outcome, 'overlength-c')).toBeNull();
+ }
+ const after = await engine.getChunks('overlength-c');
+ expect(after.map(c => [c.id, c.chunk_text])).toEqual(before.map(c => [c.id, c.chunk_text]));
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBeUndefined();
+ expect((await engine.readPageSnapshot('overlength-c'))!.revision).toBe(snapshot.revision);
+ });
+ });
+
+ test('a model with a declared cap, or an operator GBRAIN_MAX_CHUNK_TOKENS, is terminal: the declaration is the thing to fix', async () => {
+ const body = fatParagraph(40);
+ await seed('overlength-d', body);
+ const err = http(400, 'Input length 1460 exceeds maximum allowed token size 512');
+ configureGateway({ embedding_model: 'nvidia:nvidia/nv-embedqa-e5-v5', embedding_dimensions: 1024, env: { NVIDIA_API_KEY: 'k' } });
+ await withoutChunkTokenEnv(async () => {
+ const declared = await healPageAfterOverLength(engine, 'overlength-d', 'default', err, [body]);
+ expect(declared).toEqual({ kind: 'skipped', reason: 'declared_cap' });
+ expect(describeOverLengthOutcome(declared, 'overlength-d')).toContain('max_input_tokens');
+ });
+ configureGateway({ embedding_model: UNDECLARED_MODEL, embedding_dimensions: 768, env: {} });
+ await withEnv({ GBRAIN_MAX_CHUNK_TOKENS: '1500' }, async () => {
+ const pinned = await healPageAfterOverLength(engine, 'overlength-d', 'default', err, [body]);
+ expect(pinned).toEqual({ kind: 'skipped', reason: 'declared_cap' });
+ });
+ expect((await engine.getChunks('overlength-d')).map(c => c.chunk_text)).toEqual([body]);
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBeUndefined();
+ });
+
+ test('a learned cap is per model and cleared by the test seam', async () => {
+ await withoutChunkTokenEnv(async () => {
+ const body = fatParagraph(40);
+ await seed('overlength-e', body);
+ await healPageAfterOverLength(engine, 'overlength-e', 'default', http(400, 'maximum context length is 1024 tokens'), [body]);
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBe(614);
+ expect(learnedChunkCap('ollama:other-model')).toBeUndefined();
+ configureGateway({ embedding_model: 'ollama:other-model', embedding_dimensions: 768, env: {} });
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ _resetLearnedChunkCapsForTest();
+ expect(learnedChunkCap(UNDECLARED_MODEL)).toBeUndefined();
+ });
+ });
+});
diff --git a/test/embedding-input-limit-hosted-caps.test.ts b/test/embedding-input-limit-hosted-caps.test.ts
new file mode 100644
index 0000000000..e5413839fb
--- /dev/null
+++ b/test/embedding-input-limit-hosted-caps.test.ts
@@ -0,0 +1,120 @@
+/**
+ * PR #5922 takeover (#4530 follow-up) — hosted encoders declare their
+ * per-INPUT token caps so the chunker splits to a size the model accepts.
+ *
+ * DashScope rejects any single input over 2,048 tokens on text-embedding-v1
+ * / v2 (8,192 on v3 / v4) with a 400 that fails the whole batch; master
+ * declared nothing, so its cap was unenforced. The same audit found Google
+ * gemini-embedding-001 (2,048; silently TRUNCATES over the cap by default,
+ * which is a lossy vector, not an error) and Zhipu embedding-2 / embedding-3
+ * (512 / 3,072). Each figure is the vendor's documented per-input limit.
+ *
+ * The chunk cap is floor(limit × EMBED_INPUT_SAFETY), never above
+ * DEFAULT_MAX_CHUNK_TOKENS (so an 8K+ limit changes nothing).
+ */
+import { describe, test, expect, beforeEach, afterAll } from 'bun:test';
+import {
+ resolveMaxChunkTokens,
+ maxInputTokensForModel,
+ EMBED_INPUT_SAFETY,
+} from '../src/core/embedding-input-limit.ts';
+import { DEFAULT_MAX_CHUNK_TOKENS } from '../src/core/chunkers/token-estimate.ts';
+import { estimateEmbedTokens } from '../src/core/chunkers/token-estimate.ts';
+import { healOversizedChunks } from '../src/core/embed-oversize-heal.ts';
+import { dashscope } from '../src/core/ai/recipes/dashscope.ts';
+import { google } from '../src/core/ai/recipes/google.ts';
+import { zhipu } from '../src/core/ai/recipes/zhipu.ts';
+import { openai } from '../src/core/ai/recipes/openai.ts';
+import { mistral } from '../src/core/ai/recipes/mistral.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const withoutChunkTokenEnv = <T>(fn: () => T | Promise<T>) =>
+ withEnv({ GBRAIN_MAX_CHUNK_TOKENS: undefined }, fn);
+
+beforeEach(() => resetGateway());
+afterAll(() => {
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });
+});
+
+const cap = (limit: number) => Math.min(DEFAULT_MAX_CHUNK_TOKENS, Math.floor(limit * EMBED_INPUT_SAFETY));
+
+describe('DashScope per-input caps (PR #5922)', () => {
+ test('the recipe declares 2048 for v1/v2 and 8192 for v3', () => {
+ expect(maxInputTokensForModel(dashscope, 'text-embedding-v1')).toBe(2048);
+ expect(maxInputTokensForModel(dashscope, 'text-embedding-v2')).toBe(2048);
+ expect(maxInputTokensForModel(dashscope, 'text-embedding-v3')).toBe(8192);
+ });
+
+ test('v2 chunks at 1228 estimated tokens; v3 keeps the 2000 default (8192 × 0.6 is above it)', async () => {
+ await withoutChunkTokenEnv(() => {
+ configureGateway({ embedding_model: 'dashscope:text-embedding-v2', embedding_dimensions: 1024, env: { DASHSCOPE_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(1228);
+ expect(resolveMaxChunkTokens()).toBe(cap(2048));
+ configureGateway({ embedding_model: 'dashscope:text-embedding-v3', embedding_dimensions: 1024, env: { DASHSCOPE_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ });
+ });
+
+ test('a stored CJK-dense chunk over the v2 cap is split by the heal pass, never truncated', async () => {
+ await withoutChunkTokenEnv(() => {
+ configureGateway({ embedding_model: 'dashscope:text-embedding-v2', embedding_dimensions: 1024, env: { DASHSCOPE_API_KEY: 'k' } });
+ const sentence = '阿里云百炼平台提供多种文本向量模型,用于检索、聚类和分类任务,支持中英文混合输入。';
+ const text = Array.from({ length: 30 }, (_, i) => `${sentence} 第${i}段。`).join('\n\n');
+ // Between the v2 cap and the 2000 default: only the declaration makes this split.
+ expect(estimateEmbedTokens(text)).toBeGreaterThan(resolveMaxChunkTokens());
+ expect(estimateEmbedTokens(text)).toBeLessThan(DEFAULT_MAX_CHUNK_TOKENS);
+ const healed = healOversizedChunks([{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 0 }]);
+ expect(healed.changed).toBe(true);
+ expect(healed.chunks.length).toBeGreaterThan(1);
+ for (const c of healed.chunks) expect(estimateEmbedTokens(c.chunk_text)).toBeLessThanOrEqual(resolveMaxChunkTokens());
+ expect(healed.chunks.map(c => c.chunk_text).join('')).toContain('第29段');
+ });
+ });
+});
+
+describe('hosted encoder audit ([R13])', () => {
+ test('Google gemini-embedding-001 declares 2048 (the endpoint silently truncates past it); gemini-embedding-2 stays undeclared', () => {
+ expect(maxInputTokensForModel(google, 'gemini-embedding-001')).toBe(2048);
+ expect(maxInputTokensForModel(google, 'gemini-embedding-2')).toBeUndefined();
+ });
+
+ test('Zhipu embedding-2 declares 512 and embedding-3 declares 3072', () => {
+ expect(maxInputTokensForModel(zhipu, 'embedding-2')).toBe(512);
+ expect(maxInputTokensForModel(zhipu, 'embedding-3')).toBe(3072);
+ });
+
+ test('OpenAI (8191) and Mistral (8192) declare caps above the default chunk size, so their chunking is unchanged', async () => {
+ expect(maxInputTokensForModel(openai, 'text-embedding-3-large')).toBe(8191);
+ expect(maxInputTokensForModel(openai, 'text-embedding-3-small')).toBe(8191);
+ expect(maxInputTokensForModel(mistral, 'mistral-embed')).toBe(8192);
+ await withoutChunkTokenEnv(() => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ configureGateway({ embedding_model: 'mistral:mistral-embed', embedding_dimensions: 1024, env: { MISTRAL_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);
+ });
+ });
+
+ test('effective chunk caps for the models whose chunking changes', async () => {
+ await withoutChunkTokenEnv(() => {
+ configureGateway({ embedding_model: 'google:gemini-embedding-001', embedding_dimensions: 768, env: { GOOGLE_GENERATIVE_AI_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(1228);
+ configureGateway({ embedding_model: 'zhipu:embedding-2', embedding_dimensions: 1024, env: { ZHIPUAI_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(307);
+ configureGateway({ embedding_model: 'zhipu:embedding-3', embedding_dimensions: 1024, env: { ZHIPUAI_API_KEY: 'k' } });
+ expect(resolveMaxChunkTokens()).toBe(1843);
+ });
+ });
+
+ test('every declared cap is a positive integer keyed by a model the recipe lists', () => {
+ for (const recipe of [dashscope, google, zhipu, openai, mistral]) {
+ const table = recipe.touchpoints.embedding!.max_input_tokens!;
+ for (const [model, limit] of Object.entries(table)) {
+ expect(Number.isInteger(limit) && limit > 0).toBe(true);
+ expect(recipe.touchpoints.embedding!.models).toContain(model);
+ }
+ }
+ });
+});