Search and contents

Chunking registry and the document type catalogue

How a document's text is split into chunks, and how a site says which kinds of document it has and how each is split. A site defines its document types in the document_types section of its configuration; the chunking registry is built from that catalogue when the configuration loads, so a type is chunked by its configured strategy with no Python registered.

This code only splits already-extracted plain text into chunks — turning a raw file (PDF, Word, a scanned image) into that text is the ingestion layer's job, and nothing here depends on a particular document-management system.

1. The catalogue

Each entry keeps everything about one kind of document together:

{
  "document_types": {
    "design_note": {
      "description": "Prose notes and rationale around a drawing; not the drawing",
      "case_record": false,
      "revisions": {"policy": "keep", "previous": "leave"},
      "strategy": {"name": "heading_sections", "heading_depth": 2, "min_chars": 150, "max_chars": 1200},
      "context": "{document_number} {title} rev {revision_label} — {heading_path}:",
      "identity": {"first_line": "^(?P<document_number>\\S+)\\s+(?P<title>.+)$"},
      "applicability": {}
    }
  }
}

Only strategy is required.

FieldMeaning
description Free text.
case_record true for a past case record (a deviation or nonconformance record); default false.
draft_claims true to have the Node also draft instruction claims from this type's documents for a person to confirm (Instruction claim drafting); default false. Only a strategy that puts a locator in every chunk (heading_sections, boundary_rules, or your own with stamps_locator=True) may be used with it; any other is refused when the configuration loads.
revisions How a new revision of a document is kept: {"policy": "replace"} (the default), or {"policy": "keep", "previous": "deactivate" or "leave"}. keep needs previous; replace does not take it.
require_effective_range true to refuse a newer revision of a kept document that carries no effective range; default false, which stores it with a warning (see A newer revision with no effective range). Only a type with revisions.policy keep may set it; any other is refused when the configuration loads.
strategy name plus that strategy's parameters (section 3).
context The text put before each chunk when it is embedded (section 4). Default {title}:.
identity How a title and document number are read from the text when the sender gave none (section 5).
applicability The scope an item of this type takes when it carries none of its own (an item that carries one, even an empty one, keeps it): any of product_id, mfg_order_id, effective_unit_from, effective_unit_to, effective_date_from, effective_date_to. Absent means everywhere.

A type's name is lower case letters, digits and underscores, starting with a letter. An intake item names its type with document_type; a blank one takes generic, and a name the catalogue does not define is refused.

The section is accepted when the Node also has a document_intake section. A Node with no document_types section uses the starter catalogue alone.

A newer revision with no effective range

A type that keeps each revision stores every revision as a document of its own, so its applicability has to say where it applies: a unit range, a date range or a Mfg Order. A product alone does not say which of the document's revisions governs. A newer revision (one that has an earlier revision of the same document on file) that arrives with none would apply at every date and compete with its successors, so:

  • By default it is stored, and the intake result and the Activity Log entry carry a warning that names the document and the revision (warning is no_effective_range, with base_document_id, revision_label and assumed_effective_from).
  • It is treated as applying from the day it arrived: that day is stored as its effective_date_from, so a question asked about an earlier date is not answered from it. An answer drawn from it ends with a Source note naming the revision and that date, whatever the model wrote.
  • Storing the same revision again keeps its first assumed start. Giving it a range of its own and storing it again (with overwrite) replaces the assumption.
  • With "require_effective_range": true the type refuses such a revision instead, naming the document and revision, and nothing is stored. The first revision of a document is never refused.

A type that replaces its revisions is not affected.

An older revision that has no range of its own yields to a newer one

A revision stored with no range, or with only an assumed start, has an open end, so it would answer beside its successor. To prevent that, when the Node answers a question (point-of-use retrieval, context given), it leaves out such an older revision whenever a newer revision is on file that:

  • is of the same document and type;
  • is active; and
  • applies to the same unit, date, product and Mfg Order.

The answer says so in a second Source note that names the revision left out and the revision that replaced it.

How the rule behaves:

  • Decided at question time. Nothing stored changes. So it covers a revision stored before this rule, a revision that arrives late, and a chain: a later revision with no range sets aside every earlier one, and a question dated before its start is still answered from the earlier revisions.
  • Revisions with their own range are never set aside. A unit, date or Mfg Order range says where a revision governs, so give each revision a range wherever it matters.
  • The note covers only what the answer drew on. The Source note names only the documents the answer drew other chunks from. A question that matches only an older revision, with the newer one's chunks below the retrieval bar, gets neither revision and no note. The newer revision is the one that applies, and it did not match.
  • Where it does not apply. It does nothing when no context is given, for an analysis of everything on file (include_inactive), or for Precedent Retrieval.
  • Which is newer. It uses the revisions' revision times, so a sender that gives wrong revision times can make the wrong revision win.

A revision older than one already on file is not assumed a start. A late arrival has no earlier revision to compete with, and it is left out at question time, as above. Two revisions of one document stored at the same moment can each miss the other, so deliver a document's revisions oldest first.

The starter catalogue

TypeCase recordStrategyRevisions
generic no fixed_window, 800 / 100 replace
sop no heading_sections, depth 2, 150 to 1500 replace
work_instruction no heading_sections, depth 3, 100 to 1200 replace
inspection_plan no heading_sections, depth 2, 150 to 1200 replace
design_note no heading_sections, depth 2, 150 to 1200 keep, leave
deviation_report yes heading_sections, depth 1, 300 to 3000 replace
nonconformance_record yes heading_sections, depth 1, 300 to 3000 replace
approved_summary yes fixed_window, 1500 / 150 replace

approved_summary is the type an approved case summary is queued as when a person submits it with a disposition they wrote (see submitting an approved case summary); a site does not send documents to it itself. The values are starting points to tune on your own documents. generic is always present. A site entry with the same name as a starter type replaces it whole: nothing is carried over from the starter's version, so give the replacement every field it needs. A site may also add types. No starter type has an identity rule, because no one rule fits every site's first line.

Everything is checked when the configuration loads

An unknown strategy name, parameters the strategy refuses, a context placeholder that is not allowed, an identity rule that does not compile, a boundary pattern that is unsafe, or a bad revisions or applicability is refused when the Node (or the offline check) loads the configuration, never at the first document. The message names the field, for example document_types.sop.strategy.max_chars, and lists every problem it found. The offline config check runs the same checks, with one exception: it cannot tell a strategy your deployment registers in its own Python (section 7) from a misspelt one, so it does not report an unregistered strategy.name or check that entry's strategy parameters. The rest of the entry is still checked, and the Node refuses the name when it starts.

2. A worked override: a plain-text work instruction

The starter splits a work instruction at markdown headings. A plain-text work instruction whose steps read "Step 3" has none, so the starter would cut it into one chunk. Replace the type with one that starts a chunk at each step:

{
  "document_types": {
    "work_instruction": {
      "description": "Plain-text work instructions numbered Step N",
      "strategy": {
        "name": "boundary_rules",
        "patterns": ["^Step\\s+\\d+"],
        "min_chars": 80,
        "max_chars": 1200
      },
      "context": "{document_number} {title} — {heading_path}:"
    }
  }
}

Each chunk then carries the step's label ("Step 3") as its locator, and {heading_path} in the context renders that label.

3. Strategies

Every strategy is deterministic: the same text under the same parameters always yields the same chunks, in the same order. Text with nothing in it yields no chunks.

  • fixed_window: overlapping character windows. window_chars (default 800) and overlap_chars (default 100, must be smaller than window_chars). Makes no assumption about structure, which is why generic uses it.
  • paragraph: one chunk per blank-line-separated paragraph. Optional max_chars cuts a paragraph longer than that into overlapping windows of overlap_chars (default 0, which needs max_chars); with neither, a paragraph is never cut, so a document with no blank lines is one chunk of any length.
  • heading_sections: splits at markdown (#) headings down to heading_depth (1 to 6, default 2). Headings inside a fenced code block are ignored (a fence is closed by a fence of the same character at least as long, with nothing after it); setext (underlined) headings are not recognised. Text before the first heading is its own section. A section longer than max_chars (default 1200) is split by paragraph, then by an overlapping window of overlap_chars (default 100); a section shorter than min_chars (default 150) joins the next one, or the previous one when it is last. Text with no headings is one section.
  • boundary_rules: a line that matches any of patterns starts a new chunk, with the same min_chars (default 100), max_chars and overlap_chars handling. A pattern is matched against the start of the line, so ^ is optional.

heading_sections and boundary_rules put a locator in each chunk's metadata: the heading path joined with > (for example Torque Procedure > Steps), or the matched label (Step 3). A locator names the place in the document, not the chunk, so it is the same after the section is chunked at another size or the document is revised elsewhere.

  • Text before the first heading or boundary is (preamble), and a document with none is (document).
  • A repeated locator in one document is numbered (Notes, Notes #2).
  • A locator is cut at 120 characters.
  • When a short section is joined to its neighbour, the chunk keeps the first section's locator and lists all of them under locators. It also records locator_spans: each joined section's locator, with where in the chunk it begins. A claim drafted from the chunk can then be placed in the section that holds its sentence, not in the first one. A later piece of a long joined section lists only the sections that lie in it.
  • heading_sections also records heading_path, the list of headings.

Boundary patterns are restricted

A pattern is run over your own documents, and Python's regular expression engine backtracks: a short pattern such as (a+)+$ takes time that doubles with every character on a line that almost matches. A pattern is therefore refused at load if it:

  • is longer than 100 characters, is empty, or can match an empty string;
  • has a repeat inside a repeat ((a+)+), an alternation inside an open-ended repeat, or a backreference;
  • has more than four open-ended repeats (*, +, or {n,} and ranges above ten).

A line longer than 200 characters is never matched. Ordinary step patterns (^Step\s+\d+, ^\d+\.\s, ^\s*\d+\s*[.)]\s+) pass.

4. The chunk context

context is a format whose placeholders are {document_number}, {title}, {revision_label}, {heading_path} and {document_type}. The rendered context is put before the chunk for embedding only: a chunk such as "SEAL SURFACE FINISH Ra 0.8" says nothing of its part, but with "DWG 40-1177 Housing, Pump — General Notes:" ahead of it a question about the pump housing's seal surface matches it.

  • A placeholder with no value is dropped together with the literal text that leads into it, so a missing revision label leaves neither "rev" nor a dangling " — ". The text after the last placeholder (a closing colon) is kept when anything else was rendered.
  • {heading_path} is the chunk's heading path, or its locator when the strategy has no headings.
  • Each value is collapsed to one line and cut at 200 characters.
  • The result is never empty: when every placeholder is dropped it is the title followed by a colon.

5. Title and document number

An intake item may carry title, document_number and revision_label. The seam fills what is missing: first from the type's identity.first_line, a regular expression matched against the start of the first non-blank line, with the named groups document_number and title (no other group name is allowed); then a title still missing becomes the source_document_id. The intake report lists title under identity_fallback when that last step was needed. A rule that matches but names no title group leaves the title as the id when the sender gave none, and the chunk preview says so with the finding title_taken_from_document_id. The rule reads nothing but the text it is given, and a first line longer than 200 characters is not matched. The same pattern restrictions as in section 3 apply.

6. The configuration fingerprint

Each type has a fingerprint, a hash of its effective configuration: the strategy and its parameters with the defaults filled in, the strategy's code version, the context, the identity rule and the default applicability. It changes when any of those changes and not when only the description, the case_record flag, draft_claims, require_effective_range or the revisions policy does, because those alter no chunk.

Which changes are worth a targeted re-ingest

To see what a change does to a real document before anything is ingested, run the chunk preview.

Changing a type's configuration affects only documents ingested after it; chunks made earlier stay as they were, stamped with the configuration version they were made under and still retrievable. Re-ingesting the type's documents brings them into line. engine.document_report.version_report shows how many documents of a type are on each version, and stale_document_batches selects those below a version, a batch at a time (retrieval-embedding-infra.md).

  • Material, so worth a re-ingest: the strategy, the window or section sizes, the context format, an identity rule, or the default applicability.
  • Not material: an overlap_chars tweak, a description, the case_record or draft_claims flag, a new type.
  • Changing revisions alters no chunk and so leaves the version as it was, but it changes the ids documents are stored under, and only for revisions that arrive afterwards. From replace to keep, the documents already stored stay under their plain id, active, beside the id@label rows of later revisions, and retrieval returns both; deactivate the old ones (python3 -m engine.document_tools deactivate) when you switch. From keep to replace, the id@label rows stay active and the next revision is stored under the plain id; deactivate the kept ones for a document you want answered from the new revision alone.

Chunks made under different settings are scored on one scale, so a material change leaves older documents ranked unevenly until they are re-ingested.

7. Your own strategy

A strategy the starter does not have is registered in Python before the configuration loads, then named in a catalogue entry. Registering a name again replaces it; the four built-in names cannot be replaced.

from engine.public import Chunk, ChunkingStrategySpec, register_chunking_strategy


def build_by_semicolon(params):
    keep = params["min_chars"]

    def strategy(text):
        parts = [p.strip() for p in text.split(";")]
        return [Chunk(text=p, sequence=i) for i, p in enumerate(q for q in parts if len(q) >= keep)]

    return strategy


register_chunking_strategy(
    ChunkingStrategySpec(
        name="by_semicolon",
        version=1,
        build=build_by_semicolon,
        schema={
            "type": "object",
            "properties": {"min_chars": {"type": "integer", "minimum": 0}},
            "additionalProperties": False,
        },
        defaults={"min_chars": 0},
    )
)

The version is part of every type's fingerprint: raise it whenever a change to the code alters what the strategy returns for the same parameters, or chunks made before and after will look identical to the history. schema is the JSON Schema for the parameters (the default accepts none); defaults fills in the ones a catalogue entry omits; check, if given, looks at the finished parameters and returns the name of the one at fault and what is wrong, for rules that cross fields; and stamps_locator (default False) says that every chunk the strategy makes carries a locator in its metadata that names a place in the document and does not depend on the chunk's size or sequence, which a type needs to declare draft_claims. A strategy must never raise for any text, including empty text (return []).

8. Using the registry in Python

The catalogue builds an ordinary ChunkingRegistry:

from engine.document_types import load_document_types

catalogue = load_document_types(config.get("document_types"))
registry = catalogue.chunking_registry()
chunks = registry.chunk("sop", extracted_text)

A ChunkingRegistry can also be built by hand, which is how a Node that does not use the catalogue picks a strategy per type. ChunkingRegistry() always seeds "generic" with fixed_window_chunking; register(document_type, strategy) adds or replaces a type, and registered_document_types lists them. An unregistered type routes to whatever is registered under "generic", so chunk() never raises for an unknown type.

Chunk deliberately carries no document identity: the caller assigns a chunk id (typically f"{source_document_id}:{chunk.sequence}") and stores chunk.metadata beside the text, as in retrieval-embedding-infra.md.

Pitfalls

  • A site entry replaces a starter type whole. Overriding sop with only a new strategy drops the starter's context and revisions policy; they return to the defaults.
  • A pattern that matches nothing yields one oversized chunk. boundary_rules with a pattern that never matches a document is valid; the document is one (document) section, split only by size. Check a new pattern against a real document before bulk ingestion.
  • overlap_chars must be smaller than the size it overlaps (window_chars, or max_chars for the two section strategies), or the configuration is refused.
  • Headings need a space after the #. #Title is text, not a heading.

Release: v0.11.0