Skip to content

retrieval.record_loaders

Registry of record-oriented loaders. A record loader maps a file suffix to a callable load(docid, text, url) -> list[Document] that yields one chunk-granularity Document per logical record (a gettext entry, a CSV row, a subtitle cue). Stdlib-only.

retrieval.project_loader consults lookup(path) in both load_chunk_documents and load_ast_chunk_documents, and the CLI prints detail_lines(metadata) under each hit in text mode, so the engine core contains no format-specific code. retrieval.po_loader registers .po this way; it is listed in BUILTIN_LOADER_MODULES and imported lazily on first lookup.

Each loader declares detail_keys (rendered as label: value) or a describe hook for custom text-mode lines. JSON output is unaffected.

Registry of record-oriented loaders (one Document per record).

Stdlib-only. A record loader turns a whole file into one chunk-granularity Document per logical record (a gettext entry, a CSV row, a subtitle cue, ...) instead of size-based chunking. The engine core (retrieval.project_loader, retrieval.cli) stays format-agnostic: it only asks this registry which loader, if any, owns a path's suffix.

Contract for RecordLoader.load: load(docid, text, url) -> List[Document] where docid is the file's relative POSIX path. Each returned Document uses docid=f"{path}:{start}-{end}", sets source_path/start_line/ end_line, and stamps metadata["kind"] = loader.kind. Text-mode CLI hits are followed by detail_lines(metadata): either the loader's detail_keys rendered as label: value or the output of its optional describe hook.

Bootstrap: built-in loader modules listed in BUILTIN_LOADER_MODULES are imported lazily on first lookup and register themselves at import time, so the result does not depend on import order. Out-of-tree loaders just call register at import.

Caveat: project_loader.DEFAULT_EXTENSIONS is computed when that module is first imported, so a loader registered later is routed by the chunk loaders but not discovered by default; pass extensions=DEFAULT_EXTENSIONS | {".ext"}.

RecordLoader dataclass

A suffix-keyed loader producing one Document per record.

Source code in engine/retrieval/record_loaders.py
39
40
41
42
43
44
45
46
47
@dataclass(frozen=True)
class RecordLoader:
    """A suffix-keyed loader producing one ``Document`` per record."""

    kind: str
    suffixes: FrozenSet[str]
    load: LoadFn
    detail_keys: Tuple[str, ...] = ()
    describe: Optional[DescribeFn] = None

detail_lines(metadata)

Indented label: value lines for a hit's metadata (text mode).

Empty when there is no metadata or its kind has no registered loader.

Source code in engine/retrieval/record_loaders.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def detail_lines(metadata: Mapping[str, Any]) -> List[str]:
    """Indented ``label: value`` lines for a hit's *metadata* (text mode).

    Empty when there is no metadata or its ``kind`` has no registered loader.
    """
    _ensure_builtins()
    kind = metadata.get("kind") if metadata else None
    loader = _BY_KIND.get(kind) if isinstance(kind, str) else None
    if loader is None:
        return []
    if loader.describe is not None:
        pairs = loader.describe(metadata)
    else:
        pairs = [(k, one_line(str(metadata[k]))) for k in loader.detail_keys if k in metadata]
    return [f"    {label}: {value}" for label, value in pairs]

lookup(path)

The loader owning path's suffix (case-insensitive), or None.

Source code in engine/retrieval/record_loaders.py
92
93
94
95
def lookup(path: str) -> Optional[RecordLoader]:
    """The loader owning *path*'s suffix (case-insensitive), or ``None``."""
    _ensure_builtins()
    return _BY_SUFFIX.get(Path(path).suffix.lower())

one_line(text, limit=160)

Flatten newlines to a literal \n and truncate to limit chars.

Source code in engine/retrieval/record_loaders.py
104
105
106
107
def one_line(text: str, limit: int = 160) -> str:
    """Flatten newlines to a literal ``\\n`` and truncate to *limit* chars."""
    flat = text.replace("\n", "\\n")
    return flat if len(flat) <= limit else flat[:limit] + "..."

register(loader)

Register loader; re-registering the same kind replaces it.

Raises ValueError for a suffix without a leading dot or one already owned by a different kind.

Source code in engine/retrieval/record_loaders.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def register(loader: RecordLoader) -> None:
    """Register *loader*; re-registering the same ``kind`` replaces it.

    Raises ``ValueError`` for a suffix without a leading dot or one already
    owned by a different kind.
    """
    suffixes = frozenset(s.lower() for s in loader.suffixes)
    for suffix in suffixes:
        if not suffix.startswith("."):
            raise ValueError(f"record loader suffix must start with '.': {suffix!r}")
        owner = _BY_SUFFIX.get(suffix)
        if owner is not None and owner.kind != loader.kind:
            raise ValueError(f"suffix {suffix!r} already registered by kind {owner.kind!r}")
    unregister(loader.kind)
    _BY_KIND[loader.kind] = loader
    for suffix in suffixes:
        _BY_SUFFIX[suffix] = loader

registered_suffixes()

All suffixes currently owned by a record loader.

Source code in engine/retrieval/record_loaders.py
 98
 99
100
101
def registered_suffixes() -> FrozenSet[str]:
    """All suffixes currently owned by a record loader."""
    _ensure_builtins()
    return frozenset(_BY_SUFFIX)

unregister(kind)

Remove the loader for kind and its suffixes (no-op if unknown).

Source code in engine/retrieval/record_loaders.py
83
84
85
86
87
88
89
def unregister(kind: str) -> None:
    """Remove the loader for *kind* and its suffixes (no-op if unknown)."""
    loader = _BY_KIND.pop(kind, None)
    if loader is None:
        return
    for suffix in [s for s, owner in _BY_SUFFIX.items() if owner is loader]:
        del _BY_SUFFIX[suffix]

Next steps