RAG 7 min read

Validate Markdown Before Ingesting It Into a RAG Index

Validate extracted Markdown before it enters a RAG index.

(Updated: ) • 1,265 words

A page can look readable and still be missing the one table your RAG answer needs. Check the extracted document before chunking it. Keep its source address and retrieval time, name the content that must survive, and quarantine a failed extraction instead of silently indexing what is left.

The example below makes that admission decision locally. It does not fetch a page, choose an extraction service, or measure an LLM’s answer accuracy.

Choose the checks from the source, before reading the output

Start with a source you are allowed to inspect. For this fixture, the important content is a retry-policy heading, a delay with its unit, a table row and a Python statement. These are invented test inputs, not observations from a vendor test or a customer deployment.

Sample What to verify against the source Failure to keep visible
Static article Required paragraph and its source identity A readable summary has dropped the supporting passage
JavaScript page The content visible after the permitted page state loads The output contains a shell rather than the required content
Table or code reference Required rows, units and code statements The output has preserved a heading but lost the detail

Write the required checks before examining the extractor’s result. Otherwise it is easy to make a test pass by checking only the content that happened to survive. A literal check is useful for a known regression; it does not establish that a table’s columns are correctly associated or that a paraphrase preserves the meaning.

An admission function with an explicit failure record

Save this as admission.py. It uses the Python standard library. The local policy requires an HTTP or HTTPS source address, a retrieval timestamp with a timezone, nonempty Markdown and named required literals. Invalid check configuration raises an error so a missing test specification cannot become an accepted document.

The fence check handles top-level backtick and tilde fences, including longer fences that contain shorter markers. It is deliberately narrower than a Markdown parser. CommonMark allows an unclosed fence to continue to the end of a document; this ingestion policy quarantines that case as a possible truncation. Fences inside list or blockquote containers, heading hierarchy and table semantics need a parser or source review.

import re
from datetime import datetime
from hashlib import sha256
from urllib.parse import urlsplit


def has_unclosed_fence(text):
    opened = None
    for line in text.splitlines():
        if opened:
            char, width = opened
            closing = r" {0,3}" + re.escape(char) + "{" + str(width) + r",}[ \t]*"
            if re.fullmatch(closing, line):
                opened = None
            continue
        match = re.match(r"^ {0,3}(`{3,}|~{3,})(.*)$", line)
        if match:
            marker, info = match.groups()
            if marker[0] == "`" and "`" in info:
                continue
            opened = marker[0], len(marker)
    return opened is not None


def admit_source(record, required):
    if not isinstance(required, dict) or not required or any(
        not isinstance(k, str) or not k.strip()
        or not isinstance(v, str) or not v.strip()
        for k, v in required.items()
    ):
        raise ValueError("required must name nonempty, source-chosen literals")
    if not isinstance(record, dict):
        return {"source_url": None, "retrieved_at": None, "sha256": None,
                "disposition": "quarantine", "failures": ["record_type"]}

    failures = []
    url, accessed = record.get("source_url"), record.get("retrieved_at")
    try:
        parsed = urlsplit(url) if isinstance(url, str) else None
        if parsed:
            parsed.port  # Trigger urllib's invalid-port validation.
        valid_url = parsed and parsed.scheme in {"https", "http"} and parsed.hostname
        if not valid_url or parsed.username or parsed.password:
            failures.append("source_url")
    except ValueError:
        failures.append("source_url")
    try:
        stamp = datetime.fromisoformat(accessed.replace("Z", "+00:00"))
        if stamp.utcoffset() is None:
            failures.append("retrieved_at_timezone")
    except (AttributeError, TypeError, ValueError):
        failures.append("retrieved_at")

    text = record.get("markdown")
    if not isinstance(text, str) or not text.strip():
        failures.append("empty_markdown")
        digest = None
    else:
        digest = sha256(text.encode("utf-8")).hexdigest()
        failures.extend("missing:" + name for name, literal in required.items()
                        if literal not in text)
        if has_unclosed_fence(text):
            failures.append("unclosed_top_level_fence")
    return {"source_url": url, "retrieved_at": accessed, "sha256": digest,
            "disposition": "quarantine" if failures else "accept",
            "failures": failures}

The returned hash identifies the exact UTF-8 Markdown candidate. It is not a hash of the original HTML and does not prove that the content is true, permitted to store or still current. The address check also does not make a URL safe to fetch; network access policy belongs before the HTTP request.

Delete a required row and inspect the result

Save the following beside it as fixture.py, then run python fixture.py. The timestamp is part of the synthetic input. The function checks its format and timezone; it does not impose a freshness deadline.

from admission import admit_source

markdown = """# Retry policy

The delay is 5 seconds.

| Setting | Value |
| --- | --- |
| Delay | 5 seconds |

```python
print("retry")
```
"""
required = {"heading": "# Retry policy", "unit": "5 seconds",
            "table_row": "| Delay | 5 seconds |", "code": 'print("retry")'}
record = {"source_url": "https://example.org/retry-policy",
          "retrieved_at": "2026-11-21T12:00:00+00:00", "markdown": markdown}

intact = admit_source(record, required)
damaged = admit_source({**record, "markdown": markdown.replace(
    "| Delay | 5 seconds |", "")}, required)
assert intact["disposition"] == "accept"
assert damaged["failures"] == ["missing:table_row"]
print(intact["disposition"])
print(damaged["disposition"], damaged["failures"])

The intact input prints accept. Removing the row prints quarantine ['missing:table_row'], even though the document still contains the same delay in a paragraph. That is why the table requirement is separate from the unit requirement.

Try removing the final fence, clearing the Markdown and dropping the timestamp. Also try a four-backtick code fence containing three literal backticks: it must not be rejected just because a shorter marker appears in the code. Keep these cases with the input and expected failure names when changing the extraction workflow.

Keep extraction failure separate from content loss

Before calling this function, check the HTTP result, provider business status and returned field shape. In the documented SearchCans Reader response, the candidate text is data.markdown. A successful response envelope is not proof that every required passage survived. A failed request should remain a request failure rather than being converted into an empty accepted page.

Store the source URL, retrieval time, candidate hash, extractor settings, check version and failed requirement names together. Preserve the inspected source or an approved reference snapshot when review requires it, subject to your access and retention policy. Retry only when the failure and that policy justify another request.

Accepting a revision does not replace the old index

After acceptance, hand the identified revision to the chunking and storage layer. Hash comparison can tell you that bytes changed; it cannot remove old chunks or make a database update atomic. Use version replacement and tombstone handling for that separate storage task.

For the earlier conversion step, use the Python URL-to-Markdown implementation. To compare extraction services, use the API selection checklist. Parsing Markdown tables and fenced code is a separate concern covered in the Markdown parsing guide.

Syntax references: CommonMark fenced code blocks and Python’s datetime parsing reference.

Tags:

RAG LLM Markdown Token Optimization AI Development Reader API
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.