惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
H
Hacker News: Front Page
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
AWS News Blog
AWS News Blog
Spread Privacy
Spread Privacy
S
Schneier on Security
The Hacker News
The Hacker News
Cyberwarzone
Cyberwarzone
T
Tenable Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Tailwind CSS Blog
S
Secure Thoughts
N
Netflix TechBlog - Medium
T
The Exploit Database - CXSecurity.com
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Help Net Security
Help Net Security
K
Kaspersky official blog
Google Online Security Blog
Google Online Security Blog
L
LangChain Blog
Martin Fowler
Martin Fowler
L
LINUX DO - 热门话题
Hacker News: Ask HN
Hacker News: Ask HN
www.infosecurity-magazine.com
www.infosecurity-magazine.com
有赞技术团队
有赞技术团队
P
Privacy International News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Recent Announcements
Recent Announcements
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
Recorded Future
Recorded Future
The Last Watchdog
The Last Watchdog
G
Google Developers Blog
T
Threatpost
小众软件
小众软件
S
Securelist
Recent Commits to openclaw:main
Recent Commits to openclaw:main
O
OpenAI News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Tokenizer-Aware Markdown Chunking That Doesn't Shred Tables
Gabriel Anha · 2026-04-28 · via DEV Community

Picture a support engineer asking a doc bot why a webhook retry is failing. The retriever returns half of a markdown table: the header row, two body rows, then a hard cut at exactly 512 tokens. The remaining four rows, including the one that lists 429 as the retry trigger, go to the next chunk. The generator answers confidently and wrong. A better embedder will not save you. A fancier reranker will not save you. The fix is a splitter that knows what a table is.

Fixed-size token chunking is the default in most RAG tutorials because it is one line of code and the chunk count is predictable. It is also the reason your retrieval looks fine on prose and falls apart on anything with structure. Tables get bisected, code blocks lose their opening fence, and a bulleted list will happily keep its first three items while orphaning the last four under a heading the retriever never sees again.

What follows is a tokenizer-aware splitter for markdown that respects structure and stays under a soft token budget. Python, tiktoken, no external chunking library.

The failure mode in one snippet

Here is the canonical fixed-size splitter every tutorial ships:

import tiktoken

enc = tiktoken.encoding_for_model("gpt-4o")

def fixed_chunks(text: str, size: int = 512) -> list[str]:
    tokens = enc.encode(text)
    return [
        enc.decode(tokens[i : i + size])
        for i in range(0, len(tokens), size)
    ]

Enter fullscreen mode Exit fullscreen mode

It cuts at token 512 regardless of what is there. If token 512 lands inside a | col1 | col2 | row, half the table goes to chunk N and half to chunk N+1. The retriever embeds two halves of one idea. Neither half answers the question on its own.

A February 2026 benchmark over 50 academic papers put recursive 512-token splitting at 69% retrieval accuracy and pure semantic chunking at 54%. The recursive strategy wins because it cuts at boundaries the document already provides. The splitter below extends that idea to markdown specifically, and counts tokens with the model's real tokenizer instead of characters.

Detect the structure first

Before splitting, parse the markdown into a flat list of blocks: headings, paragraphs, fenced code, tables, lists. Each block carries its level (for headings) and its raw text.

import re
from dataclasses import dataclass

@dataclass
class Block:
    kind: str   # h1..h6, para, code, table, list
    level: int  # heading level, else 0
    text: str

Enter fullscreen mode Exit fullscreen mode

Then a parser that walks line by line. It is small on purpose; it covers the markdown features that actually break naive splitters.

HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
FENCE = re.compile(r"^`{3}")
TABLE_ROW = re.compile(r"^\s*\|.*\|\s*$")
LIST_ITEM = re.compile(r"^\s*([-*+]|\d+\.)\s+")

def parse(md: str) -> list[Block]:
    lines = md.splitlines()
    blocks: list[Block] = []
    i = 0
    while i < len(lines):
        ln = lines[i]
        if m := HEADING.match(ln):
            lvl = len(m.group(1))
            blocks.append(Block(f"h{lvl}", lvl, ln))
            i += 1
        elif FENCE.match(ln):
            i = _consume_code(lines, i, blocks)
        elif TABLE_ROW.match(ln):
            i = _consume_table(lines, i, blocks)
        elif LIST_ITEM.match(ln):
            i = _consume_list(lines, i, blocks)
        elif ln.strip() == "":
            i += 1
        else:
            i = _consume_paragraph(lines, i, blocks)
    return blocks

Enter fullscreen mode Exit fullscreen mode

The _consume_* helpers each accumulate their kind of block until the run ends, then append a single Block and return the next index. The point: a table is one atomic block, a fenced code section is one atomic block, and a list is one atomic block. The splitter never gets the chance to cut inside them.

Now wrap tiktoken so you can ask any block for its token count once and cache it.

import tiktoken

ENC = tiktoken.encoding_for_model("gpt-4o")

def n_tokens(text: str) -> int:
    return len(ENC.encode(text))

Enter fullscreen mode Exit fullscreen mode

For a real corpus, cache n_tokens(block.text) on the block when you parse. Re-encoding the same string repeatedly is the slow part of every naive token splitter.

A soft budget means: aim for target tokens per chunk, allow up to hard_max, never go past hard_max. For embedding models with 512-token windows, target=480 and hard_max=512 works. For long-context embedders like text-embedding-3-large (8191 tokens), target=800 and hard_max=1024 matches what most production RAG systems ship.

Greedy pack with priority splits

The packing loop is the heart of it. Iterate blocks. Add to the current chunk if it fits the target. If a single block is larger than hard_max, recursively split that block by priority: paragraph, then sentence, then word. Headings always stick to the next block so a section title never strands itself.

def pack(
    blocks: list[Block],
    target: int = 480,
    hard_max: int = 512,
) -> list[str]:
    chunks: list[str] = []
    buf: list[Block] = []
    buf_tokens = 0

    def flush():
        nonlocal buf, buf_tokens
        if buf:
            chunks.append("\n\n".join(b.text for b in buf))
            buf, buf_tokens = [], 0

    for blk in blocks:
        bt = n_tokens(blk.text)
        if bt > hard_max:
            flush()
            for piece in split_oversize(blk, hard_max):
                chunks.append(piece)
            continue
        if buf_tokens + bt > target and buf_tokens > 0:
            flush()
        buf.append(blk)
        buf_tokens += bt
    flush()
    return chunks

Enter fullscreen mode Exit fullscreen mode

Two things matter here. First, oversize blocks bypass the buffer entirely; they own their own chunks. Second, the target check fires only when the buffer is non-empty, so a block exactly at target still lands in a chunk on its own rather than triggering an empty flush.

A 700-token paragraph still needs to fit somewhere. Walk the priority ladder: split by H3 sub-headings if the block came from a long heading section, then by paragraph (\n\n), then by sentence (regex on [.!?]\s+), then by word as a last resort. Stop at the first ladder rung that produces pieces under hard_max.

SENTENCE = re.compile(r"(?<=[.!?])\s+")

def split_oversize(blk: Block, hard_max: int) -> list[str]:
    if blk.kind == "code":
        return _split_code(blk.text, hard_max)
    parts = blk.text.split("\n\n")
    if max(n_tokens(p) for p in parts) <= hard_max:
        return _greedy_join(parts, hard_max)
    parts = SENTENCE.split(blk.text)
    if max(n_tokens(p) for p in parts) <= hard_max:
        return _greedy_join(parts, hard_max)
    return _split_by_tokens(blk.text, hard_max)

Enter fullscreen mode Exit fullscreen mode

Code blocks deserve their own splitter because you want to keep the fence and language tag on each piece. _split_code re-emits the opening python fence at the top of every fragment so the chunk is still valid markdown when the retriever returns it. _split_by_tokens is the last-resort tiktoken-windowed fallback.

The _greedy_join helper packs sub-pieces back up to hard_max so you do not over-fragment. A paragraph that splits into eight sentences of 50 tokens each becomes one chunk of 400 tokens, not eight chunks of 50.

Boundary overlap, not token overlap

Most splitters overlap by N tokens. That copies a slice of arbitrary mid-sentence text into the next chunk. With structured blocks, overlap by boundary instead: the last heading and the last full sentence of chunk N become the lead of chunk N+1.

def with_overlap(chunks: list[str]) -> list[str]:
    out = [chunks[0]]
    for i in range(1, len(chunks)):
        prev_tail = _last_heading_and_sentence(chunks[i - 1])
        out.append(f"{prev_tail}\n\n{chunks[i]}")
    return out

Enter fullscreen mode Exit fullscreen mode

_last_heading_and_sentence scans the previous chunk for the most recent line starting with # and the last sentence in the trailing paragraph, joins them, caps the overlap at ~50 tokens, and returns the string. The retriever now gets a reminder of what section a chunk came from without copying noise.

This is the move that recovers the table-half failure from the opener. Even if a giant table forces a split, chunk N+1 starts with the H2 it sits under and the table's header row, so the embedding still says "this chunk is about webhook retries."

Putting it together

The full pipeline, end to end:

def chunk_markdown(
    md: str,
    target: int = 480,
    hard_max: int = 512,
) -> list[str]:
    blocks = parse(md)
    raw = pack(blocks, target, hard_max)
    return with_overlap(raw)

Enter fullscreen mode Exit fullscreen mode

Three calls. Parse, pack, overlap. Run it on a doc set and inspect the boundaries: every chunk should start at a heading, a paragraph break, or an overlap line carrying the previous heading. None should start mid-sentence. None should contain half a table. None should leave a code fence unclosed.

A small sanity check pays off in production:

FENCE_MARK = "`" * 3

def audit(chunks: list[str]) -> None:
    for i, c in enumerate(chunks):
        if c.count(FENCE_MARK) % 2 != 0:
            raise ValueError(f"chunk {i}: unbalanced fence")
        toks = n_tokens(c)
        if toks > 600:
            raise ValueError(f"chunk {i}: budget {toks}")

Enter fullscreen mode Exit fullscreen mode

Add this to your ingest pipeline. Catching the unbalanced-fence case once will save you a confused weekend later.

Fixed-size token splitting only looks good on benchmarks built from research-paper PDFs without tables, code, or nested lists, and real corpora rarely cooperate. Once the splitter respects H2/H3, paragraphs, sentences, and atomic blocks under a soft token budget with boundary overlap, the retrieval numbers move on their own and the per-query cost stays at zero. Drop it into your ingest pipeline next sprint, run your eval set against the new chunks, and spend the rest of the quarter on the parts of the stack that actually need an LLM.


If this was useful

The chunking chapter of the RAG Pocket Guide goes deeper on token-aware splitters, including the budget-vs-recall tradeoff per embedding model, how to handle PDFs with extracted layout, and the eval rig for catching chunking regressions before they hit prod. If you are tuning a real corpus, it is the chapter to start at.

RAG Pocket Guide: Retrieval, Chunking, and Reranking Patterns for Production