rerank() can return undefined documents for invalid provider ranking indices
Description
rerank() maps every provider-returned ranking[i].index straight back onto the
input documents array with a bare documents[index] lookup, and never validates
the index. The public result contract is non-optional:
// RerankResult<VALUE>
ranking: Array<{ originalIndex: number; score: number; document: VALUE }>;
rerankedDocuments: Array<VALUE>;
@ai-sdk/provider documents RerankingModelV4Result.ranking[].index as "the index
of the document in the original list of documents before reranking".
When a reranking model returns an index that is out of range or non-integer,
rerank() resolves successfully with document: undefined in ranking and
undefined entries in rerankedDocuments — no error, no retry, and the onEnd /
telemetry end event fires as if the call succeeded. The undefined then tends to
surface later as a TypeError far from the cause.
This is the same shape as #20355 (embed() resolves with an undefined embedding)
and #20351 (empty choices[]): a structurally valid but semantically invalid
successful provider response passed through as a value that violates the SDK's own
result type.
Actual behavior
documents = ['a', 'b', 'c'], one ranking entry, default maxRetries:
provider index |
outcome | ranking[0].document |
rerankedDocuments |
doRerank calls |
onEnd fired |
|---|---|---|---|---|---|
3 (=== length) |
resolves | undefined |
[undefined] |
1 | yes |
-1 |
resolves | undefined |
[undefined] |
1 | yes |
5 (> length) |
resolves | undefined |
[undefined] |
1 | yes |
1.5 |
resolves | undefined |
[undefined] |
1 | yes |
The malformed response is not retried (the provider is called once), so this is deterministic rather than a transient failure.
Expected behavior
An invalid provider ranking index should not produce a successful RerankResult
containing undefined documents. Adjacent malformed-successful-response handling
in the same package surfaces this as InvalidResponseDataError
(embed-many.ts validateEmbeddingCount; #20358 / #20362) — but the exact error
type and whether the check belongs inside or outside the retry callback are for
maintainers to decide.
Control (unchanged, valid input)
ranking indices [2, 0] -> rerankedDocuments ['c', 'a']
Valid in-range rankings continue to work as before.
Source pointers (main @ c3c189c068baefe62808b4eca5432fe092dc37cb)
packages/ai/src/rerank/rerank.ts—document: documents[ranking.index]in both theonEndevent payload and theDefaultRerankResultconstruction (both afterretry()resolves); noNumber.isInteger/0 <= index < documents.lengthcheck.packages/ai/src/rerank/rerank-result.ts—ranking[].document: VALUE,rerankedDocuments: Array<VALUE>.packages/provider/src/reranking-model/v4/reranking-model-v4-result.ts—indexsemantics.
I searched issues, PRs, and recent commits (rerank invalid index,
rerank out of range, rerank undefined document, ranking index validation,
InvalidResponseDataError rerank) and found nothing covering rerank index
validation.
Reproduction
Minimal, using the public API and the shipped mock (ai @ main,
c3c189c068baefe62808b4eca5432fe092dc37cb — current main at the time of
reproduction):
import { rerank } from 'ai';
import { MockRerankingModelV4 } from 'ai/test';
const result = await rerank({
model: new MockRerankingModelV4({
// documents.length === 3, so index 3 is out of range
doRerank: async () => ({ ranking: [{ index: 3, relevanceScore: 0.9 }] }),
}),
documents: ['a', 'b', 'c'],
query: 'q',
});
console.log(result.ranking[0].document); // => undefined
console.log(result.rerankedDocuments); // => [ undefined ]
As a failing test in packages/ai/src/rerank/:
import { expect, it } from 'vitest';
import { MockRerankingModelV4 } from '../test/mock-reranking-model-v4';
import { rerank } from './rerank';
it('does not resolve with an undefined document for an out-of-range index', async () => {
const model = new MockRerankingModelV4({
doRerank: async () => ({ ranking: [{ index: 3, relevanceScore: 0.9 }] }),
});
await expect(
rerank({ model, documents: ['a', 'b', 'c'], query: 'q' }),
).rejects.toThrow();
});
On current main this test fails: rerank() resolves with
DefaultRerankResult { ranking: [{ document: undefined, originalIndex: 3, score: 0.9 }] }.
AI SDK Version
ai:main@c3c189c068baefe62808b4eca5432fe092dc37cb(also reproduces on published[email protected])- Node: v22.13+
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Identify issue type
Identified as Bug
Confidence: High
Rationale
This is a concrete failure in existing SDK behavior: malformed provider indices produce successful results that violate the documented result type instead of raising an error.
Evidence
rerank()accepts out-of-range, negative, and non-integer provider ranking indices without validation.- Invalid indices resolve successfully with
undefineddocuments despite the publicRerankResultcontract declaring non-optionalVALUEentries. - A minimal reproduction and failing test demonstrate the behavior on current
mainand published[email protected].
Bug Reproduction - AI SDK 7
Bug was reproduced.
Branch: main
PR: successful reproduction pull request
Details
- On
mainatc3c189c068baefe62808b4eca5432fe092dc37cb,packages/ai/src/rerank/rerank.tsmaps provider indices through unvalidateddocuments[index]lookups despite the non-optional result contract. - Reproduction artifact
examples/ai-functions/src/reproduction/rerank-invalid-provider-indices.tsshowed indices3,-1,5, and1.5all resolving withundefinedinranking,rerankedDocuments, and theonEndpayload. - Each malformed case called
doRerankonce and firedonEndonce as a successful operation; invalid indices were expected not to expose successful results or end events containing undefined documents. - The valid control ranking
[2, 0]continued to produce['c', 'a'].
Bugfix - AI SDK 7
Created bugfix and opened PR: #20423
Root Cause
rerank() mapped provider indices through unchecked documents[index] lookups after the provider call. The reproduction confirmed that out-of-range, negative, and fractional indices all produced undefined documents.
Summary
Validated provider ranking indices as in-range integers and now throw InvalidResponseDataError before constructing results or firing onEnd. Added a patch changeset and removed reproduction-only artifacts.
Testing
Added regression coverage for out-of-range, negative, and fractional indices, verifying rejection, a single provider call, and no onEnd callback.
Bug Reproduction - AI SDK 5
Issue report appears invalid.
Target branch: release-v5.0
- The reported primary failure cannot occur on the target branch because no
rerank()API orRerankResultcan be constructed there. - The invalid assumption is that issue #20421's AI SDK 7
rerank()andMockRerankingModelV4APIs exist onrelease-v5.0. packages/ai/package.jsonidentifies the target as[email protected];packages/ai/src/index.tshas no rerank export, andpackages/ai/test/index.tshas no reranking mock export.packages/provider/package.jsonidentifies@ai-sdk/[email protected], whilepackages/provider/src/index.tsexposes V2 model families and no reranking model contract.content/docs/01-announcing-ai-sdk-6-beta/index.mdxexplicitly states that AI SDK 6 introduces native reranking support, confirming it is unavailable in AI SDK 5.
Relevant Documentation
- https://ai-sdk.dev/v5/docs/reference/ai-sdk-core
- https://ai-sdk.dev/docs/reference/ai-sdk-core/rerank
Bug Reproduction - AI SDK 6
Bug was reproduced.
Branch: release-v6.0
PR: successful reproduction pull request
Details
- On
release-v6.0,packages/ai/src/rerank/rerank.tsmaps provider indices through an uncheckeddocuments[ranking.index]lookup despite the non-optional result contract inpackages/ai/src/rerank/rerank-result.ts. - Reproduction artifact
examples/ai-functions/src/reproduction/issue-20421-rerank-invalid-provider-indices.tsshowed indices3,-1,5, and1.5each resolving with one undefined ranking document and one undefined reranked document. - Every malformed case called
doRerankexactly once with default retry settings, confirming the malformed successful response was not retried. - The valid control indices
[2, 0]returned['c', 'a']and called the provider once. - This branch uses
RerankingModelV3, whose index semantics match the reported V4 contract; the V6rerank()API does not expose the report's V7-specificonEndcallback.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-core/rerank
:rocket: Published in:
| Package | Version |
|---|---|
ai |
7.0.98 github npm |
@ai-sdk/alibaba |
2.0.45 github npm |
@ai-sdk/amazon-bedrock |
5.0.82 github npm |
@ai-sdk/angular |
3.0.98 github npm |
@ai-sdk/anthropic |
4.0.53 github npm |
@ai-sdk/anthropic-aws |
2.0.45 github npm |
@ai-sdk/assemblyai |
3.0.40 github npm |
@ai-sdk/azure |
4.0.69 github npm |
@ai-sdk/baseten |
2.1.26 github npm |
@ai-sdk/black-forest-labs |
2.0.41 github npm |
@ai-sdk/bytedance |
2.0.43 github npm |
@ai-sdk/cartesia |
3.0.35 github npm |
@ai-sdk/cerebras |
3.0.48 github npm |
@ai-sdk/code-mode |
1.0.55 github npm |
@ai-sdk/cohere |
4.0.41 github npm |
@ai-sdk/deepgram |
3.1.11 github npm |
@ai-sdk/deepinfra |
3.0.48 github npm |
@ai-sdk/deepseek |
3.0.43 github npm |
@ai-sdk/devtools |
1.0.19 github npm |
@ai-sdk/elevenlabs |
3.0.41 github npm |
@ai-sdk/fal |
3.0.41 github npm |
@ai-sdk/fireworks |
3.0.51 github npm |
@ai-sdk/fish-audio |
3.0.18 github npm |
@ai-sdk/gateway |
4.0.79 github npm |
@ai-sdk/gladia |
3.0.40 github npm |
@ai-sdk/gmicloud |
3.0.19 github npm |
@ai-sdk/google |
4.0.68 github npm |
@ai-sdk/google-vertex |
5.0.80 github npm |
@ai-sdk/groq |
4.0.41 github npm |
@ai-sdk/harness |
1.0.108 github npm |
@ai-sdk/harness-acp |
1.0.46 github npm |
@ai-sdk/harness-claude-code |
1.0.112 github npm |
@ai-sdk/harness-cline |
1.0.35 github npm |
@ai-sdk/harness-codex |
1.0.110 github npm |
@ai-sdk/harness-cursor |
1.0.21 github npm |
@ai-sdk/harness-deepagents |
1.0.108 github npm |
@ai-sdk/harness-fx |
1.0.21 github npm |
@ai-sdk/harness-github-copilot |
1.0.3 github npm |
@ai-sdk/harness-grok-build |
1.0.45 github npm |
@ai-sdk/harness-opencode |
1.0.110 github npm |
@ai-sdk/harness-pi |
1.0.110 github npm |
@ai-sdk/huggingface |
2.0.48 github npm |
@ai-sdk/hume |
3.0.40 github npm |
@ai-sdk/klingai |
4.0.42 github npm |
@ai-sdk/langchain |
3.0.98 github npm |
@ai-sdk/llamaindex |
3.0.98 github npm |
@ai-sdk/luma |
3.0.41 github npm |
@ai-sdk/mcp |
2.0.49 github npm |
@ai-sdk/minimax |
3.0.30 github npm |
@ai-sdk/mistral |
4.0.43 github npm |
@ai-sdk/moonshotai |
3.0.49 github npm |
@ai-sdk/open-responses |
2.0.44 github npm |
@ai-sdk/openai |
4.0.66 github npm |
@ai-sdk/openai-compatible |
3.0.48 github npm |
@ai-sdk/otel |
1.0.98 github npm |
@ai-sdk/perplexity |
4.0.43 github npm |
@ai-sdk/policy-opa |
1.0.98 github npm |
@ai-sdk/prodia |
2.0.41 github npm |
@ai-sdk/provider |
4.0.14 github npm |
@ai-sdk/provider-utils |
5.0.40 github npm |
@ai-sdk/quiverai |
2.0.40 github npm |
@ai-sdk/react |
4.0.101 github npm |
@ai-sdk/replicate |
3.0.41 github npm |
@ai-sdk/revai |
3.0.40 github npm |
@ai-sdk/rsc |
3.0.98 github npm |
@ai-sdk/sandbox-just-bash |
1.0.108 github npm |
@ai-sdk/sandbox-vercel |
1.0.108 github npm |
@ai-sdk/svelte |
5.0.98 github npm |
@ai-sdk/togetherai |
3.0.49 github npm |
@ai-sdk/tui |
1.0.99 github npm |
@ai-sdk/valibot |
3.0.40 github npm |
@ai-sdk/voyage |
2.0.40 github npm |
@ai-sdk/vue |
4.0.98 github npm |
@ai-sdk/workflow |
2.0.29 github npm |
@ai-sdk/workflow-harness |
1.0.108 github npm |
@ai-sdk/xai |
4.0.58 github npm |
@ai-sdk/zai |
3.0.10 github npm |
Backport to v6.0
created: #20725 (fixed merge).