Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): stop retrying a single-input context overflow reported as 5xx (#6772)

garrytanab072df0c193
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 5791a54b63..9f40df3fba 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -35,7 +35,7 @@ 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/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/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` (lives in `src/core/embed-overlength-classify.ts`, re-exported here: status 400/413/422 with one of the field-seen message shapes, or #6772 a 5xx or statusless error whose message names a token or context limit, such as llama.cpp's "larger than the max context size" and Ollama's 500 "input length exceeds the context length"; never a batch-shaped message or the gateway's `isTokenLimitError`; `isEmbedRetriableError`, `isTransientNetworkEmbedError` and `embedPageTexts`' no-fan-out rule all exempt it, so the bad chunk is isolated instead of retried; tests `test/embed-overlength-classification.test.ts`, `test/embed-partial-failure-3037.serial.test.ts`), `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.
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 00b79660f7..9ec41f4f5d 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -16,7 +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 { healAndReportOverLength, isSingleInputOverLengthError, statusFromCause } from '../core/embed-overlength-heal.ts';
import {
createEmbedStallWatchdog,
resolveEmbedStallAbortSeconds,
@@ -2279,7 +2279,7 @@ async function embedPageTexts(
if (texts.length <= 1) throw e; // nothing to isolate
// #3374 — network-transient exhaustion isn't chunk-specific either:
// fanning out during an outage multiplies failing calls per page.
- if (isEmbedRetriableError(e) || isTransientNetworkEmbedError(e) || e instanceof AITransientError) throw e;
+ if (!isSingleInputOverLengthError(e) && (isEmbedRetriableError(e) || isTransientNetworkEmbedError(e) || e instanceof AITransientError)) throw e;
const status = statusFromCause(e);
if (status === 401 || status === 403) throw e;
diff --git a/src/core/embed-overlength-classify.ts b/src/core/embed-overlength-classify.ts
new file mode 100644
index 0000000000..5fb100967d
--- /dev/null
+++ b/src/core/embed-overlength-classify.ts
@@ -0,0 +1,81 @@
+/**
+ * Single-input over-length classification, shared by the embed retry loop
+ * (`embed-retry.ts`), the per-chunk fan-out (`embedPageTexts`) and the heal
+ * (`embed-overlength-heal.ts`). Pure; imports nothing that imports the retry
+ * loop.
+ *
+ * A 400/413/422 counts when its message has one of the over-length shapes. A
+ * 5xx or statusless error (#6772: llama.cpp's server answers 500 "input (N
+ * tokens) is larger than the max context size", Ollama 500 "input length
+ * exceeds the context length") counts only on explicit token or
+ * context-length wording, because 5xx bodies such as "The input queue is too
+ * long" or "exceeds maximum concurrent connection limit" are transient.
+ * Batch-level token errors (the gateway's `isTokenLimitError`, or any message
+ * about the batch or request as a whole) never count: shrinking the batch,
+ * not the chunk, is their fix.
+ */
+
+import { isTokenLimitError } from './ai/gateway.ts';
+
+/** 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,
+];
+
+/** #6772: the subset that names a token or context limit, the only wording trusted behind a 5xx or no status. */
+const EXPLICIT_OVER_LENGTH_PATTERNS: readonly RegExp[] = [
+ // llama.cpp server: "input (1234 tokens) is larger than the max context size (512 tokens)"
+ /larger\s+than\s+the\s+max(?:imum)?\s+context\s+size/i,
+ /max(?:imum)?\s+context\s+length\s+is\s+\d+/i,
+ // Ollama "input length exceeds the context length"; NIM "exceeds maximum allowed token size 512"
+ /exceeds?\s+(?:the\s+)?(?:model'?s\s+)?(?:max(?:imum)?\s+)?(?:allowed\s+)?(?:input\s+)?(?:context\s+(?:length|size|window)|token\s+(?:size|limit|count))/i,
+ // "the input of 9000 tokens exceeds the maximum of 8192"
+ /\b\d+\s+tokens?\b[^.\n]{0,60}\b(?:exceeds?|larger\s+than|greater\s+than|more\s+than)\b[^.\n]{0,40}\b(?:max(?:imum)?|limit|context)\b/i,
+];
+
+const BATCH_SHAPED = /\b(?:batch|per\s+request|overall|request\s+size)\b/i;
+
+/** Every message on the cause chain, joined. */
+export function overLengthMessage(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 rejection whose message says ONE input is over the model's limit. */
+export function isSingleInputOverLengthError(e: unknown): boolean {
+ const status = statusFromCause(e);
+ const requestShaped = status !== undefined && OVER_LENGTH_STATUSES.has(status);
+ if (!requestShaped && status !== undefined && status < 500) return false;
+ if (isTokenLimitError(e)) return false;
+ const msg = overLengthMessage(e);
+ if (BATCH_SHAPED.test(msg)) return false;
+ return (requestShaped ? OVER_LENGTH_PATTERNS : EXPLICIT_OVER_LENGTH_PATTERNS).some((re) => re.test(msg));
+}
diff --git a/src/core/embed-overlength-heal.ts b/src/core/embed-overlength-heal.ts
index 010c0740d5..a01ce9f390 100644
--- a/src/core/embed-overlength-heal.ts
+++ b/src/core/embed-overlength-heal.ts
@@ -10,9 +10,11 @@
* 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);
+ * 1. recognise a single-input over-length rejection
+ * (`embed-overlength-classify.ts`: 400/413/422 with an over-length
+ * message, or a 5xx/statusless error naming a token or context limit;
+ * 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
@@ -27,7 +29,8 @@
*/
import { estimateEmbedTokens } from './chunkers/token-estimate.ts';
-import { getEmbeddingModel, isTokenLimitError } from './ai/gateway.ts';
+import { getEmbeddingModel } from './ai/gateway.ts';
+import { isSingleInputOverLengthError, overLengthMessage } from './embed-overlength-classify.ts';
import { resolveRecipe } from './ai/model-resolver.ts';
import {
EMBED_INPUT_SAFETY,
@@ -47,60 +50,7 @@ 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));
-}
+export { statusFromCause, isSingleInputOverLengthError } from './embed-overlength-classify.ts';
/** The token limit an over-length message names, when it names one. */
export function overLengthLimitFromMessage(msg: string): number | undefined {
@@ -121,7 +71,7 @@ export function overLengthLimitFromMessage(msg: string): number | undefined {
* 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 named = overLengthLimitFromMessage(overLengthMessage(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;
diff --git a/src/core/embed-retry.ts b/src/core/embed-retry.ts
index 3e81f3973d..da2ffdd833 100644
--- a/src/core/embed-retry.ts
+++ b/src/core/embed-retry.ts
@@ -13,6 +13,7 @@
*/
import { embedBatch } from './embedding.ts';
+import { isSingleInputOverLengthError } from './embed-overlength-classify.ts';
import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';
import { serr } from './console-prefix.ts';
import { noteEmbedApiResponse } from './embed-stall.ts';
@@ -276,6 +277,7 @@ export async function embedBatchKeepingUsable(texts: string[], opts: EmbedBatchW
*/
export function isEmbedRetriableError(e: unknown): boolean {
if (isEmbeddingZeroNormError(e)) return false; // #4616: terminal per item, never retried
+ if (isSingleInputOverLengthError(e)) return false; // #6772: the same input fails again, even behind a 5xx
const msg = e instanceof Error ? e.message : String(e);
return (
detect429FromCause(e) ||
@@ -316,6 +318,7 @@ export function transientBackoffMs(attempt: number, rng: () => number = Math.ran
*/
export function isTransientNetworkEmbedError(e: unknown): boolean {
if (isEmbeddingZeroNormError(e)) return false;
+ if (isSingleInputOverLengthError(e)) return false;
const TRANSIENT_CODES = /^(DNS_ETIMEOUT|ETIMEOUT|ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|EPIPE|ECONNABORTED|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|UND_ERR_BODY_TIMEOUT|UND_ERR_SOCKET)$/;
let cur: unknown = e;
for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
diff --git a/test/embed-overlength-classification.test.ts b/test/embed-overlength-classification.test.ts
new file mode 100644
index 0000000000..5399355419
--- /dev/null
+++ b/test/embed-overlength-classification.test.ts
@@ -0,0 +1,61 @@
+/**
+ * #6772: some providers report a single input over the model's context with a
+ * 5xx or no HTTP status (llama.cpp's server answers 500 "input (N tokens) is
+ * larger than the max context size"; Ollama answers 500 "input length exceeds
+ * the context length"). Those were retried as transient and never isolated or
+ * healed. A 5xx or statusless error now counts as a single-input overflow only
+ * on explicit token or context-length wording; queue, connection and generic
+ * "too long" 5xx messages stay transient, and the gateway's batch-token guard
+ * still vetoes.
+ */
+import { describe, expect, test } from 'bun:test';
+import { isSingleInputOverLengthError } from '../src/core/embed-overlength-heal.ts';
+import { isEmbedRetriableError, isTransientNetworkEmbedError } from '../src/core/embed-retry.ts';
+import { AITransientError } from '../src/core/ai/errors.ts';
+
+const http = (status: number | undefined, message: string): Error => Object.assign(new Error(message), status === undefined ? {} : { status });
+const wrapped = (status: number | undefined, message: string): Error => new AITransientError('embedding request failed', http(status, message));
+
+const OVERFLOWS = [
+ 'input (1234 tokens) is larger than the max context size (512 tokens). skipping',
+ 'input length exceeds the context length',
+ "This model's maximum context length is 8192 tokens, however you requested 9211 tokens",
+ 'Input length 1460 exceeds maximum allowed token size 512',
+ 'the input of 9000 tokens exceeds the maximum of 8192',
+];
+
+describe('#6772 single-input overflow behind a 5xx or no status', () => {
+ test('explicit token or context-length wording is an overflow at 500/502/503/504 and with no status, and is never retried as transient', () => {
+ for (const message of OVERFLOWS) for (const status of [500, 502, 503, 504, undefined]) {
+ for (const error of [http(status, message), wrapped(status, message)]) {
+ expect([message, status, isSingleInputOverLengthError(error)]).toEqual([message, status, true]);
+ expect(isEmbedRetriableError(error)).toBe(false);
+ expect(isTransientNetworkEmbedError(error)).toBe(false);
+ }
+ }
+ });
+
+ test('queue, connection-limit, URL-length and generic too-long 5xx messages stay transient', () => {
+ for (const [status, message] of [
+ [503, 'The input queue is too long, try again later'],
+ [503, 'server exceeds maximum concurrent connection limit'],
+ [undefined, 'Request text too long for URL'],
+ [500, 'Input text is too long for this model'],
+ [503, 'service unavailable'],
+ [500, 'Internal server error'],
+ ] as const) {
+ expect([message, isSingleInputOverLengthError(http(status, message))]).toEqual([message, false]);
+ }
+ expect(isEmbedRetriableError(http(503, 'The input queue is too long, try again later'))).toBe(true);
+ expect(isEmbedRetriableError(http(503, 'server exceeds maximum concurrent connection limit'))).toBe(true);
+ });
+
+ test('batch-level token errors are vetoed at any status, and 4xx outside 400/413/422 never count', () => {
+ for (const status of [500, 503, undefined]) {
+ expect(isSingleInputOverLengthError(http(status, 'max allowed tokens per batch is 120000'))).toBe(false);
+ expect(isSingleInputOverLengthError(http(status, "Invalid 'input': maximum request size is 300000 tokens per request."))).toBe(false);
+ expect(isSingleInputOverLengthError(http(status, 'batch of 40000 tokens exceeds the maximum context length'))).toBe(false);
+ }
+ for (const status of [401, 403, 404, 429]) expect(isSingleInputOverLengthError(http(status, OVERFLOWS[0]!))).toBe(false);
+ });
+});
diff --git a/test/embed-overlength-heal.test.ts b/test/embed-overlength-heal.test.ts
index f8348a97c8..bf0533b3b6 100644
--- a/test/embed-overlength-heal.test.ts
+++ b/test/embed-overlength-heal.test.ts
@@ -90,9 +90,9 @@ describe('recognising a single-input over-length rejection', () => {
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(500, 'Input text is too long for this model'))).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(new Error('Request text too long for URL'))).toBe(false);
expect(isSingleInputOverLengthError(null)).toBe(false);
});
@@ -189,14 +189,15 @@ describe('healPageAfterOverLength against a PGLite brain', () => {
});
});
- test('an unrelated 400, a 5xx and a batch-level token error never rewrite the page', async () => {
+ test('an unrelated 400, a transient 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(500, 'Internal server error'),
+ http(503, 'The input queue is too long, try again later'),
http(400, 'Too many tokens overall, split into more batches.'),
new Error('socket hang up'),
]) {
diff --git a/test/embed-partial-failure-3037.serial.test.ts b/test/embed-partial-failure-3037.serial.test.ts
index 251b2acb31..cba9b91f73 100644
--- a/test/embed-partial-failure-3037.serial.test.ts
+++ b/test/embed-partial-failure-3037.serial.test.ts
@@ -114,6 +114,23 @@ describe('#3037 — one bad chunk no longer darkens its page', () => {
expect(stamps).toHaveLength(0);
});
+ test('#6772: a context overflow reported as a 500 is isolated: siblings embed, only the bad chunk fails', async () => {
+ embedBatchBehavior = async (texts: string[]) => {
+ if (texts.length > 1 || texts[0] === 'BAD') throw new AITransientError('embedding request failed', Object.assign(new Error('input (1234 tokens) is larger than the max context size (512 tokens)'), { status: 500 }));
+ return texts.map(() => new Float32Array(1536));
+ };
+ const stale = THREE_CHUNKS.map(c => ({
+ slug: 'overflow-500-page', chunk_index: c.chunk_index, chunk_text: c.chunk_text,
+ chunk_source: c.chunk_source, model: null, token_count: 1, source_id: 'default', page_id: 1,
+ }));
+ const engine = mockEngine({ countStaleChunks: async () => 3, listStaleChunks: async () => stale, getChunks: async () => THREE_CHUNKS, upsertChunks: async () => {} });
+ const result = await runEmbedCore(engine, { stale: true });
+ expect(embedCalls.map(c => c.length)).toEqual([3, 1, 1, 1]);
+ expect(result.embedded).toBe(2);
+ expect(result.failures).toBe(1);
+ expect(embeddingUpdates(engine)).toHaveLength(2);
+ });
+
test('--all: same isolation on the listPages path', async () => {
oneBadChunkBehavior();
const engine = mockEngine({