On this page
A developer asks an internal engineering assistant what maximum batch size the v2 inference API allows for offline embedding jobs. The assistant replies "50,000 requests per file" and cites [E1]. The endpoint returns 200 OK, and every dashboard stays green.
The answer is wrong in the quietest way possible. Under v2, the ceiling dropped to 20,000 requests per file, and only when the compressed payload stays under 100 MB. That 50,000 figure came from last year's deprecated v1 specification, which is what [E1] resolved to.
Retrieval-augmented generation (RAG) grounds a language model in an external document index so answers track live documentation without retraining weights.[1] Building a demo takes an afternoon, yet five failures break it in production: mistaking nearest neighbors for evidence, leaking restricted docs via post-filtering, letting stale revisions outrank current ones, splitting a specification across chunk edges so its 100 MB cap disappears, and tuning prompts when retrieval dropped the passage.
Four guarantees and three paths
Every grounded response needs four properties simultaneously:
| Property | Target behavior | Failure prevented |
|---|---|---|
| Scope & ACL | Search only records permitted for the caller's workspace and groups | Restricted drafts leak into prompts or rerankers |
| Freshness | Serve only active document versions and honor deletions permanently | Deprecated v1 limits override v2 specs |
| Completeness | Expand matched child chunks to version-matched parent sections | Clause split drops the 100 MB payload cap |
| Grounding & attribution | Cite packed sources faithfully, abstain when unsupported, trace every stage | Unverifiable claims or blind prompt tuning |
Splitting the system into three paths localizes every regression quickly:
- Ingestion path (offline): Parses docs, builds child chunks linked to parent sections, attaches trusted tenant/group/version metadata, and publishes atomic versioned bundles.
- Request path (online): Filters by caller identity and active version, retrieves and reranks candidates, packs source-labeled context within a token budget, and returns a cited answer or explicit abstention.
- Evaluation path (pre-release): Replays a fixed labeled suite across any new index, retriever, prompt, or model, attributing regressions to the earliest failing stage before cutover.
Versioned evidence records and parent-child expansion
Carry source metadata from Chunking Strategies onto every indexed record: chunk_id, document_id, parent_id, version, workspace, acl_group, effective_from, and effective_to. Populate these fields strictly from trusted ingestion pipelines rather than document text, and version ACL grants separately from document content because group membership changes while text stays unchanged.
Retrieve small, expand to version-matched parents
Short chunks produce crisp retrieval vectors, while complete sections supply qualifiers and exceptions. Parent-child indexing searches compact child chunks, then resolves each hit through parent_id to its surrounding parent section after rechecking revision and ACL.[2] A lighter alternative is sentence-window retrieval, indexing single sentences and expanding to neighboring sentences on hit.[3]

Sliding overlap helps short phrases cross a split, yet multi-clause specifications with footnotes or exceptions still fracture unless you expand to the parent section.

Publish each index update as an atomic bundle (child index, parent store, manifest, retriever config) and pin one bundle per request so child matches and expanded parents share the exact same revision. Separate deletions from supersession: archived versions stay queryable for replay, while deleted documents carry a permanent tombstone (plus cache purge) so rolling back an index pointer never resurrects deleted text. When swapping embedding models, build the new index in parallel and validate on shadow traffic because two models with the same dimension still inhabit incompatible vector spaces.
Pre-filter ACLs inside search, never after top-k
Pre-filter ACL invariant: Run tenant, workspace, and group predicates before or inside vector and lexical search rather than post-filtering global top- in application code. Post-filtering breaks twice: restricted chunks enter worker memory, caches, traces, and external rerankers before removal, and when another tenant dominates top-, the caller gets underfilled or empty results even when permitted docs sit just below the cutoff. In HNSW engines, pgvector's
hnsw.iterative_scankeeps traversing until enough eligible rows match,[4][5][6] while Weaviate and Azure AI Search build allow-lists before or during traversal (such as ACORN or flat fallback).[7][8][9] Never retry an empty authorized search by relaxing the filter.
Authorized retrieval and context packing in code
This runnable pipeline indexes a technical documentation corpus with TfidfVectorizer and cosine similarity, applies workspace, ACL, effective-date, and tombstone filters before scoring, and packs version-matched parents:
from dataclasses import dataclass
from datetime import date
from hashlib import sha256
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
@dataclass(frozen=True)
class DocChunk:
chunk_id: str
document_id: str
parent_id: str
version: str
workspace: str
acl_group: str
effective_from: date
effective_to: date | None
text: str
@dataclass(frozen=True)
class ParentSection:
parent_id: str
document_id: str
version: str
workspace: str
acl_group: str
effective_from: date
effective_to: date | None
locator: str
text: str
@dataclass(frozen=True)
class Caller:
user_id: str
workspace: str
groups: frozenset[str]
TODAY = date(2026, 6, 15)
BATCH_SPEC_V2 = (
"Batch Inference API v2 accepts up to 20,000 requests per JSONL file, "
"provided the compressed payload stays under 100 MB."
)
CHUNKS = [
DocChunk("batch-api-v2-limits", "batch-api", "batch-api-sec4-v2", "batch-api/2026-05-01",
"ml-platform", "eng:platform", date(2026, 5, 1), None, BATCH_SPEC_V2),
DocChunk("batch-api-v1-limits", "batch-api", "batch-api-sec4-v1", "batch-api/2025-03-01",
"ml-platform", "eng:platform", date(2025, 3, 1), date(2026, 4, 30),
"Batch Inference API v1 accepts up to 50,000 requests per JSONL file."),
DocChunk("stream-sse-timeout-v2", "streaming-api", "streaming-sec2-v2", "streaming-api/2026-02-10",
"ml-platform", "eng:platform", date(2026, 2, 10), None,
"Streaming SSE connections close after 90 seconds of idle time unless heartbeats arrive."),
DocChunk("batch-capacity-internal", "capacity-plan", "capacity-plan-v1", "capacity/2026-06-01",
"ml-platform", "infra:capacity-admins", date(2026, 6, 1), None,
"Batch Inference API v2 internal quota override: capacity admins may submit 200,000 requests per JSONL file."),
]
PARENTS = {
"batch-api-sec4-v2": ParentSection(
"batch-api-sec4-v2", "batch-api", "batch-api/2026-05-01", "ml-platform", "eng:platform",
date(2026, 5, 1), None, "Batch Inference API v2 > Section 4.1 Limits",
"Section 4.1 Batch Limits. " + BATCH_SPEC_V2,
),
"streaming-sec2-v2": ParentSection(
"streaming-sec2-v2", "streaming-api", "streaming-api/2026-02-10", "ml-platform", "eng:platform",
date(2026, 2, 10), None, "Streaming API v2 > Section 2.3 Timeouts",
"Section 2.3 Timeouts. Streaming SSE connections close after 90 seconds of idle time unless heartbeats arrive.",
),
}
def is_active(record: DocChunk | ParentSection, on_date: date) -> bool:
return record.effective_from <= on_date and (record.effective_to is None or on_date <= record.effective_to)
def prefilter_chunks(
caller: Caller, chunks: list[DocChunk], on_date: date, deleted_docs: frozenset[str] = frozenset()
) -> list[DocChunk]:
return [
c for c in chunks
if c.document_id not in deleted_docs and c.workspace == caller.workspace
and c.acl_group in caller.groups and is_active(c, on_date)
]
def search_prefiltered(
query: str, caller: Caller, chunks: list[DocChunk], on_date: date,
top_k: int = 2, deleted_docs: frozenset[str] = frozenset(),
) -> list[tuple[DocChunk, float]]:
eligible = prefilter_chunks(caller, chunks, on_date, deleted_docs)
if not eligible:
return []
vec = TfidfVectorizer(stop_words="english")
matrix = vec.fit_transform([c.text for c in eligible])
sims = cosine_similarity(vec.transform([query]), matrix).ravel()
order = np.argsort(-sims)[:top_k]
return [(eligible[int(i)], float(sims[int(i)])) for i in order if sims[int(i)] > 0.0]
def pack_parents(
hits: list[tuple[DocChunk, float]], caller: Caller, on_date: date,
parents: dict[str, ParentSection], max_chars: int = 420,
deleted_docs: frozenset[str] = frozenset(),
) -> list[dict[str, str]]:
packed, seen, total_chars = [], set(), 0
for chunk, _ in hits:
parent = parents.get(chunk.parent_id)
if parent is None or parent.parent_id in seen or parent.document_id in deleted_docs:
continue
if (parent.document_id != chunk.document_id or parent.version != chunk.version
or parent.workspace != caller.workspace or parent.acl_group not in caller.groups
or not is_active(parent, on_date)):
continue
entry = f"[E{len(packed) + 1}] ({parent.version}) {parent.text}"
if total_chars + len(entry) > max_chars:
continue
packed.append({
"label": f"E{len(packed) + 1}", "chunk_id": chunk.chunk_id, "parent_id": parent.parent_id,
"version": parent.version, "locator": parent.locator, "text": parent.text,
"sha256": sha256(parent.text.encode()).hexdigest()[:12],
})
seen.add(parent.parent_id)
total_chars += len(entry)
return packed
caller = Caller("dev-42", "ml-platform", frozenset({"eng:platform"}))
query = "batch inference API v2 max requests per JSONL file"
all_vec = TfidfVectorizer(stop_words="english")
all_mat = all_vec.fit_transform([c.text for c in CHUNKS])
all_sims = cosine_similarity(all_vec.transform([query]), all_mat)[0]
unfiltered_top = CHUNKS[int(np.argmax(all_sims))].chunk_id
hits = search_prefiltered(query, caller, CHUNKS, TODAY, top_k=2)
packed = pack_parents(hits, caller, TODAY, PARENTS)
print("Unfiltered top hit (leaky/stale risk):", unfiltered_top)
print("Pre-filtered hits:", [(c.chunk_id, round(s, 3)) for c, s in hits])
print("Packed context:", [(p["label"], p["parent_id"], p["sha256"]) for p in packed])
print("After tombstone delete:", search_prefiltered(query, caller, CHUNKS, TODAY, deleted_docs=frozenset({"batch-api"})))
assert hits[0][0].chunk_id == "batch-api-v2-limits"
assert all(c.acl_group == "eng:platform" for c, _ in hits)
assert len(packed) == 1 and packed[0]["parent_id"] == "batch-api-sec4-v2"Unfiltered top hit (leaky/stale risk): batch-api-v1-limits
Pre-filtered hits: [('batch-api-v2-limits', 0.661)]
Packed context: [('E1', 'batch-api-sec4-v2', 'a609ac25af27')]
After tombstone delete: []Keep three operational guardrails beside context packing: avoid padding prompts with weak distractors (relevant passages buried in the middle lose accuracy[10]), delimit retrieved passages as untrusted quoted data to block indirect prompt injection (Prompt Injection Defense),[11] and key caches by workspace, ACL revision, effective date, bundle ID, and prompt/model version while rechecking live grants and answer-critical numeric thresholds (18,000 vs. 25,000 requests) before reusing any cached or buffered reply.
A developer loses access to an internal design doc after retrieval finishes and after the LLM drafted a reply, even though the draft only cites a public doc. Can you strip the unquoted doc and send the draft?
Answer
No. Because the restricted doc was inside the prompt when the model generated the text, its wording can reflect that source even without citing it. Discard the draft and regenerate from currently permitted context alone.
Evaluate retrieval and generation separately
An end-to-end score hides whether retrieval, context packing, or generation failed. Measure each layer separately (as in RAGAS and TruLens's RAG triad[12][13]):
| Layer | Metric | Formula / Definition | Failure caught |
|---|---|---|---|
| Stage 1 Retrieval | Candidate Recall | First-stage search missed required passages (distinct from ANN recall vs. exact search) | |
| Context Packing | Context Recall[14] | Reranker or token budget dropped a retrieved passage before the prompt | |
| Context Packing | Context Precision | Prompt is flooded with distractors (set precision vs. rank-weighted Ragas ContextPrecision[15]) | |
| Generation | Faithfulness[16] | Model contradicts context or invents unsupported claims | |
| Generation | Answer Relevance | Fraction of required query aspects addressed (or clean abstention when ) | Model cites valid text faithfully yet dodges the question |
Faithfulness vs. citation syntax vs. answer relevance
Checking whether packed context entails atomic claim is an NLI check (entailed, contradicted, or unsupported). Keep three distinct failures separate: a valid citation with an unfaithful claim ([E1] exists and states 20,000, yet the model claims 50,000), a faithful but off-topic answer (accurately summarizing SSE timeouts when asked about batch limits: faithfulness 1.0, answer relevance 0.0), and supported denial vs. abstention (a 25,000-request job against the v2 limit is a supported no, whereas missing documentation calls for explicit abstention).
Attribute the first failed stage
Check stages in causal pipeline order: authorization -> candidate retrieval -> context packing -> faithfulness -> citation support -> answer relevance. Stopping at the earliest failure prevents editing prompts when retrieval or reranking dropped the source.

@dataclass(frozen=True)
class Claim:
text: str
cited_label: str | None
@dataclass(frozen=True)
class RagTrace:
caller_authorized: bool
candidate_ids: tuple[str, ...]
packed_ids: tuple[str, ...]
source_map: dict[str, str]
claims: tuple[Claim, ...]
answered_aspects: frozenset[str]
REQUIRED_DOCS = frozenset({"batch-api-v2-limits"})
REQUIRED_ASPECTS = frozenset({"max_requests", "payload_cap"})
ENTAILED_BY = {
"Batch API v2 allows up to 20,000 requests per JSONL file.": "batch-api-v2-limits",
"Compressed payloads must stay under 100 MB.": "batch-api-v2-limits",
"SSE connections time out after 90 seconds idle.": "stream-sse-timeout-v2",
}
def compute_metrics(trace: RagTrace) -> dict[str, float]:
cand_set, pack_set = set(trace.candidate_ids), set(trace.packed_ids)
cand_recall = len(cand_set & REQUIRED_DOCS) / len(REQUIRED_DOCS)
ctx_recall = len(pack_set & REQUIRED_DOCS) / len(REQUIRED_DOCS)
ctx_prec = len(pack_set & REQUIRED_DOCS) / len(pack_set) if pack_set else 0.0
if trace.claims:
entailed = [ENTAILED_BY.get(c.text) in pack_set for c in trace.claims]
cited_ok = [c.cited_label is not None and trace.source_map.get(c.cited_label) == ENTAILED_BY.get(c.text) for c in trace.claims]
faith, cite_acc = float(np.mean(entailed)), float(np.mean(cited_ok))
else:
faith, cite_acc = 0.0, 0.0
ans_rel = len(trace.answered_aspects & REQUIRED_ASPECTS) / len(REQUIRED_ASPECTS)
return {"cand_recall": cand_recall, "ctx_recall": ctx_recall, "ctx_prec": ctx_prec,
"faithfulness": faith, "cite_support": cite_acc, "ans_relevance": ans_rel}
def first_failed_stage(trace: RagTrace) -> str:
if not trace.caller_authorized:
return "1_authorization"
m = compute_metrics(trace)
for key, stage in (
("cand_recall", "2_candidate_retrieval"),
("ctx_recall", "3_context_packing"),
("faithfulness", "4_faithfulness"),
("cite_support", "5_citation_support"),
("ans_relevance", "6_answer_relevance"),
):
if m[key] < 1.0:
return stage
return "pass"
good_claims = (
Claim("Batch API v2 allows up to 20,000 requests per JSONL file.", "E1"),
Claim("Compressed payloads must stay under 100 MB.", "E1"),
)
scenarios = {
"healthy": RagTrace(True, ("batch-api-v2-limits", "stream-sse-timeout-v2"), ("batch-api-v2-limits",),
{"E1": "batch-api-v2-limits"}, good_claims, REQUIRED_ASPECTS),
"noisy_context_still_pass": RagTrace(True, ("batch-api-v2-limits", "stream-sse-timeout-v2"),
("batch-api-v2-limits", "stream-sse-timeout-v2"),
{"E1": "batch-api-v2-limits", "E2": "stream-sse-timeout-v2"}, good_claims, REQUIRED_ASPECTS),
"retrieval_miss": RagTrace(True, ("stream-sse-timeout-v2",), ("stream-sse-timeout-v2",),
{"E1": "stream-sse-timeout-v2"}, good_claims, REQUIRED_ASPECTS),
"packer_dropped_v2": RagTrace(True, ("batch-api-v2-limits", "stream-sse-timeout-v2"), ("stream-sse-timeout-v2",),
{"E1": "stream-sse-timeout-v2"}, good_claims, REQUIRED_ASPECTS),
"hallucinated_v1_limit": RagTrace(True, ("batch-api-v2-limits",), ("batch-api-v2-limits",), {"E1": "batch-api-v2-limits"},
(Claim("Batch API v2 allows up to 50,000 requests per JSONL file.", "E1"),), REQUIRED_ASPECTS),
"faithful_but_off_topic": RagTrace(True, ("batch-api-v2-limits", "stream-sse-timeout-v2"),
("batch-api-v2-limits", "stream-sse-timeout-v2"),
{"E1": "batch-api-v2-limits", "E2": "stream-sse-timeout-v2"},
(Claim("SSE connections time out after 90 seconds idle.", "E2"),), frozenset()),
}
for name, tr in scenarios.items():
m = compute_metrics(tr)
print(f"{name:24} | ctx_rec={m['ctx_recall']:.1f} ctx_prec={m['ctx_prec']:.2f} faith={m['faithfulness']:.1f} rel={m['ans_relevance']:.1f} -> {first_failed_stage(tr)}")
assert first_failed_stage(scenarios["healthy"]) == "pass"
assert compute_metrics(scenarios["noisy_context_still_pass"])["ctx_prec"] == 0.5
assert first_failed_stage(scenarios["retrieval_miss"]) == "2_candidate_retrieval"
assert first_failed_stage(scenarios["packer_dropped_v2"]) == "3_context_packing"
assert first_failed_stage(scenarios["hallucinated_v1_limit"]) == "4_faithfulness"
assert first_failed_stage(scenarios["faithful_but_off_topic"]) == "6_answer_relevance"healthy | ctx_rec=1.0 ctx_prec=1.00 faith=1.0 rel=1.0 -> pass
noisy_context_still_pass | ctx_rec=1.0 ctx_prec=0.50 faith=1.0 rel=1.0 -> pass
retrieval_miss | ctx_rec=0.0 ctx_prec=0.00 faith=0.0 rel=1.0 -> 2_candidate_retrieval
packer_dropped_v2 | ctx_rec=0.0 ctx_prec=0.00 faith=0.0 rel=1.0 -> 3_context_packing
hallucinated_v1_limit | ctx_rec=1.0 ctx_prec=1.00 faith=0.0 rel=1.0 -> 4_faithfulness
faithful_but_off_topic | ctx_rec=1.0 ctx_prec=0.50 faith=1.0 rel=0.0 -> 6_answer_relevanceTraceability and latency budgets
Log compact identifiers (request_id, user_id, workspace, acl_revision, index_bundle_id, candidate_ids, source_map with parent_id/version/sha256, cited_labels, abstained, model_version, stage timings) instead of dumping restricted corpus text into shared logs. Because greedy decoding (temperature = 0) is still best-effort across serving upgrades,[17] store full prompts only in an access-controlled archive when required.
Budget TTFT and tail latency by stage
Distinguish model TTFT (prompt arrival to first token) from end-to-end TTFT (caller arrival through authorization, retrieval, packing, and prefill to first client token). Streaming over SSE shows tokens as they decode, whereas buffering the entire answer for post-generation verification delays first text until decode plus verification finish.

Propagate one end-to-end deadline across stages and measure complete-request p95 directly: if five independent stages each pass 95% of the time, all five pass together only of the time.
import numpy as np
STAGE_BUDGET_MS = {"authorize": 10, "retrieve": 80, "pack": 10, "model_ttft": 500, "generate": 500, "trace": 10}
CRITICAL_PATH = ("authorize", "retrieve", "pack", "model_ttft", "generate")
DEADLINE_MS = 1000
def check_latency(timings: dict[str, int]) -> list[str]:
breaches = [s for s, lim in STAGE_BUDGET_MS.items() if timings.get(s, -1) < 0 or timings[s] > lim]
if all(s in timings and timings[s] >= 0 for s in CRITICAL_PATH):
if sum(timings[s] for s in CRITICAL_PATH) > DEADLINE_MS:
breaches.append("end_to_end_deadline")
return breaches
healthy = {"authorize": 2, "retrieve": 18, "pack": 1, "model_ttft": 320, "generate": 410, "trace": 3}
cumulative = {"authorize": 10, "retrieve": 80, "pack": 10, "model_ttft": 500, "generate": 450, "trace": 3}
e2e_ttft = sum(healthy[s] for s in ("authorize", "retrieve", "pack", "model_ttft"))
print(f"Healthy e2e TTFT: {e2e_ttft} ms | breaches: {check_latency(healthy)}")
print(f"Cumulative slow : {sum(cumulative[s] for s in CRITICAL_PATH)} ms | breaches: {check_latency(cumulative)}")
rng = np.random.default_rng(42)
stage_ok = rng.random((100_000, 5)) < 0.95
print(f"All-5-pass empirical rate: {stage_ok.all(axis=1).mean():.3f} (analytic 0.95^5 = {0.95**5:.3f})")
assert e2e_ttft == 341 and check_latency(healthy) == []
assert check_latency(cumulative) == ["end_to_end_deadline"]Healthy e2e TTFT: 341 ms | breaches: []
Cumulative slow : 1050 ms | breaches: ['end_to_end_deadline']
All-5-pass empirical rate: 0.774 (analytic 0.95^5 = 0.774)Pre-launch verification checklist
| Check | Release blocker | First place to fix |
|---|---|---|
| Pre-filter ACL | Any restricted chunk enters candidates, reranker, or traces | Search-engine pre-filter and metadata schema |
| Version & tombstones | Superseded or deleted revision surfaces on rollback | Bundle pinning, effective-date filter, tombstone table |
| Context recall & precision | Required parent dropped or drowned by distractors | Stage-1 retriever, chunking, rerank cutoff, packer budget |
| Faithfulness & relevance | Unsupported claims, wrong citations, or off-topic replies | Prompt grounding, claim verifier, abstention threshold |
| Prompt injection | Retrieved text alters system behavior or invokes tools | Data delimiters; keep tool authorization outside the model |
| Cache isolation | Cache key omits workspace, ACL revision, or bundle version | Cache key schema and pre-return grant recheck |
| Tail latency | End-to-end p95 misses request deadline | Profile slowest stage; enforce deadline propagation |
Ship RAG as an evidence pipeline rather than a prompt wrapper: enforce ACLs and versions inside search, expand to pinned parent sections, attribute failures to the first broken stage, and budget end-to-end tail latency before launch.