The reranker has answered. Your application now holds this reduced response fixture:

{"results": [
  {"index": 2, "relevance_score": 0.91},
  {"index": 1, "relevance_score": 0.89},
  {"index": 0, "relevance_score": 0.24}
]}

These scores and their order are invented for an offline example. They are not measurements of Qwen's ranking quality. The important question is already concrete: which original source should the first result open?

The answer is the candidate submitted at position two. It is not the first retrieved document, the document with database ID two, or whichever document happens to contain matching text. QwenCloud's compatible reranking reference defines index as the original position in documents; the response array is ranked by descending relevance. Those are two different coordinates. Confusing them can produce a convincing answer whose source link opens an unrelated passage.

Read the response backward to its source

Imagine a support search for “How do I reset?” The exact submitted candidate snapshot contained these four entries. Positions are zero based; the source labels and product instructions are fictional.

Input indexStable source IDChunkRevisionSubmitted text
0manualopeningr4Start the console.
1faqresetr7Hold Reset for ten seconds.
2manualresetr4Hold Reset for ten seconds.
3manualnetworkr4Check the network cable.

Reading the response from top to bottom produces manual/reset/r4, then faq/reset/r7, then manual/opening/r4. The fourth submitted candidate did not appear because this request asked for three results. Its absence is not an extraction failure, deletion instruction, or evidence that the document does not exist.

Notice the identical text at positions one and two. A lookup such as documents.index(returned_text) would always choose the first match. It would silently attach the FAQ identity to the manual result. Matching by text also fails when a source is normalized, shortened for display, or later edited. The returned position resolves an occurrence in one request; your retained metadata resolves its source.

Carry all three identities into the application: presentation rank, request-local input index, and durable source identity. The first answers “Where should this appear?” The second answers “Which submitted candidate was scored?” The third answers “Which source revision can a person inspect?” A single field named id obscures these different jobs. This distinction also prepares the evidence for native citation rendering, where preserving a valid source reference remains separate from checking whether the generated claim is supported.

Before there was an index, there was an authorized candidate list

Work backward one more stage. The retriever initially found six rows: the four shown above, a private exception document, and a second retrieval hit for the same FAQ chunk. The private row must be removed before its text enters the rerank request. Filtering it after scoring cannot undo disclosure to the model endpoint, request logs, or a downstream trace that captured the payload.

Authorization is an application decision using the current user, tenant, source policy, and intended processing destination. A relevance model cannot establish those permissions. OWASP's authorization guidance recommends permission checks on every request and default denial. Applied here, that means the application first determines which source contents it may process, then constructs the reranking candidates from that permitted set. An allowlist supplied directly by the browser would not be a trusted authorization decision.

The repeated FAQ hit is a different problem. If both hits identify the same source, chunk, and revision, removing the repeat before submission avoids spending two candidate positions on the same evidence. If two different sources contain the same sentence, preserve both unless the product has an explicit rule for merging equivalent sources. Their ownership, effective dates, surrounding exceptions, and links can differ. Text equality alone does not establish interchangeable evidence.

Filtering and ranking therefore operate on different questions. Filtering decides whether an item is eligible: authorized, applicable to the selected product, in the requested language, or within an effective date. Ranking decides which eligible text best serves the query. If a mandatory rule is available as reliable metadata, enforce it before ranking. Asking the reranker to “prefer permitted documents” makes a permission requirement dependent on a relevance judgment.

When no candidates survive, return a clear no-source state without calling the model. When access changes during an in-flight request, recheck permission before displaying evidence. That second check protects delivery; it does not replace the first check before external processing. If your text came from file extraction, verify that the chunk actually represents the source before freezing it; the Kimi extraction acceptance article examines that earlier boundary.

Freeze the request, including what the model actually read

Once filtering and identity-based deduplication finish, assign indices by array order. Freeze the resulting list with the query, model, requested result count, and authorization policy version. Include the exact submitted text, not only a pointer to a database record that can change while the request runs. If you add a custom ranking instruction, include it in the frozen payload as well.

A source ID survives edits; a source revision identifies the content that was scored. Both matter. Suppose the manual changes from revision four to revision five after submission. Reconstructing index two from the newest manual can attach a score computed for one instruction to a different instruction. The response may be perfectly valid while the application's reconstructed evidence is wrong.

The snapshot identifier belongs to your application. Associate it with the request task or callback that carries the response; do not assume the API echoes an arbitrary metadata field. A content fingerprint can detect that the retained request changed, but it is not an authorization token and does not authenticate an untrusted client. Store the actual manifest in trusted request state rather than trying to recover it from the hash later.

For a retriever backed by multiple indexes, retain the index generation in your surrounding manifest too. That makes it possible to explain which candidate-producing dataset supplied the rows. The embedding migration guide addresses how those generations change; the operation here is narrower, preserving the evidence chosen from one generation during a single rerank request.

A small mapper that refuses ambiguous reconstruction

This standard-library implementation keeps metadata locally and submits only the document strings expected by the compatible text endpoint. Its allowlist is a fixture stand-in for a trusted authorization service. It deduplicates a repeated source revision, keeps equal text from distinct sources, and rejects conflicting text under one identity.

"""Offline source mapping for the QwenCloud compatible rerank schema."""
from dataclasses import asdict, dataclass
import hashlib
import json
import math


@dataclass(frozen=True)
class Candidate:
    source_id: str
    chunk_id: str
    revision: str
    text: str


@dataclass(frozen=True)
class Snapshot:
    candidates: tuple
    payload_json: str
    snapshot_id: str


def freeze(rows, allowed_source_ids, query, model, policy_version, top_n=3):
    # allowed_source_ids comes from trusted application authorization.
    if type(top_n) is not int or top_n < 1:
        raise ValueError("top_n must be a positive integer")
    unique = {}
    for row in rows:
        if row.source_id not in allowed_source_ids:
            continue
        key = (row.source_id, row.chunk_id, row.revision)
        if key in unique and unique[key].text != row.text:
            raise ValueError("one source revision has conflicting text")
        unique.setdefault(key, row)
    candidates = tuple(unique.values())
    if not candidates:
        raise ValueError("no authorized candidates; do not call rerank")
    payload = {"model": model, "query": query,
               "documents": [c.text for c in candidates], "top_n": top_n}
    encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True)
    manifest = {"payload": payload, "policy_version": policy_version,
                "candidates": [asdict(c) for c in candidates]}
    digest = hashlib.sha256(json.dumps(
        manifest, ensure_ascii=False, sort_keys=True
    ).encode()).hexdigest()
    return Snapshot(candidates, encoded, digest)


def restore(snapshot, bound_snapshot_id, response):
    # The caller binds this ID to its request; the API need not echo it.
    if bound_snapshot_id != snapshot.snapshot_id:
        raise ValueError("response belongs to another snapshot")
    rows = response["results"]  # compatible schema, not output.results
    expected = min(json.loads(snapshot.payload_json)["top_n"],
                   len(snapshot.candidates))
    if not isinstance(rows, list) or len(rows) != expected:
        raise ValueError("unexpected result count")
    seen, restored, previous = set(), [], float("inf")
    for rank, result in enumerate(rows, 1):
        i, score = result["index"], result["relevance_score"]
        if type(i) is not int or not 0 <= i < len(snapshot.candidates):
            raise ValueError("invalid input index")
        if i in seen:
            raise ValueError("duplicate input index")
        if (type(score) not in (int, float) or not math.isfinite(score)
                or not 0 <= score <= 1 or score > previous):
            raise ValueError("invalid score or ranking order")
        seen.add(i)
        previous = score
        restored.append({"rank": rank, "input_index": i,
                         "relevance_score": score,
                         **asdict(snapshot.candidates[i])})
    return restored

The mapper deliberately uses the compatible response's top-level results. It will not guess that an unrelated nested object is equivalent. It rejects negative indices, booleans masquerading as integers, repeated indices, nonfinite scores, and an unexpected result count. These checks prevent malformed data from selecting an unintended source. A failure should leave the request unresolved for investigation rather than partially publishing the rows that happened to parse.

The count check expresses this example's strict contract: the response must contain the smaller of the requested count and candidate count. If your integration deliberately permits partial results, give that outcome an explicit status and preserve the missing-result information. Silently accepting an empty list as a complete ranking makes a protocol error indistinguishable from a genuine no-source state.

The function preserves returned order, including equal scores. It does not promise identical tie ordering across future calls. Once reconstructed, the application can add display labels or group chunks from the same document, but it should retain the original rank and input index for inspection. Grouping for presentation must never rewrite the mapping used to identify the scored evidence.

What top_n removes, and what it cannot repair

QwenCloud's reranking guide describes top_n as a returned-result limit: omitting it returns all ranked candidates, and a value above the candidate count returns all candidates. It does not mean “rank only the first N submitted strings.” Treat the input list and output selection as separate quantities.

In our example, requesting three results leaves the network chunk unreturned. You cannot assign that chunk a score of zero; its score is simply absent from this response. Nor can you recover a missing policy document that the retriever never supplied by increasing top_n. The parameter controls how much of the ranked candidate set comes back, not which documents exist in the collection.

Duplicate sources create a second practical trap. If the interface needs three distinct documents, three ranked chunks might supply only two documents. Decide the diversity policy before choosing the result count. You can deduplicate identical chunk identities before submission and, where justified, request additional ranked candidates for later document grouping. Keep the distinction visible: a result limit is a count of returned entries, not a guarantee of distinct source documents.

Avoid treating a short returned list as proof of proportionally lower scoring work. Every submitted candidate remains relevant to request size. Reducing the eligible candidate set and reducing the returned result count are different decisions. Record both numbers so that troubleshooting does not confuse a large payload with a large output.

Keep the HTTP contract in one documentation family

For a concrete live integration, use one complete endpoint contract. The accompanying request template targets QwenCloud's compatible text endpoint with qwen3-rerank. It is not a live test, and it does not use a chat-completions method.

Contract elementQwenCloud compatible text reranking
Singapore URLhttps://ap-southeast-1.maas.qwencloudapi.com/compatible-api/v1/reranks
Request bodyFlat model, query, documents, top_n
Document representationArray of strings
Result locationTop-level results
Mapping fieldsindex, relevance_score

QwenCloud's regions reference describes region-specific keys and region-only hosts. Its rerank reference documents Singapore and Beijing for this text endpoint. Select a matching endpoint and credential together; a working credential for a different service region does not establish a valid rerank configuration.

The Alibaba Cloud Model Studio guide currently illustrates workspace-qualified maas.aliyuncs.com hosts. Its published per-document limit also differs from the QwenCloud table. Do not combine a host from one page with limits or account assumptions from another. Confirm limits against the particular service contract you will call instead of treating a model name as a universal transport specification.

The DashScope reranking reference uses nested input and parameters, with results inside output.results. Its curl example uses the native /api/v1/services/rerank/text-rerank/text-rerank path. Those wrappers do not belong in the compatible request above. Keeping separate adapters makes this difference explicit and keeps the source mapper independent of SDK method names.

A score belongs to this query and this request

The compatible reference describes relevance scores as relative to the current request and warns against comparing them across requests. Store a score alongside its query and snapshot, rather than writing it onto the source as a permanent quality rating. A manual paragraph can be ideal for reset instructions and irrelevant to a billing question without either outcome revealing a contradiction.

For the same reason, a score of 0.91 is not a documented 91 percent probability that a generated answer is correct. The reranker has assessed the submitted text against a query. It has not verified the entire source, checked current user permissions, or validated an answer that has not yet been generated. If the product needs abstention, build that decision around task-specific evidence and validated behavior rather than an unexplained universal score cutoff.

Keep ranking instructions with the same request record. An instruction favoring semantic similarity can select different evidence from an instruction favoring passages that answer a question. Changing that instruction is a change to the task. When investigating an unexpected source, inspect the query, submitted text, and instruction together before concluding that the index mapping is broken.

Replay the handoff without calling a model

Run the following fixture after the mapper. It recreates the opening response and deliberately contains identical strings with different identities. No API key is needed.

rows = [
    Candidate("manual", "opening", "r4", "Start the console."),
    Candidate("private", "exceptions", "r2", "Private exception."),
    Candidate("faq", "reset", "r7", "Hold Reset for ten seconds."),
    Candidate("manual", "reset", "r4", "Hold Reset for ten seconds."),
    Candidate("faq", "reset", "r7", "Hold Reset for ten seconds."),
    Candidate("manual", "network", "r4", "Check the network cable."),
]
snapshot = freeze(rows, {"manual", "faq"}, "How do I reset?",
                  "qwen3-rerank", "acl-v12", top_n=3)
response = {"results": [
    {"index": 2, "relevance_score": 0.91},
    {"index": 1, "relevance_score": 0.89},
    {"index": 0, "relevance_score": 0.24},
]}
result = restore(snapshot, snapshot.snapshot_id, response)
assert [r["input_index"] for r in result] == [2, 1, 0]
assert [r["source_id"] for r in result] == ["manual", "faq", "manual"]
assert len(json.loads(snapshot.payload_json)["documents"]) == 4
assert "Private exception." not in snapshot.payload_json

These assertions test evidence identity and the order of operations, not model accuracy. The accompanying offline suite also exercises stale snapshots, malformed indices, duplicate results, changed revisions, changed policy versions, score validation, ties, and result-count mismatches. All fourteen tests passed locally. The separate HTTP template was compiled but not sent to a provider.

Persist the mapping outcome with the request record before handing sources to answer generation. This resembles the accountability problem in batch-result reconciliation: successful transport does not by itself prove that results have been attached to the correct business objects. Here the durable record is much smaller, but it still needs to explain which exact input occurrence became each displayed source.

FAQ

Can returned document text replace the snapshot?

No. Equal text can belong to different sources, and returned text does not carry all your revision and authorization metadata. Even when the selected protocol returns document text, use the input index to recover identity from the retained snapshot.

Should I filter private results after selecting top_n?

Filter unauthorized material before submitting it. Otherwise, its contents have already entered the scoring request. Recheck permissions before delivery when necessary, and treat that as an additional check rather than a substitute.

Can I merge scores from separately reranked candidate batches?

Do not assume they form one calibrated ranking. The documented scores are request-relative. If a global ordering is required, use an explicitly designed consolidation stage and retain each batch's identity instead of sorting unrelated scores into a supposedly universal list.

For the next boundary, testing source-supported answers shows why preserving source IDs is necessary but does not establish that an answer's claims are correct. Before routing a live experiment, confirm the model, region, endpoint, and rerank fields available on the selected Treerouter route. Start with the four authorized fixture candidates and verify that every returned position opens the intended source revision.

Official references