A visual guide to RAG chunking

Chunks that keep
their source.

The chunker packs parse JSON into token-bounded, section-aware units — on CPU, deterministically, without calling the model again.

Sections in, chunks outFig. 01
Authored document units pack into token-bounded chunks that keep section paths and source spans On the left, document units carry token counts; a table is marked protected. On the right, three chunks each stay under a 512 token budget, keep their section path, and reference source spans like p1:b4. UNITS § title · 40t text · 180t text · 220t table · 300tPROTECTED text · 150t text · 90t authoring token counts, not tokenizer output max_tokens 512 chunk 0 · 440t §1 · p1:b1–b3 title + 2 paragraphs chunk 1 · 300t protected table · p1:b4 never split chunk 2 · 240t §1 · p1:b5–b6 closing paragraphs deterministic DP packing · CPU same input + options → same bytes
Authored sketch. Real token counts come from the PaddleOCR tokenizer; the section title repeated into chunks 1 and 2 is not drawn.
01 / The big picture

A budget. Sections.
Protected units.

Chunking is packing under three rules: every chunk stays inside a token budget, chunks keep their section context, and protected units never split.

THE TOKEN BUDGET

max_tokens is explicit.

Chunking never runs without an explicit options.max_tokens. Token counts come from the local PaddleOCR tokenizer on CPU — the same counting every request.

Missing budget returns an actionable 422, not a guess.
THE SECTION AWARENESS

Chunks carry their context.

Each chunk keeps its section_id, section title and section_path, plus repeated titles and headers inside its token count. A chunk answers "which part of the document" on its own.

Provenance — source_spans point at p{page}:b{block_id}.
THE PROTECTED UNITS

Tables never tear.

preserve_tables and preserve_code_blocks keep those units whole. In strict mode a protected unit over budget fails atomically with a 422 conflict instead of being split.

Atomic — no partial chunks escape on a conflict.
Deterministic by design

Same parse JSON plus same options produce byte-identical chunks: deterministic dynamic-programming packing and canonical RFC 8785 hashes (source_fingerprint, policy_hash). Chunker version structural-dp-v1.1.

Pack a document yourself
02 / Follow one parse

From JSON
to packed chunks.

Follow a parsed document through the chunker. Each stage shows what the CPU-side pipeline contributes — no GPU is involved.

Inside the chunkerReady when you are
01 / Two doors, one input

Start from
parse JSON.

/chunk takes a complete /parse JSON — pages, blocks, warnings — and never touches the GPU. /parse/chunks parses a document and chunks it in one request; the MCP tool checks model health before calling it.

ocr-api · /chunk and /parse/chunks
Prefer saved JSON: rechunking existing output costs no inference.
Existing JSONPOST /chunk
Document filePOST /parse/chunks
Agentocr_create_rag_chunks
Complete parse JSONpages[] · blocks[] · warnings[]
INPUT

Structural chunking is opt-in: /parse never runs this chunker; its optional json_rag flag produces a different, per-block export.

02 / Blocks become units

Sections give
the structure.

The chunker maps blocks into units: body text, section titles, tables, code and formulas. Section titles open and close the hierarchy — each unit knows which section it belongs to.

ocrserver/chunking · unit building
A unit is the smallest piece the packer may place — tables stay whole.
u1section_title — “Results”opens §1
u2text — two paragraphs§1
u3table — measurements§1 · protected
u4text — discussion§1
u5section_title — “Appendix”opens §A

Illustrative units. Unit roles: body, section_title, table_cell, code, formula.

03 / Measure everything

The tokenizer
sets the ruler.

Every unit is counted with the local PaddleOCR-VL tokenizer — including repeated section titles and table headers the packer may add. options.max_tokens is required; nothing is estimated by characters.

ocrserver/chunking · exact token counts
Token counts include repeated titles and headers — only the PaddleOCR tokenizer counts.
The explicit optionsoptions
max_tokens
required · 1–32768
strictly
true by default
overlap_tokens
0 by default · < max_tokens
protection
preserve_tables · preserve_code_blocks
Units with real countstokenizer output, not estimates
MEASURED

Option defaults from the shipped schema. Missing max_tokens → 422.

04 / Pack the budget

DP packing,
not first-fit.

A deterministic dynamic-programming packer places units under the budget — it looks ahead instead of greedily filling. Splittable text may divide at boundaries; protected tables and code stay whole or, in strict mode, fail the whole request.

ocrserver/chunking · packing.py
Same input, same options, same bytes — every time.

▤ Units in

Measured units in document order, section-aware

⌗ Chunks out

Token-bounded chunks under max_tokens. A strict protected overflow returns one actionable 422 — never a torn table.

Illustrative outcome. The real packer is deterministic DP, not a greedy fill.

05 / Keep the address

Overlap and
provenance.

overlap_tokens is a ceiling: when the previous chunk in the same section ends in prose, a suffix of at most that many tokens is repeated at the start of the next chunk and counted inside the budget. Every chunk records source_spans (p{page}:b{block_id} with character ranges) and context_spans for repeated titles, headers and overlap.

ocrserver/chunking · overlap.py and provenance.py
A chunk can always point back at the exact blocks and character ranges it came from.
c1source_spans → p1:b4 [0..212]provenance
c1context_spans → section_title “Results”context
c2context_spans → overlap of c1 · 40toverlap
c2source_spans → p1:b5 [0..96], p2:b1 [0..48]provenance

Illustrative spans. Roles: section_title, overlap, table_header, table_coordinates, separator, code_fence.

06 / The normative output

One JSON.
Verifiable.

The response is {"chunks": […]} — each chunk carries id, text, token_count and its provenance. Canonical RFC 8785 serialization feeds source_fingerprint and policy_hash, and chunker_version names the algorithm.

ocrserver/chunking · rag.schema.json
A closed schema: the fields below are the contract, nothing else is added.
normative output{"chunks": […]}
One chunk · illustrative
{"id":1,"text":"…","token_count":300,
 "section":"Results","section_id":"s:p1:b1",
 "source_spans":[{"source_key":"p1:b4"}],
 "chunker_version":"structural-dp-v1.1"}
Closed schema · v1.1canonical hashes for comparison

Full field list in the schema section below.

You control the pace. Nothing plays automatically.Illustrative workflow · no requests are sent
Prefer to read? The chunking in six sentences
  1. Input. /chunk reuses complete parse JSON on CPU; /parse/chunks parses a document and chunks it in one request.
  2. Units. Blocks become section-aware units — body text, titles, tables, code and formulas.
  3. Budget. The local PaddleOCR tokenizer measures every unit; an explicit options.max_tokens is required.
  4. Packing. Deterministic dynamic programming places units under the budget; protected tables and code never split.
  5. Provenance. Optional overlap is counted inside the budget, and every chunk records source and context spans.
  6. Output. The result is one closed-schema chunks list with canonical fingerprints — byte-identical for identical input and options.
03 / Budget lab

Change the budget.
Watch the packing.

Slide the token budget over an authored document. A protected table never splits — under a small budget it overflows into a chunk of its own.

Packed result, illustratedauthored counts

A report under a 256-token budget.

4 chunks at 256 tokens

    The lab uses a simple greedy fill to illustrate budgets — the service uses deterministic dynamic-programming packing and exact PaddleOCR tokenizer counts, so real boundaries can differ.

    04 / The chunk contract

    A closed schema.
    No surprises.

    The normative output is defined by ocrserver/chunking/rag.schema.json — additionalProperties is false at every level. These are the real fields.

    Top level

    {"chunks": […]}

    One property only: chunks, an array with at least one entry. Nothing else is allowed at the root.

    Required — chunks. Closed object.
    Every chunk

    Identity and text

    id, text and token_count are always present. Optional but common: page, pages, section_id, section, section_path, block_types, source_id, lang, diagnostics, document_context.

    Always — id, text, token_count.
    Every chunk

    Provenance and context

    source_spans address real blocks (source_key shaped p{page}:b{block}, with page, block_index, type, bbox, polygon, character start/end/text_start/text_end, and a role of body, section_title, table_cell, code or formula). context_spans record repeated titles, headers and overlap; page_context, assets and relations carry the rest.

    Traceable — every chunk points back at its blocks.
    Every chunk

    Integrity and overflow

    overflow/overflow_tokens/overflow_reason (protected_table | protected_code) report a protected unit over budget, and overlap_token_count is 0 on overflow chunks. source_fingerprint and policy_hash are 64-hex canonical digests; tokenizer records the model repo, snapshot revision, tokenizer.json SHA-256 and tokenizers library version; chunker_version is the constant structural-dp-v1.1.

    Verifiable — compare hashes instead of diffing text.

    Options the caller supplies: max_tokens (required), strictly, preserve_tables, preserve_code_blocks, overlap_tokens (< max_tokens), marginal_policy (metadata|text), table_header_policy (declared|first_row|none), metadata_fields. Defaults: strictly, preserve_tables and preserve_code_blocks true; overlap_tokens 0; marginal_policy metadata; table_header_policy declared; metadata_fields every optional field; max_tokens is also capped by OCR_CHUNK_MAX_TOKENS. Full definitions: rag.schema.json ↗.

    05 / Two routes, one contract

    Choose the door
    that fits the input.

    Both routes share the same options and output schema. They differ only in what you hand over.

    POST /chunk · no GPU

    Chunk existing JSON

    Send a complete /parse result as parsed_document with explicit options.max_tokens. No model health check, no inference — only tokenizer counting and packing on CPU. accept_truncated applies only here; max_pages/dpi do not. The tokenizer is loaded from the mounted model cache — without it the route answers 503 tokenizer_unavailable. In archive-only mode (--archive-only / -ArchiveOnly) /chunk, stored RAG refinement and splitting keep working from that same cache, while /parse/chunks answers 503 ocr_disabled_archive_only. /chunk never archives; both routes accept optional source_id and lang labels.

    Fastest path — rechunk the same parse as often as needed.
    POST /parse/chunks · GPU

    Parse and chunk at once

    Send a document source plus the same options. The API parses on the GPU, then chunks the result; it runs no health preflight of its own, so check /health first (the MCP tool does this for you). A failure after inference may require parsing again — never retry a timed-out POST automatically. Without an explicit max_pages it refuses a document longer than the server page cap instead of chunking a silent prefix; with storage enabled it archives its result (kind parse-chunks).

    One request — document in, chunk JSON out.
    MCP · agent path

    ocr_create_rag_chunks

    The MCP tool picks the route for you: parsed_document → /chunk; a document source → /parse/chunks. The ocr_prepare_rag prompt walks an agent through preferring saved JSON and presenting budget conflicts instead of silently weakening protection.

    Strict overflow fails atomically — change budget or protection only with intent.
    HTTP 422 · budget conflict

    An actionable refusal

    Missing options.max_tokens, overlap_tokens ≥ max_tokens, or a protected unit that cannot fit in strict mode all return structured 422s. The answer is a bigger budget or an explicit policy change — never an automatic retry. Other 422 codes: incomplete_ocr, tokenizer_mismatch, protected_block_exceeds_budget; expect 413 for input/output limits, 503 with Retry-After for capacity or an unloadable tokenizer, and 504 for the chunk deadline.

    Fail closed — no partial chunk lists.
    json_rag · on /parse

    A different export

    json_rag=true on /parse returns one Qdrant-ready item per markdown-visible block — id, text, type, token_count, document, page — with running heads, page labels, footnotes, asides and equation numbers attached as plain string fields, plus document-level metadata. No token budget, no packing: it is not this chunker's output.

    Per block — the file the console's RAG tab refines.
    Where to call

    Both routes live on the OCR API; the launcher prints the current host URLs. The console's RAG tab is a different tool: it refines json_rag.json files saved in Storage with best-effort token targets through POST /storage/rag/refine and POST /storage/rag/split (preview only) — the MCP tools ocr_refine_rag_storage and ocr_split_rag_group. Its gestures are Preview group, Cut, Merge with previous, Merge with next and Undo; the original json_rag.json is never overwritten, each save adds a json_rag_<job>_<seq>.json beside it.

    Windows · PowerShell 7
    pwsh .\stack.ps1 urls

    Linux / macOS · Bash
    bash stack.sh urls

    06 / Practical trade-offs

    Tune the contract,
    not the model.

    Chunking options are explicit choices with visible consequences. Everything is deterministic — an option change you can re-run is a safe experiment.

    Dial / Size

    max_tokens and overlap

    Larger budgets mean fewer, wider chunks; smaller budgets give finer retrieval granularity. overlap_tokens repeats at most that many tokens of prose across a boundary inside the same section and is counted inside the budget — it must stay below max_tokens.

    Dial / Protection

    preserve_tables, preserve_code_blocks, strictly

    Protection keeps tables and code whole; strictly makes an over-budget protected unit a 422 instead of an overflow chunk. Relax either only with intent — a split table is silent evidence damage.

    Dial / Margins & metadata

    marginal_policy and friends

    Marginal = header, footer, printed page number and header/footer images. marginal_policy metadata keeps them in page_context (headers, footers, page_labels, marginal_assets); text folds them into the section body. Footnotes are body text with footnote_reference relations. table_header_policy applies only when preserve_tables is off and a table is split by rows: declared uses the table's header cells, first_row assumes the first row, none repeats nothing. metadata_fields selects exported fields — id, text and token_count always ship.

    07 / Glossary & further reading

    A little less jargon.
    One level deeper.

    Terms this page uses, and the owning documents that define the exact behavior.

    What is a chunk?

    A token-bounded, section-aware unit of document text produced by the deterministic CPU chunker. Each chunk carries its text, its exact token count and the spans it was built from.

    What is max_tokens?

    The explicit token ceiling every chunking request must supply as options.max_tokens (1–32768). Without it the request is refused — there is no implicit default budget.

    Which tokenizer counts?

    The local PaddleOCR-VL tokenizer, on CPU inside ocr-api. Counts include repeated titles and headers the packer adds; no other tokenizer's count is interchangeable.

    What is a protected unit?

    A unit covered by preserve_tables or preserve_code_blocks. It never splits. In strict mode an over-budget protected unit fails the request; in permissive mode it becomes an overflow chunk marked with overflow, overflow_tokens and a reason.

    What is overlap?

    A repeated prose tail of the previous chunk at the start of the next, at most overlap_tokens long and counted inside the budget; it is skipped across sections, around protected overflow chunks and whenever no suffix fits. Overlap spans appear as context_spans with role overlap; it must stay below max_tokens.

    What is a source span?

    A chunk's address back to the document: source_key like p1:b4, page and block index, the block type, geometry, and character start/end ranges with a unit role.

    What are the fingerprints?

    source_fingerprint and policy_hash are 64-hex digests over canonical (RFC 8785) serializations — compare them to prove two chunk runs used the same input and options.

    What does deterministic mean here?

    The same parse JSON plus the same options always produce the same chunk bytes — packing is dynamic programming, not sampling or model output. chunker_version names the algorithm that produced them.

    Go one level deeper.

    Checked against the repository's owning references. This page is an offline explanation; it does not inspect your machine, connect to your services, or change their configuration.

    08 / Questions

    Read a conflict
    as an answer.

    Match each chunking surprise to the option or field that explains it.

    Why does chunking refuse without max_tokens?

    The budget is an explicit contract, not a guess. options.max_tokens is required on every request; its absence is a structured 422. Pick a budget that matches your embedding target, then re-run — the result is deterministic.

    A table exceeded my budget — why did the request fail?

    In strict mode a protected table or code unit that cannot fit max_tokens fails atomically rather than splitting. Raise the budget, or switch strictly off to receive a flagged overflow chunk instead. Change protection only with intent.

    My overlap request was rejected — why?

    overlap_tokens must stay below max_tokens: overlap is counted inside the budget, so an overlap equal to the budget would leave no room for new content. Reduce overlap or raise the budget.

    Do I need to parse again to change the budget?

    No. Keep the complete structured parse JSON and call /chunk (or ocr_create_rag_chunks with parsed_document) — that path needs no GPU inference. Keep accept_truncated in mind when the parse was truncated.

    A /parse/chunks call timed out — should I retry?

    Not automatically. That route performs real GPU inference first, so a blind retry may repeat the expensive work. Check service health, then decide; /chunk on existing JSON is always safe to re-run.

    09 / Keep going

    Read what
    you packed.

    Chunks are only as good as the parse they came from — go back one step.