On this page
The API specification made it out of the Markdown parser intact:
inference-api-spec-v2.md, section 4.2: Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames.
Then the chunking step runs, and it does something that looks harmless. One chunk ends with Streaming timeout: close idle SSE connections after, and the next begins with 90 seconds without heartbeat frames. A developer asks, "Why did my idle SSE connection close, and how do I keep it alive?" The second chunk matches seconds and heartbeat cleanly and ranks first. The model receives a timeout and an exception with nothing stating which protocol or condition they belong to.
Nothing crashed. Extraction succeeded, the vector index returned a high-scoring hit, and the answer still failed because the boundary landed right across the one sentence that mattered.
Two stages decide whether the trigger (idle SSE connections), the threshold (90 seconds), and the exception (without heartbeat frames) reach the generator intact: document ingestion (extracting clean structure from raw PDFs, HTML, scans, and Markdown) and chunking (dividing normalized documents into the units a retriever indexes and returns in retrieval-augmented generation (RAG)).[1] Every embedding model also enforces a hard token ceiling while compressing an entire chunk into one vector; all-MiniLM-L6-v2, for example, outputs 384 dimensions and truncates inputs past 256 word pieces by default.[2]

Ingestion first: PDFs, HTML, OCR, and normalized records
Even the sharpest chunker cannot repair text corrupted during extraction. Normalize every incoming file format into a single structured record carrying source_id, locator (page number, section heading, or anchor), version, a SHA-256 checksum, extracted text blocks, and caller-permission metadata before any splitter runs:
| Source format | Dominant failure mode | Practical defense |
|---|---|---|
| Digital PDFs | PDFs store positioned glyphs rather than logical paragraphs; multi-column layouts scramble reading order, running headers/footers break sentences, and tables flatten into unaligned text[3][4] | Use layout-aware parsers (such as Docling or bounding-box column sorters) that reconstruct reading order and emit structured tables[5] |
| Scanned PDFs & images (OCR) | Character confusions (1S vs. 15, O vs. 0, dropped decimal points) silently alter numeric limits[6] | Record OCR confidence scores and route low-confidence pages to vision-language OCR (such as olmOCR) or human review; never silently regex-rewrite uncertain digits[7] |
| HTML web pages | Navigation bars, sidebars, cookie banners, and footers flood chunks with repeated boilerplate | Parse the DOM (for example with BeautifulSoup or readability extractors) to keep <main> / <article> headings, lists, and tables while stripping page chrome[8] |
| Markdown & docs | Flattening files to plain text throws away headings, tables, and code fences you already had | Parse into an AST or preserve heading hierarchy, fenced code blocks, and pipe tables verbatim[9] |
When documents are dominated by dense charts, multi-column financial tables, or engineering schematics that resist text extraction, visual page retrieval (such as ColPali, which embeds rendered page images with a vision-language encoder and matches queries via ColBERT-style late interaction) lets retrieval skip fragile OCR altogether.[10][11] Finally, treat external HTML and PDF text as untrusted input: keep extraction quality, quarantine checks against embedded prompt injections, and document access permissions as three independent gates before writing records into the index.[12]
Define answerability before choosing a chunk size
It is tempting to treat chunk size as a tuning dial and ask whether 512 tokens beats 256. Start instead with what a complete passage must hold for a real query: "Why did my idle streaming connection close, and how do I keep it open?"
| Candidate chunk | Searchable? | Answerable? | Defect |
|---|---|---|---|
Streaming timeout: close idle SSE connections after | yes | no | Drops the 90-second limit and heartbeat exception |
90 seconds without heartbeat frames. Batch retention: expire JSONL outputs after 14 days. | yes | no | Drops the SSE trigger and mixes in an unrelated retention rule |
Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. | yes | yes | Keeps trigger, threshold, and exception intact |
Small chunks still work well as sharp search targets when a downstream step reliably expands them into their parent section before generation. Always evaluate the complete assembled text that actually enters the generator under your context budget.
Fixed windows and the real cost of overlap
The simplest splitter walks across text in fixed windows of tokens with overlap , advancing by stride . The script below splits on whitespace so cut boundaries stay easy to inspect; in production, always count lengths with your embedding model's tokenizer (including prepended headings and special tokens) so oversized inputs are never silently truncated.
What does increasing overlap actually buy? Our streaming-timeout rule is 12 words long. Inside a 7-word window, ramping overlap from 0 to 4 doubles the total indexed words while keeping complete coverage of the 12-word rule at zero:
import numpy as np
def fixed_windows(text: str, size: int, overlap: int) -> list[str]:
if not 0 <= overlap < size:
raise ValueError("require size > overlap >= 0")
words = text.split()
chunks = []
for start in range(0, len(words), size - overlap):
end = min(start + size, len(words))
chunks.append(" ".join(words[start:end]))
if end == len(words):
break
return chunks
spec = (
"Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. "
"Batch retention: expire JSONL outputs after 14 days."
)
for i, chunk in enumerate(fixed_windows(spec, size=6, overlap=2)):
print(f"win[{i}]: {chunk}")
full_rule = ("streaming timeout", "90 seconds", "heartbeat frames")
short_fact = ("connections after 90 seconds",)
for overlap in (0, 2, 4):
chunks = fixed_windows(spec, size=7, overlap=overlap)
indexed_words = sum(len(c.split()) for c in chunks)
has_rule = sum(all(p in c.lower() for p in full_rule) for c in chunks)
has_short = sum(all(p in c.lower() for p in short_fact) for c in chunks)
print(f"size=7 overlap={overlap}: chunks={len(chunks)} words={indexed_words:2d} full_rule={has_rule} short_fact={has_short}")
assert has_rule == 0win[0]: Streaming timeout: close idle SSE connections
win[1]: SSE connections after 90 seconds without
win[2]: seconds without heartbeat frames. Batch retention:
win[3]: Batch retention: expire JSONL outputs after
win[4]: outputs after 14 days.
size=7 overlap=0: chunks=3 words=20 full_rule=0 short_fact=0
size=7 overlap=2: chunks=4 words=26 full_rule=0 short_fact=1
size=7 overlap=4: chunks=6 words=40 full_rule=0 short_fact=1Look at win[4] (outputs after 14 days.): a trailing fragment drops its subject (Batch retention: expire JSONL) so the 14-day window floats without context. Meanwhile, overlap 2 rescues the 4-word phrase "connections after 90 seconds" (short_fact=0 -> 1) at the cost of 6 extra words, yet no amount of overlap can ever fit a 12-word rule inside a 7-word window.

Bennani and Moslonka found no measurable answer-quality gain from up to 20% overlap on Natural Questions with sentence-aware splitting and SPLADE retrieval.[13] Measure overlap on your own labeled queries before paying the storage and latency tax.
You split a 10,000-token API manual into 200-token windows with 40 tokens of overlap. Roughly how many tokens do you embed, and how long can a fact be and still be sure to land unbroken in one window?
Answer
Overlap fraction is , so you embed about tokens. Because adjacent windows share 40 overlapping tokens (stride 160), any discrete fact of up to tokens always lands intact inside at least one window (a 41-token span starting at index 159 ends at index 199 inside window 0, and starting at index 160 begins inside window 1); facts of 42 to 200 tokens depend on alignment, and anything past 200 tokens never fits.
Split on document structure first
Technical documentation, API references, and research papers already mark logical boundaries with headings, tables, paragraphs, and fenced code blocks. Throwing away Markdown structure only to patch broken boundaries with overlap solves a problem you created yourself.
For plain prose or oversized sections without subheadings, LangChain's RecursiveCharacterTextSplitter tries paragraph breaks ("\n\n"), line breaks ("\n"), spaces (" "), and characters ("") in sequence.[14] Watch two defaults: it counts Python characters (len) unless you pass a tokenizer-backed length_function, and its default separators do not detect sentence boundaries.
Keep three structural rules intact when splitting technical docs:
- Prepend headings to body text: Attach each Markdown heading (or heading hierarchy) to the embedded string while storing raw text and source locators separately so citations stay verbatim.
- Keep table headers with every row group: Detaching
| /v1/batches | 100 MB | 24h |from| Endpoint | Max Payload | Timeout |strips every cell of its role. Repeat column headers (and table-wide units or footnotes) on every split group. - Keep fenced code blocks intact, and distribute oversized tails evenly: Treat each fenced code block as atomic unless it alone exceeds the encoder cap. When an oversized paragraph must be split under a hard cap (for example, 15 words at max size 7), you need at least 3 chunks so you cannot enforce a 6-word minimum (); distribute evenly (
5, 5, 5) rather than gluing a 1-word tail into an 8-word overflow that silently truncates inside the embedder.
import math
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class SpecChunk:
heading: str
body: str
indexed_text: str
locator: str
def split_markdown_sections(markdown: str, source: str) -> list[SpecChunk]:
chunks, heading, buf = [], "Document", []
def flush() -> None:
text = "\n".join(buf).strip()
if text:
chunks.append(SpecChunk(heading, text, f"{heading}\n{text}", f"{source}#sec={len(chunks)}"))
buf.clear()
for line in markdown.strip().splitlines():
if line.startswith("## "):
flush()
heading = line[3:].strip()
else:
buf.append(line)
flush()
return chunks
def split_table_with_headers(lines: list[str], heading: str, max_rows: int = 2) -> list[str]:
header, sep, rows = lines[0], lines[1], lines[2:]
return [
f"{heading}\n{header}\n{sep}\n" + "\n".join(rows[i:i + max_rows])
for i in range(0, len(rows), max_rows)
]
def balanced_cap_split(text: str, max_words: int) -> list[tuple[str, tuple[int, int]]]:
spans = list(re.finditer(r"\S+", text))
count = math.ceil(len(spans) / max_words)
base, extra = divmod(len(spans), count)
out, cursor = [], 0
for i in range(count):
n = base + int(i < extra)
s, e = spans[cursor].start(), spans[cursor + n - 1].end()
out.append((text[s:e], (s, e)))
cursor += n
return out
doc = """## Streaming timeout
Close idle SSE connections after 90 seconds without heartbeat frames.
## Batch retention
Expire completed JSONL output files after 14 days."""
for ch in split_markdown_sections(doc, "inference-api-spec-v2.md"):
print(ch.locator, "|", ch.indexed_text.replace("\n", " :: "))
table = [
"| Endpoint | Max Payload | Timeout |",
"| --- | --- | --- |",
"| /v1/embeddings | 16 MB | 30s |",
"| /v1/chat/completions | 32 MB | 90s |",
"| /v1/batches | 100 MB | 24h |",
]
table_chunks = split_table_with_headers(table, "API Endpoint Limits", max_rows=2)
print("Table groups:", len(table_chunks), "| all carry header:", all("| Endpoint |" in g for g in table_chunks))
balanced = balanced_cap_split(
"Close idle SSE connections after 90 seconds unless clients send periodic keepalive heartbeat frames over HTTP.",
max_words=7,
)
print("Balanced spans:", [(len(t.split()), span) for t, span in balanced])
assert all(len(t.split()) <= 7 for t, _ in balanced)inference-api-spec-v2.md#sec=0 | Streaming timeout :: Close idle SSE connections after 90 seconds without heartbeat frames.
inference-api-spec-v2.md#sec=1 | Batch retention :: Expire completed JSONL output files after 14 days.
Table groups: 2 | all carry header: True
Balanced spans: [(6, (0, 35)), (5, (36, 72)), (5, (73, 110))]Parent-child retrieval: search small, answer big
Often the sharpest embedding target is a single sentence, while the generator needs the entire surrounding section (including caveats and parameter tables). Parent-child retrieval indexes narrow child spans for matching and expands each hit to its parent section before generation.[15]

Expansion introduces three serving-time invariants:
- Deduplicate parents when two matched children point to the same parent section.
- Verify version agreement and caller permissions on the parent itself.
- Reject budget overflows (or drop lower-ranked parents) rather than silently truncating a parent mid-clause.
parents = {
"sec-4-2": {
"text": "Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. Send `: ping` every 30 seconds.",
"source": "inference-api-spec-v2.md",
"version": 2,
},
}
hits = [
{"text": "90 seconds without heartbeat frames", "parent_id": "sec-4-2", "version": 2},
{"text": "Send `: ping` every 30 seconds", "parent_id": "sec-4-2", "version": 2},
]
def expand_parents(matches: list[dict], allowed: set[str], word_budget: int) -> list[dict]:
selected = {}
for m in matches:
pid = m["parent_id"]
if pid not in allowed:
raise PermissionError("parent access denied")
parent = parents[pid]
if m["version"] != parent["version"]:
raise ValueError("stale child-to-parent version")
selected[pid] = parent
if sum(len(p["text"].split()) for p in selected.values()) > word_budget:
raise ValueError("context budget exceeded")
return list(selected.values())
expanded = expand_parents(hits, allowed={"sec-4-2"}, word_budget=25)
print(f"child_hits={len(hits)} -> deduplicated_parents={len(expanded)}")
print("expanded:", expanded[0]["text"])
for label, args in [
("stale", ([{**hits[0], "version": 1}], {"sec-4-2"}, 25)),
("denied", (hits, set(), 25)),
("overflow", (hits, {"sec-4-2"}, 10)),
]: try:
expand_parents(*args)
except (ValueError, PermissionError) as err:
print(f"{label}: {err}")
assert len(expanded) == 1child_hits=2 -> deduplicated_parents=1
expanded: Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. Send `: ping` every 30 seconds.
stale: stale child-to-parent version
denied: parent access denied
overflow: context budget exceededSearch matches children from three API sections (300, 300, and 500 generator tokens) under a 1,000-token evidence budget. A teammate suggests truncating the third section to 400 tokens so all three fit. Why is that risky?
Answer
Cutting the final 100 tokens can slice off the exact caveat or exception that parent expansion was supposed to restore. Send the top two complete sections (600 tokens), log that the third was skipped due to budget, or use smaller complete subsections.
Semantic chunking and late chunking
Structure-aware splitting plus parent expansion handles most technical corpora cleanly. Reach for heavier splitters only when labeled errors reveal a specific failure:
| Observed failure | Technique | What to verify |
|---|---|---|
| Long unstructured prose drifts across topics | Semantic boundary detection | Hard size cap and labeled recall vs. sentence splits |
| Short matched span misses caveats | Parent-child expansion | Deduplication, version match, and token budget |
| Pronouns depend on earlier paragraphs | Late chunking | Encoder token-state access and permission isolation |
Bennani and Moslonka observed that sentence-preserving splits matched semantic chunking up to ~5,000 tokens of retrieved context on Natural Questions.[13] Always benchmark the simpler structural baseline first.
Semantic chunking embeds adjacent sentences and proposes a split wherever cosine similarity drops below a tuned threshold (watch out for poorly calibrated thresholds that sever an exception from its rule). Late chunking solves cross-sentence coreference (such as a paper introducing "Rotary Position Embeddings (RoPE)" and later saying "the method"): Günther et al. run the full document through the transformer encoder first, then mean-pool contextual token states inside each chunk span.[16]

Keep three constraints in mind for late chunking:
- Vectors gain context, raw text does not: The stored chunk still reads
"the method", so the generator still needs parent expansion to name RoPE clearly. - Encoder requirements: You need access to token-level hidden states plus exact character-to-token offset alignment (unlike ColBERT late interaction, late chunking still stores a single pooled vector per chunk).[16]
- Permission isolation: Never encode public and restricted sections in the same transformer forward pass, because cross-token attention lets restricted text shape the public chunk's vector even if the restricted chunk is filtered out later.
Evaluate splitters at a fixed generation budget
The script below compares broken fixed windows against heading-aware sections using TfidfVectorizer cosine retrieval and a semantic-boundary check over technical paper sentences:
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
query = "idle SSE connection timeout seconds heartbeat"
required_phrases = ("sse connections", "90 seconds", "heartbeat")
configs = {
"broken_fixed": [
"Streaming timeout: close idle SSE connections after",
"90 seconds without heartbeat frames. Batch retention: expire JSONL outputs after 14 days.",
],
"heading_aware": [
"Streaming timeout\nClose idle SSE connections after 90 seconds without heartbeat frames.",
"Batch retention\nExpire completed JSONL output files after 14 days.",
],
}
for name, chunks in configs.items():
vec = TfidfVectorizer(stop_words="english")
mat = vec.fit_transform(chunks)
top_hit = chunks[int(np.argmax(cosine_similarity(vec.transform([query]), mat)[0]))]
answerable = all(p in top_hit.lower() for p in required_phrases)
print(f"{name:14} | answerable={answerable} | hit={top_hit.splitlines()[0]}")
# Semantic similarity drop between topic-coherent vs topic-shifted sentences
sentences = [
"Rotary position embeddings rotate query and key pairs by token index.",
"Rotary position embeddings preserve relative position inside query-key dot-product attention.",
"KV cache paging allocates fixed blocks to eliminate external memory fragmentation.",
]
s_vec = TfidfVectorizer(stop_words="english").fit_transform(sentences).toarray()
for i in range(len(sentences) - 1):
sim = float(cosine_similarity(s_vec[i:i + 1], s_vec[i + 1:i + 2])[0, 0])
action = "split" if sim < 0.15 else "keep"
print(f"boundary {i}->{i + 1}: cosine={sim:.2f} -> {action}")
assert not all(p in configs["broken_fixed"][0].lower() for p in required_phrases)
assert all(p in configs["heading_aware"][0].lower() for p in required_phrases)broken_fixed | answerable=False | hit=Streaming timeout: close idle SSE connections after
heading_aware | answerable=True | hit=Streaming timeout
boundary 0->1: cosine=0.41 -> keep
boundary 1->2: cosine=0.00 -> splitProduction chunking checklist
| Decision | Default starting point | What to check |
|---|---|---|
| Primary splitter | Heading- and table-aware splitting with recursive fallback | Answerable-chunk rate on labeled queries |
| Token budget | Measure full embedded string (heading + body + special tokens) with embedder tokenizer | Zero silent truncation |
| Tables & code | Repeat column headers on row splits; keep fenced blocks intact | Exact-value and API-parameter queries |
| Overlap | Off for complete sections; benchmark on prose fallbacks | Token inflation vs. recall lift |
| Metadata | source_id, locator, heading, version, SHA-256 checksum | Verbatim citations back to normalized spans |
| Advanced splitters | Parent expansion first; semantic/late chunking only on measured misses | Fair comparison at a fixed generation token budget |