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.
A visual guide to RAG chunking
The chunker packs parse JSON into token-bounded, section-aware units — on CPU, deterministically, without calling the model again.
Chunking is packing under three rules: every chunk stays inside a token budget, chunks keep their section context, and protected units never split.
Chunking never runs without an explicit options.max_tokens. Token counts come from the local PaddleOCR tokenizer on CPU — the same counting every request.
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.
source_spans point at p{page}:b{block_id}.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.
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.
Follow a parsed document through the chunker. Each stage shows what the CPU-side pipeline contributes — no GPU is involved.
/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.
Structural chunking is opt-in: /parse never runs this chunker; its optional json_rag flag produces a different, per-block export.
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 buildingIllustrative units. Unit roles: body, section_title, table_cell, code, formula.
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.
Option defaults from the shipped schema. Missing max_tokens → 422.
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.pyMeasured units in document order, section-aware
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.
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.
Illustrative spans. Roles: section_title, overlap, table_header, table_coordinates, separator, code_fence.
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.
{"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"}Full field list in the schema section below.
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.
Protected means whole. The table unit is flagged protected: it lands in exactly one chunk at every budget — its own overflow chunk when the budget is too small.
An authored example,
not a chunking run.
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.
The normative output is defined by ocrserver/chunking/rag.schema.json — additionalProperties is false at every level. These are the real fields.
One property only: chunks, an array with at least one entry. Nothing else is allowed at the root.
chunks. Closed object.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.
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.
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.
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 ↗.
Both routes share the same options and output schema. They differ only in what you hand over.
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.
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).
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.
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.
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.
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.
pwsh .\stack.ps1 urls
bash stack.sh urls
Chunking options are explicit choices with visible consequences. Everything is deterministic — an option change you can re-run is a safe experiment.
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.
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.
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.
Terms this page uses, and the owning documents that define the exact behavior.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Match each chunking surprise to the option or field that explains it.
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.
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.
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.
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.
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.
Chunks are only as good as the parse they came from — go back one step.
Layout, recognition, reading order — what a block actually is.
Read the pipeline guide ↗Launcher commands, storage profile and every environment variable.
Read the CLI guide ↗