Lab: Three Chunkers, One Corpus
Build a fixed-size chunker with overlap, a recursive splitter and a structure-aware Markdown chunker that all return character offsets, run them on the same four-page corpus and compare where their boundaries fall.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the corpus
- Step 2: Fixed-size windows with overlap
- Step 3: Recursive splitting
- Step 4: Structure-aware chunks with a heading path
- Step 5: Compare the three on the whole corpus
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Chunking
- Why Chunk Boundaries Matter Concept · 15 min
- Parsing Documents, Scans and Tables into Clean Text Worked example · 20 min
- Lab: Three Chunkers, One Corpus Lab · 25 min
- Stable IDs and Source Metadata Worked example · 15 min
- Measuring Chunking by Retrieval Recall Lab · 20 min
- Check: Choose a Chunking Strategy Knowledge check · 6 questions
What you will learn
- Apply fixed-size, recursive and structure-aware chunking with overlap, and attach a stable ID and source metadata to every chunk.
01. Goal and setup
In this lab you implement the three chunker families from the first lesson and run them on one documentation corpus. Every chunker returns character offsets into the source text instead of copies of it. That one design choice pays off twice later in the skill: lesson 4 attaches IDs and metadata to those offsets, and lesson 5 scores retrieval against labelled spans of the same source text. At the end you compare how many chunks each chunker makes, how big they are, and how often it cuts a line or a code block.
You need: Python 3.12 or later and two libraries, tiktoken to count tokens and markdown-it-py to parse Markdown (tested with tiktoken 0.14 and markdown-it-py 4.3). Sizes are counted in tokens of the o200k_base encoding, which stands in for your embedding model's tokenizer. The corpus is tiny, so the sizes are scaled down to match: 64 and 96 tokens here, where real documentation would use a few hundred.
chunk-lab/
├── make_corpus.py step 1: writes the four pages into corpus/
├── corpus/ install.md, configuration.md, retries.md, api.md
├── chunkers.py steps 2 to 4: three chunkers, built up in three parts
├── try_fixed.py step 2
├── try_recursive.py step 3
├── try_structure.py step 4
└── compare.py step 5mkdir chunk-lab && cd chunk-lab
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install tiktoken markdown-it-py02. Step 1: Create the corpus
The corpus is four pages of the Larkspur documentation from the previous lesson, as Markdown. Between them they hold headings at two levels, a settings table and two code samples, one of them with a blank line inside. Paragraphs are hard-wrapped at 80 characters, as in many real repositories, so a single line break does not end a paragraph. The script prints each page's size in tokens; tiktoken downloads the encoding file on first use and caches it.
"""Write the four-page Larkspur docs corpus into corpus/."""
from pathlib import Path
import tiktoken
PAGES = {
"install.md": """# Installing Larkspur
Larkspur is a job scheduler for small teams. It runs as one process and keeps
its state in a SQLite file.
## Requirements
Larkspur needs Python 3.11 or later and about 50 MB of disk space. It runs on
Linux and macOS. Windows is supported through WSL 2 only.
## Install with pip
```bash
# create an isolated environment first
python -m venv .venv
source .venv/bin/activate
pip install larkspur
```
After installing, run `larkspur doctor` to check the environment. It prints one
line per check and exits with code 1 if any check fails.
## Upgrading
Upgrade in place with `pip install --upgrade larkspur`. Version 3 changed the
state format, so stop the scheduler and run `larkspur migrate` once before you
start the new version. Skipping the migration leaves jobs stuck in the queued
state.
""",
"configuration.md": """# Configuration
Larkspur reads `larkspur.toml` from the working directory. Environment
variables override settings in the file.
## Workers
The `workers` setting controls how many jobs run at the same time. The default
is 4. Each worker is a separate process, so memory use grows with this number.
## Time zones
Schedules use UTC unless you set `timezone`. Daylight-saving changes can skip or
repeat a run between 01:00 and 03:00 local time, so schedule critical jobs
outside that window.
## Settings reference
| Setting | Default | Environment variable |
|---|---|---|
| workers | 4 | LARKSPUR_WORKERS |
| timezone | UTC | LARKSPUR_TZ |
| state_path | ./larkspur.db | LARKSPUR_STATE |
| log_level | info | LARKSPUR_LOG_LEVEL |
""",
"retries.md": """# Retries and failures
A job fails when it raises an exception or exits with a non-zero code.
## Retry policy
Failed jobs are retried up to 3 times by default. The delay doubles after each
attempt, starting at 10 seconds, so the retries happen after 10, 20 and 40
seconds. Set `max_retries = 0` on a job to turn retries off.
## Dead-letter queue
After the last retry, the job moves to the dead-letter queue. It stays there for
14 days and is then deleted. Run `larkspur dlq list` to see waiting jobs and
`larkspur dlq replay <job-id>` to run one again.
## Timeouts
A job that runs longer than its `timeout` is stopped and counts as failed. The
default timeout is 15 minutes.
""",
"api.md": """# HTTP API
The scheduler serves a small JSON API on port 8470.
## Authentication
Every request needs an `Authorization: Bearer` header with an API token. Create
tokens with `larkspur token create --name <name>`. A token is shown once and
cannot be retrieved later.
## Triggering a job
Send a POST request to `/jobs/<name>/runs` to start a job now. The response is
`202 Accepted` with the ID of the new run.
```python
import os
import httpx
# trigger the nightly report outside its schedule
response = httpx.post(
"http://localhost:8470/jobs/nightly-report/runs",
headers={"Authorization": f"Bearer {os.environ['LARKSPUR_TOKEN']}"},
)
print(response.status_code, response.json()["run_id"])
```
## Rate limits
Each token may make 60 requests per minute. Further requests get
`429 Too Many Requests` with a `Retry-After` header.
""",
}
enc = tiktoken.get_encoding("o200k_base")
Path("corpus").mkdir(exist_ok=True)
for name, text in PAGES.items():
Path("corpus", name).write_text(text, encoding="utf-8")
print(f"{name:<18} {len(enc.encode(text)):>4} tokens")python make_corpus.pyinstall.md 207 tokens
configuration.md 187 tokens
retries.md 178 tokens
api.md 210 tokens03. Step 2: Fixed-size windows with overlap
Create chunkers.py with the first part: a token counter, the Chunk record and the fixed-size chunker. The imports for all three parts are here at the top.
from dataclasses import dataclass
from typing import NamedTuple
import tiktoken
from markdown_it import MarkdownIt
ENC = tiktoken.get_encoding("o200k_base") # stand-in: use your embedding model's own
def ntokens(text: str) -> int:
return len(ENC.encode(text))
@dataclass(frozen=True)
class Chunk:
start: int # character offsets into the document: text[start:end]
end: int
headings: tuple[str, ...] = () # filled in by the structure-aware chunker
def fixed_chunks(text: str, size: int = 64, overlap: int = 16) -> list[Chunk]:
tokens = ENC.encode(text)
_, offsets = ENC.decode_with_offsets(tokens) # character where each token starts
offsets.append(len(text))
chunks = []
for i in range(0, len(tokens), size - overlap):
j = min(i + size, len(tokens))
chunks.append(Chunk(offsets[i], offsets[j]))
if j == len(tokens):
break
return chunksdecode_with_offsets() returns, for every token, the index of the character where it starts, so a window of tokens maps back to an exact character range. A window of size tokens starts every size - overlap tokens, and the loop stops after the window that reaches the end. A Chunk stores only offsets, plus a heading path that the structure-aware chunker will fill; text[c.start:c.end] gives its text. Try it on one page:
from pathlib import Path
from chunkers import fixed_chunks, ntokens
text = Path("corpus/retries.md").read_text(encoding="utf-8")
chunks = fixed_chunks(text, size=64, overlap=16)
print(len(chunks), "chunks, tokens:", [ntokens(text[c.start:c.end]) for c in chunks])
for c in chunks:
piece = text[c.start:c.end]
print(f"{c.start:>4}-{c.end:<4} {piece[:28]!r} ... {piece[-28:]!r}")python try_fixed.py4 chunks, tokens: [64, 64, 64, 34]
0-263 '# Retries and failures\n\nA jo' ... 'ries happen after 10, 20 and'
209-439 ' at 10 seconds, so the retri' ... '. It stays there for\n14 days'
372-605 ' the job moves to the dead-l' ... ' that runs longer than its `'
542-682 ' run one again.\n\n## Timeouts' ... 'ault timeout is 15 minutes.\n'The sizes are perfectly even, which is the whole appeal. Now read the boundaries. Chunk 1 ends at after 10, 20 and; the retry timings survive only because chunk 2 starts 16 tokens earlier (209 is less than 263: that is the overlap). Chunk 2 stops mid-sentence, right after It stays there for 14 days, and chunk 3 ends on the opening backtick of an inline code span. Every chunk after the first starts in the middle of a sentence.
04. Step 3: Recursive splitting
Append the second part to chunkers.py:
SEPARATORS = ["\n\n", "\n", ". ", " "] # paragraphs, lines, sentences, words
def pieces(text: str, start: int, end: int, size: int, seps: list[str]):
"""Cut text[start:end] into spans of at most `size` tokens, coarsest cut first."""
if ntokens(text[start:end]) <= size:
return [(start, end)]
if not seps: # nothing left to split on: fall back to token windows
return [(start + c.start, start + c.end)
for c in fixed_chunks(text[start:end], size, 0)]
spans, cut = [], start
while cut < end:
found = text.find(seps[0], cut, end)
stop = end if found == -1 else found + len(seps[0]) # keep the separator
spans += pieces(text, cut, stop, size, seps[1:])
cut = stop
return spans
def recursive_chunks(text: str, size: int = 64, overlap: int = 16,
seps: list[str] = SEPARATORS) -> list[Chunk]:
def tokens_in(window):
return ntokens(text[window[0][0]:window[-1][1]])
chunks, window = [], []
for span in pieces(text, 0, len(text), size, seps):
if window and tokens_in(window + [span]) > size:
chunks.append(Chunk(window[0][0], window[-1][1]))
# keep whole trailing pieces, up to `overlap` tokens, as the overlap
while window and (tokens_in(window) > overlap
or tokens_in(window + [span]) > size):
window.pop(0)
window.append(span)
if window:
chunks.append(Chunk(window[0][0], window[-1][1]))
return chunkspieces() keeps a span whole if it fits. Otherwise it cuts at every occurrence of the current separator, keeping the separator attached to the piece before it so that no character is lost, and sends any piece that is still too big to the next, finer separator. With no separator left it falls back to token windows. recursive_chunks() then packs consecutive pieces into chunks while they fit under size. When a chunk closes, the trailing whole pieces that fit within overlap tokens are carried into the next chunk, so overlap here is made of complete pieces and can come out smaller than requested, or even zero.
Copy try_fixed.py to try_recursive.py and change the two names, as below, then run it:
from pathlib import Path
from chunkers import recursive_chunks, ntokens
text = Path("corpus/retries.md").read_text(encoding="utf-8")
chunks = recursive_chunks(text, size=64, overlap=16)
print(len(chunks), "chunks, tokens:", [ntokens(text[c.start:c.end]) for c in chunks])
for c in chunks:
piece = text[c.start:c.end]
print(f"{c.start:>4}-{c.end:<4} {piece[:28]!r} ... {piece[-28:]!r}")python try_recursive.py4 chunks, tokens: [26, 64, 62, 30]
0-113 '# Retries and failures\n\nA jo' ... 'ero code.\n\n## Retry policy\n\n'
96-329 '## Retry policy\n\nFailed jobs' ... 'a job to turn retries off.\n\n'
329-559 '## Dead-letter queue\n\nAfter ' ... 'job-id>` to run one again.\n\n'
559-682 '## Timeouts\n\nA job that runs' ... 'ault timeout is 15 minutes.\n'Every chunk now starts at the beginning of a line, and the boundaries fall between paragraphs. Two weaknesses remain. The first chunk ends with the heading ## Retry policy, cut off from the text it introduces; the overlap repeats it at the start of chunk 2, but a search can still return chunk 1 for a question about retries and hand the model a heading with nothing under it. And the splitter has no idea that a blank line inside a code block is not a paragraph break. Step 5 catches it cutting the Python sample in api.md.
05. Step 4: Structure-aware chunks with a heading path
Append the third part:
MD = MarkdownIt("commonmark").enable("table")
KEEP_WHOLE = {"fence", "code_block", "table_open", "html_block"} # never split these
class Block(NamedTuple):
start: int
end: int
kind: str # markdown-it token type: heading_open, paragraph_open, fence ...
level: int # 1 to 6 for headings, 0 for every other block
title: str # the heading text, or ""
def blocks(text: str) -> list[Block]:
"""The top-level Markdown blocks of a document, with character offsets."""
line_starts = [0] + [i + 1 for i, ch in enumerate(text) if ch == "\n"]
line_starts.append(len(text))
tokens = MD.parse(text)
out = []
for i, tok in enumerate(tokens):
if tok.map and tok.level == 0: # an opening token of a top-level block
first, last = tok.map # line numbers, end exclusive
heading = tok.type == "heading_open"
out.append(Block(line_starts[first], line_starts[last], tok.type,
int(tok.tag[1]) if heading else 0,
tokens[i + 1].content if heading else ""))
return out
def structure_chunks(text: str, size: int = 128, max_level: int = 3) -> list[Chunk]:
sections, path = [], [] # sections: [(heading path, [Block, ...]), ...]
for b in blocks(text):
if 0 < b.level <= max_level:
path = path[:b.level - 1] + [b.title]
sections.append((tuple(path), []))
elif not sections:
sections.append(((), [])) # text before the first heading
sections[-1][1].append(b)
chunks = []
for heads, section in sections:
group = [] # whole blocks, packed while they fit
for b in section:
if group and ntokens(text[group[0].start:b.end]) > size:
chunks.append(Chunk(group[0].start, group[-1].end, heads))
group = []
if ntokens(text[b.start:b.end]) > size and b.kind not in KEEP_WHOLE:
# an oversized paragraph or list: split it recursively, no overlap
chunks += [Chunk(b.start + c.start, b.start + c.end, heads)
for c in recursive_chunks(text[b.start:b.end], size, 0)]
continue
group.append(b)
if group:
chunks.append(Chunk(group[0].start, group[-1].end, heads))
return chunks
def with_header(text: str, chunk: Chunk, site: str = "Larkspur docs") -> str:
"""The text to embed and index: the heading path as a header, then the chunk."""
return f"[{' > '.join((site, *chunk.headings))}]\n{text[chunk.start:chunk.end]}"How it works:
blocks()asks markdown-it-py for the top-level blocks of the page. Each opening token carriesmap, its range of source lines, andline_startsturns line numbers into character offsets. Because a real parser does the work, a#comment inside a code sample is never mistaken for a heading.structure_chunks()starts a new section at every heading down tomax_leveland keeps the heading path, such as('Retries and failures', 'Dead-letter queue').- Inside a section, whole blocks are packed while they fit. A block that is too big on its own is split recursively, unless it is a code block, a table or raw HTML: those stay whole even above the limit, because half a table or half a function is worse than one large chunk.
with_header()builds the text you will embed: the heading path in brackets, then the chunk.
from pathlib import Path
from chunkers import ntokens, structure_chunks, with_header
text = Path("corpus/retries.md").read_text(encoding="utf-8")
chunks = structure_chunks(text, size=64)
print(len(chunks), "chunks, tokens:", [ntokens(text[c.start:c.end]) for c in chunks])
for c in chunks:
print(f"{c.start:>4}-{c.end:<4} {c.headings}")
print()
print(with_header(text, chunks[2]))python try_structure.py4 chunks, tokens: [22, 64, 62, 30]
0-95 ('Retries and failures',)
96-328 ('Retries and failures', 'Retry policy')
329-558 ('Retries and failures', 'Dead-letter queue')
559-682 ('Retries and failures', 'Timeouts')
[Larkspur docs > Retries and failures > Dead-letter queue]
## Dead-letter queue
After the last retry, the job moves to the dead-letter queue. It stays there for
14 days and is then deleted. Run `larkspur dlq list` to see waiting jobs and
`larkspur dlq replay <job-id>` to run one again.One chunk per section, each tagged with its heading path, and no heading left dangling. The introduction is small, at 22 tokens: sections vary in size, which is the main cost of following the structure. The last block is what a retriever will see for the third chunk. The header names the product, the page and the section, so even It stays there for 14 days is now clearly about the dead-letter queue.
06. Step 5: Compare the three on the whole corpus
Run all three chunkers on all four pages with the same 96-token limit and count, for each: the chunks, their mean and largest size, how many start in the middle of a line, and how many contain an odd number of code-fence lines, which means they hold only part of a code block.
from pathlib import Path
from statistics import mean
from chunkers import fixed_chunks, ntokens, recursive_chunks, structure_chunks
SIZE = 96
CHUNKERS = {
"fixed": lambda text: fixed_chunks(text, SIZE, overlap=16),
"recursive": lambda text: recursive_chunks(text, SIZE, overlap=16),
"structure": lambda text: structure_chunks(text, SIZE),
}
docs = [p.read_text(encoding="utf-8") for p in sorted(Path("corpus").glob("*.md"))]
HEADER = ("chunker", "chunks", "mean", "max", "mid-line", "cut code")
print("{:<10} {:>6} {:>5} {:>4} {:>9} {:>9}".format(*HEADER))
for name, chunker in CHUNKERS.items():
sizes, mid_line, cut_code = [], 0, 0
for text in docs:
for c in chunker(text):
piece = text[c.start:c.end]
sizes.append(ntokens(piece))
mid_line += c.start > 0 and text[c.start - 1] != "\n"
cut_code += piece.count("```") % 2 # an odd number of fence lines
print(f"{name:<10} {len(sizes):>6} {mean(sizes):>5.0f} {max(sizes):>4} "
f"{mid_line:>9} {cut_code:>9}")python compare.pychunker chunks mean max mid-line cut code
fixed 12 76 96 8 4
recursive 12 69 92 0 1
structure 17 46 73 0 0- fixed gives the most even sizes, but 8 of its 12 chunks start mid-line and 4 cut through a code block.
- recursive never starts mid-line, but still cuts one code block, at the blank line inside the Python sample.
- structure never cuts a line or a code block. It makes more and smaller chunks (17, with a mean of 46 tokens), and its largest chunks are whole units such as the Python sample and the settings table.
None of these numbers tells you which chunker retrieves better. Even sizes, clean boundaries and intact code are means, not ends. Lesson 5 measures the end: whether the right text comes back for real questions.
07. Check your understanding
08. Apply it: stretch tasks
- Merge small sections. Change
structure_chunks()so that a section much smaller thansize(say under a third) is merged with the next section under the same parent heading, keeping the parent's path as the header. Runcompare.pyagain and see how the count and the mean move. - Realistic sizes on your docs. Run the three chunkers on your practice documentation set with a size of 300 to 500 tokens and an overlap of about 50 for the fixed and recursive ones. Extend
compare.pyto count chunks that contain table rows but not the table's header row. - Check against a library. Configure LangChain's
RecursiveCharacterTextSplitter(packagelangchain-text-splitters) with the same separators, a tiktoken-based length and the same size, and explain every boundary that differs fromrecursive_chunks().
09. Review prompt
Without looking back:
- How does
fixed_chunks()turn token windows into character ranges, and where does its overlap come from? - In
recursive_chunks(), why can the overlap be smaller than requested? - Name two things the structure-aware chunker does that the recursive one cannot, and the main cost of following structure.
- Which of the measures in step 5 would you use to choose a chunker, and what would you measure instead?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.