The retrieval index¶
Summary
Matsya's retrieval index, in standard terms a RAG index (retrieval-augmented generation), is the store of passages from which a search returns the passages placed in a language model's message; it is built in four steps by four programs. A compiler turns the reviewed list of sources into a manifest of file digests; the operator-run script build_retrieval_index.py extracts passages from those files, embeds them, that is, computes for each passage a vector of numbers with a local embedding model so that passages of similar meaning receive similar vectors, writes a snapshot, tests it with the searches of a check file and activates it; the operator-run script retrieval_bundle.py copies the active snapshot with the embedding model into one folder for another machine; and the service opens the snapshot named by the file active.json. A search combines an exact cosine comparison of embeddings with SQLite full-text search and a count of mathematical symbols, and weights the result by collection. The snapshot also records the index's knowledge graph, each admitted document with the sections its headings open, the links its authors wrote and the tags it carries, from which a snapshot answers two operations, related and read; the search does not read these records.
Relationship with other documents
Builds on — Matsya collection, which defines the five groups of sources considered for the index. Used by — Collections and weights: the fields of a search request and the weights; Matsya collection: the five groups of sources. See also — What Matsya reads §5, for the reading controller that uses the index’s passages and knowledge graph.
1 The four programs¶
| Step | Program | Reads | Writes |
|---|---|---|---|
| Compile | The operator-run script compile_retrieval_manifest.py |
the list of indexed sources and the checkouts of this repository, the private literature collection, HARK and Buffer Stock Theory (§3) | one manifest of paths, digests and versions, outside every checkout |
| Build | The operator-run script build_retrieval_index.py |
the manifest, the checkouts, the check file, the embedding model | a snapshot under the index folder, activated when every check passes |
| Transfer | The operator-run script retrieval_bundle.py |
the active snapshot and the embedding model | a bundle folder with index/, model/ and release.json |
| Serve | matsya-serve (serve.py), whose application create_app of api.py builds an ActiveIndexManager of retrieval/manager.py at start-up |
the index folder's active.json |
nothing; answers searches |
The installed package declares only matsya-serve under [project.scripts] in packages/matsya/pyproject.toml. Operators run the compiler, index builder and bundle script with Python from their deployment files; these scripts and the source list are maintained separately from the installed package. The scripts use the package's shared retrieval functions. The embedding library, sentence-transformers, is installed only with the optional dependency group retrieval.
2 The list of indexed sources¶
The authoritative list is the operator's reviewed source-selection.json, updated on 9 October 2026 and maintained with the deployment files. It has six top-level keys: sources, 814 entries; omissions, 118 files left out with a reason each; review_inputs, the six index and status files that were read when the list was reviewed, among them the literature collection's index and the project's specification status table, whose SHA-256 digests the compiler requires unchanged; expected_counts per collection; schema_version; and selection_date. Each source has the fields corpus (its collection), source_id, path, authority, access (the access class, public, private or article, which with the collection decides who may read a passage; the repository allows public and private, the literature private, the articles article, HARK and Buffer Stock Theory public) and model_prompt, and may have title, version, source_cluster (a label by which a job leaves a paper's own files out of its search, the guide's first page §2), source_root and expected_sha256. Operators keep a readable copy of this reviewed list with the deployment files.
The 814 sources are 197 files of this repository (150 Markdown pages, 34 stage files, 13 notebooks), 153 Markdown texts of the private literature collection, 230 journal articles (220 Markdown texts read from the literature checkout and 10 PDFs read from this repository), 209 files of HARK (74 Python, 67 notebooks, 37 reStructuredText, 16 Markdown, 15 YAML) and 25 files of Buffer Stock Theory (24 LaTeX, 1 PDF). The mark model_prompt is true for 52 repository files only; it restricts no message, and a job or a turn may place in a language model's message the passages of every collection the user's grants allow, the mark staying recorded in the list and the index. The authority label records the standing of a source in the project, in one of twelve values (primary, secondary, canonical, discovery, implementation, documentation, example, extract, synthesis, synthesis-unreviewed, development and terms); it is stored with every passage and returned with every result, and the ranking does not read it.
3 The compiler¶
compile_retrieval_manifest.py reads the list (--selection, by default config/source-selection.json beside scripts/), the checkout of this repository (--repository-root, by default the repository the script is in), the private literature checkout given by --literature-root, and the HARK and Buffer Stock Theory checkouts (--hark-root, --buffer-stock-root) when their files are selected, and writes one JSON manifest to --output. Before reading the list it refuses two roots that are the same folder, an output path inside a source root, and a checkout of this repository with changed or untracked files. It refuses the list when any review input's digest differs from the recorded value, so a changed review input requires the list to be reviewed again. For each entry it refuses an unknown collection, an unsafe path, an access class the collection does not allow, a file of the internal folder outside dev-docs/, a model_prompt mark on a file under tutorials/, on a stage file under applications/ or on any file of the literature, articles, HARK and Buffer Stock Theory collections, a missing digest for a file of another checkout, and a missing version for a HARK or Buffer Stock Theory file. It requires that each file exists in its root, that a HARK or Buffer Stock Theory file's version equals the checkout's commit and the file is tracked by Git, that a stage file elaborates without error, and that a file's digest equals expected_sha256 where one is recorded. After the entries it checks the omissions and the expected counts, reads each checkout's commit again, and writes the manifest through a temporary file: {schema_version, corpus_revisions, sources, dependencies}, where corpus_revisions records the commit of the checkout for the repository, HARK and Buffer Stock Theory and, for the literature and the articles, a SHA-256 of the collection's selected entries, and dependencies lists the Econometrica PDFs from which the article texts were made, whose presence and digest verify_dependencies of retrieval/manifest.py checks without indexing them. The manifest holds paths, digests and versions, never the text of a source.
4 Extraction¶
The extractor, retrieval/extract.py, cuts each file into passages by its kind and reads from the Markdown files and notebooks the records of the index's knowledge graph. The compiler assigns the kind from the suffix: .md is Markdown; .txt, .tex, .rst, .bl, .py, .yaml, .yml and .lark are text; .pdf is PDF; .ipynb is a notebook. A passage holds at most 1,600 characters: the extractor ends a long passage after the last blank line between characters 800 and 1,600 of the text not yet cut, or, when there is none, after the last line break in that range, or, when there is none, after the last space in that range, and consecutive passages adjoin without overlap.
Before it cuts a Markdown file, the extractor reads the whole file, front matter included, with parse_document of packages/matsya/matsya_service/document_metadata.py, the parser that also reads the reference guides (What Matsya reads §3), and it cuts at the structure the parser returns. A passage ends at each heading the parser returns, and the heading path, Top / Sub, is stored with it; the heading line itself is not part of the passage text, and a line beginning with # inside a fenced code block is not a heading and divides nothing. A cut never falls inside a link its author wrote or inside a formula, $…$, $$…$$, \(…\) or \[…\], as the parser delimits formulas; where the preferred cut would fall inside one, the passage ends before it. A formula longer than a passage is cut, and each passage holding a part of it records in its location that the formula continues before it, after it or both. Each passage of a parsed file records in its location the identifier of its innermost section, the fragment by which a link addresses that section's heading. A page marker line, a heading # [page N], # [pdf page N] or # [page N | printed <label>] (which also records the printed page label), or a comment <!-- page N -->, starts a new passage and records the page; it neither opens nor ends a section. The front matter is outside every passage.
A notebook is read cell by cell, with the cell number and type recorded and outputs, metadata and raw cells never read. Its Markdown cells are joined in cell order with a blank line between them and parsed once, so that a repeated heading is numbered across the notebook; in a Markdown cell a passage ends at each heading, the heading line staying in the passage it begins, and no cut falls inside a link or a formula; a code cell is cut by size alone. A section opened in one cell covers the following cells, code cells included, up to the next heading of the same or a higher level, so a code cell's passages record the section above them. LaTeX, Python, reStructuredText and YAML files are cut by size alone, and their passages are stored without a heading path. A stage file is parsed with the bellman package's parser and cut at each top-level block: the declarations before the first block form a passage under the heading path Stage <name> / Declarations, and each block a passage under Stage <name> / Block <id>, cut further where a span exceeds 1,600 characters. A PDF is read with pypdf page by page, each page cut separately with its page number. These files are recorded as documents whose structure was not parsed, so that the absence of their links and tags is never read as evidence that they have none. So is a Markdown file or a notebook whose front matter is not valid YAML, or two of whose headings carry one explicit identifier {#id}, whose passages are cut as the extractor of version 3 cut them, at lines that look like headings; on 9 October 2026 fifteen admitted files are in that case, fourteen article texts whose titles hold an unquoted colon and one literature note.
Each passage is one record with the fields corpus, source_root, access, source_id, path, file_sha256, kind, authority, version, title, source_cluster, model_prompt, location (page, page basis, printed page label, heading, line and character ranges, and in a parsed file the section and the mark of a divided formula), text, passage_sha256 and passage_id. The passage identity is the SHA-256 of the list [collection, path, file digest, location, text digest], so the same text at another place, or in a changed file, receives another identity. The extractor's version number, 4, is stored in every snapshot (§6). Version 4 changes where Markdown and notebook passages begin and end, and so their identities, while the passages of PDFs, text files and stage files keep the records and identities that version 3 gave them.
The knowledge graph. The extractor records each admitted document with its collection, path, source root, source identity, file digest, kind, access class, model_prompt mark, source cluster and title (the list's, or else its first heading), whether its structure was parsed, and the slug and aliases its front matter declares; each section a heading opens, with its identifier, heading, level, enclosing section, span and order; each link its author wrote, with its kind (inline, reference-style or wiki), written destination, fragment, label, span and section; and each tag membership, a tag written in the document with the scope it annotates, page, section or local, the span of that text and whether the tag is a usable topic tag. A span counts the characters of the decoded file; in a notebook it counts those of the joined Markdown cells, and each record also gives the cell and the offset in it at which its span starts and ends. Once every document of a collection has been read, the extractor resolves the collection's links with resolve_links of the same module, against the admitted documents of that collection read from the same checkout, of every kind, and against no other file. A link is available when its destination names such a document, and one of its sections where the link names a fragment; ambiguous when its name matches several; and otherwise unavailable with one reason: missing_page when it names no admitted document, whether or not a file stands at that path; missing_fragment when the document has no such section; excluded when it leaves the checkout; external for a web address, which is never fetched; unsupported for a link form the parser does not resolve or a fragment of a document whose structure was not parsed; and other_collection when another collection read from the same checkout holds the destination, as when an article text names a note of the literature collection. A link to an admitted stage file, notebook or PDF is available. Construction follows no link and opens no file the manifest does not list.
The rules of resolution and the usable topic tags stand in the graph policy GRAPH_POLICY of extract.py, at version 1, which is recorded whole in every snapshot. Its rules are those of the guides' construction policy, guide_policy.json beside the operator's guide builder, so that a link written in a page that the guides and the index both admit resolves alike in both. For each collection it lists the usable topic tags, the tags through which two documents may be associated: for the repository the nineteen tags of the guides' policy, which name objects of the language, such as stage and perch; for the literature the twenty-two topic tags its notes declare, without the tags that record a note's kind; and none for the articles, HARK and Buffer Stock Theory. A document that carries the tag definition beside a usable tag is that tag's defining page; definition itself associates nothing. Read on 9 October 2026 from the 570 admitted files of this repository and the literature checkout, the records number 6,763 sections, 6,158 links, of which 2,751 are available, and 616 tag memberships.
5 Embedding¶
retrieval/embedding.py loads a sentence-transformers model from a local folder only, with no download. The embedding model's identity is the string sentence-transformers:<version>:transformers:<version>:torch:<version>:<digest of the model folder's files>, so a change of any library version or any file of the embedding model gives another identity. The snapshot records that identity, and an index is loaded only with the embedding model whose identity it records; the two are therefore copied together (§9). The code does not name the embedding model: whichever local folder --model-path names is used. The earlier service used sentence-transformers/all-MiniLM-L6-v2; a new index records the exact identity of the local model folder used to build it. The embedder returns one vector per text, computed in batches of 32, and index.py divides each vector by its length before storing or comparing it, so the dot product of two stored vectors is their cosine similarity.
6 The snapshot on disk¶
A snapshot is a folder of three files. passages.sqlite holds the table passages, one row per passage with its sequence number, identity, collection, access class, path, cluster, prompt mark, heading, text and the complete record as JSON; the full-text table passage_fts, an SQLite FTS5 table over the heading and text columns; and the table symbols, which lists for each passage the mathematical symbols in its heading and text, the single non-ASCII characters of Unicode category Sm or with ARROW in their name, and the angle brackets ⟨ and ⟩. It also holds the knowledge graph of §4 in four tables, documents, sections, links and tag_memberships, one row per record in the order of the documents and, within a document, of the parser, each with the columns a lookup needs and the complete record as JSON written with sorted keys; SQLite indexes find the links by citing document and by target and the tag memberships by collection and tag. vectors.f32 is a plain matrix of 32-bit numbers with one unit-length row per passage in passage order. snapshot.json holds the digest and the record from which it is computed, with the schema version, 2; the extractor version, 4; the parser's version; the graph policy whole; the number of rows of each of the four graph tables; the symbol index version, the embedding model's identity, the complete manifest and its digest, the passage count, the vector width and the SHA-256 of the two other files. The digest of that record names the snapshot's folder, so it also covers the parser's version, the graph policy and the counts. Every load checks the files' digests and sizes and the row counts of the passages and of the four graph tables against the record.
A snapshot of schema 1, built by extractor version 1, 2 or 3, holds no graph records and stays readable by its digest, so that a passage cited from it is fetched as before; the active index of 5 October 2026 is a snapshot of schema 1 built by extractor version 3 (§9).
The index folder named by MATSYA_INDEX_ROOT holds candidates/<digest>/ for snapshots built but not active, snapshots/<digest>/ for activated snapshots, and active.json, which holds only the digest of the active snapshot. Every folder must be readable by its owner only (mode 0700) and every file likewise (0600); the code refuses to open anything other users can read, because the passages hold private literature text.
7 Build, check and activate¶
The operator runs build_retrieval_index.py with Python. It takes --manifest, --checks, --repository-root, --literature-root, --index-root and --model-path, and optionally --hark-root, --buffer-stock-root and --device; it reads no environment variable. Its function build_checked_index runs build_candidate, load_candidate and activate_candidate of index.py, with check_index of build_retrieval_index.py between the last two; verify_candidate runs inside build_candidate before the rename, inside load_candidate and again inside activate_candidate. build_candidate checks the manifest and the external checkouts, reads each listed file, checks its digest a second time after reading, extracts and embeds its passages in batches of 64, writes the snapshot into a temporary folder and renames it to candidates/<digest>. verify_candidate checks permissions, digests, versions and the embedding model's identity, the row counts and SQLite's integrity checks; it refuses a snapshot of schema 1 and a snapshot whose parser version or graph policy differs from the program's. It then extracts, parses and resolves every listed file again from its current bytes and requires each stored row of the passages and of the four graph tables to equal the fresh record, in order; it does not recompute the vectors, which are checked only by the digest and size of vectors.f32. Last it runs the structural check of the graph records, check_structure of index.py, which needs no source: each available link names a stored document, and a stored section where it names a fragment; the sections of each document are ordered and nested by level; each passage that names a section lies within that section's span; and each link and each tag membership names a stored document. check_index runs every check of the check file against the loaded candidate: a check names a query, a collection, an access class and a source, and requires that a search with limit 20 returns a passage of that source, with the page, kind and expected text where the check gives them. When all pass, build_retrieval_index.py prints the counts of the candidate's documents, parsed and not parsed, its sections, its links by outcome and its unavailable links by reason, and its tag memberships, which the record of a rebuild copies; only then does activate_candidate move the folder to snapshots/<digest> and replace active.json in one rename, and the command prints its last line, Active Matsya index: <digest>. On any failure active.json is unchanged and a built candidate stays in candidates/.
Activation needs the private check file of 41 checks, which is kept outside the repository. Every check file has the form {schema_version: 1, checks: [...]}; a check has query, corpus, access and source_id, and optionally path, page, kind, page_basis (pdf_ordinal or markdown_marker), printed_page_label and expected_contains. read_checks in build_retrieval_index.py requires for every selected article PDF a check and, for each of them, one on a page after the first with expected text, at least one repository check and one literature check, a HARK and a Buffer Stock Theory check when those files are present, and a later-page check of the Buffer Stock Theory PDF; the operator's known-retrieval-checks.json, nine checks of public sources, is therefore refused on its own against the current list. One build extracts every source four times, once to write the snapshot and three times to compare the stored rows with a fresh extraction, since the build, the load and the activation each verify the candidate; the build of 5 October 2026 embedded 59,756 passages, and the command is started as a background process that keeps running after the terminal session ends.
8 A search¶
RetrievalIndex.search in index.py takes a query, the permitted pairs of collection and access class, a limit from 1 to 50, and optionally the model_prompt restriction, excluded clusters, named sources and boost factors (a number per collection by which its weight is multiplied). The search runs in seven steps.
- It restricts the candidate passages with SQL to the permitted pairs and the other restrictions.
- It embeds the query with the same embedding model, computes the query's exact cosine similarity with every permitted vector in blocks of 4,096 rows, and keeps the 200 most similar passages of each collection.
- It queries the FTS5 table, collection by collection, for passages containing any of the query's words outside a stopword list and keeps the 200 best of each collection by BM25, the standard ranking function of full-text search, giving the match at rank \(r\) the score \(1/(1+r)\).
- When the query holds mathematical symbols, it keeps the 200 passages of each collection with the most of them, scored by the share of the query's symbols they contain.
- It scores each candidate as 0.7 times the larger of the full-text and symbol scores, plus 0.3 times the cosine similarity when positive, plus 0.3 when the whole query occurs in the passage's heading or text.
- It multiplies the score by the collection weight.
- It returns the first
limitpassages sorted by weighted score.
The search compares the query with every permitted vector; it uses no approximate method that would compare only some of them. The fields of a search request and the weights, as the routes POST /v1/search and POST /v1/answer apply them, are in Collections and weights §§3–4.
9 Serving and transfer¶
matsya-serve refuses to start unless seven environment variables are set: MATSYA_CONFIGURATIONS_ROOT, the folder of the published configurations; MATSYA_CONFIG_ADMIN_GRANTS_FILE, the administrator grant file; MATSYA_INDEX_ROOT, the index folder; MATSYA_EMBEDDING_MODEL_PATH, the embedding model's folder; MATSYA_DB_PATH, the token database; MATSYA_ITERATION_DB_PATH, the job database; and MATSYA_COLLECTION_GRANTS_FILE, the grant file. The application's start-up, create_app of api.py, builds an ActiveIndexManager, whose method current reads active.json at every call and loads a newly activated snapshot without a restart, and whose method at_digest opens an older snapshot so that a passage cited before an activation can still be fetched, and keeps each snapshot it has opened by its digest, so that successive reads of one stored snapshot do not hash its files again. A stored snapshot whose record names the service's embedding model is opened as a RetrievalIndex, which can be searched, so that a turn of conversation mode that names an earlier snapshot by index_digest searches it (What Matsya reads §8); one built with another embedding model is opened as a PassageSnapshot, which answers fetch, related and read but no search, since the service cannot embed a query with that model, and in it the reading controller makes no initial search and answers a search request unsupported with the reason no_search. A job takes the index once at its start and keeps it for all its cycles. The active index is a snapshot of schema 2 built by the program's extractor, parser and graph policy or, until the rebuild from the list of 7 October 2026 replaces it, the snapshot of schema 1 built by extractor version 3, so that the service starts and searches before the rebuild. When the four optional variables naming the source checkouts are set, MATSYA_REPOSITORY_ROOT and MATSYA_LITERATURE_ROOT (together, or neither), MATSYA_HARK_ROOT and MATSYA_BUFFER_STOCK_ROOT, read in create_app, the service verifies the index on loading: a snapshot of schema 2 by extracting, parsing and resolving every source again, as verify_candidate does, and the snapshot of schema 1 by the digests of its source files alone, since no extractor of version 3 remains. On a server they are unset and the service checks the snapshot's own digests only.
A snapshot answers two operations from its graph records, related and read of PassageSnapshot, so that a stored snapshot opened by its digest answers them as the active index does; both read the snapshot's database alone, and a snapshot of schema 1 answers both unsupported. An address is a passage, a document by its collection and path, or a section of it by its identifier, and every address they return carries the snapshot's digest. Unlike fetch, both apply the restriction of a search themselves, to the address and to every document they would name: the permitted pairs of collection and access class, the model_prompt mark and the excluded source clusters; source_clusters lists every source cluster the snapshot's manifest names, so that a caller can exclude them all. related lists, never with their text, the targets of the origin's links and, for each of its usable topic tags, the documents whose page tags include it and the sections outside the origin that hold it, a defining page first; with tag, one tag's candidates; with incoming, the sections whose links name the origin. A target that is not both available and permitted is left out before the candidates are ordered and counted, so that a caller cannot tell an absent target from a forbidden one, and an absent and a forbidden address both answer unavailable. read returns a passage, or the passages of a document or a section in source order, as many as fit within a number of characters, each with its permitted links and its usable topic tags. Both return a continuation position, next_position, while candidates or passages remain. No route of the service answers them directly; the reading controller of a job or of a turn calls them. In a job, the Matsya handlers do not receive the index itself: they receive the reading controller, which the processor builds over the snapshot the job holds, and it alone calls search, related and read, to make an invocation's initial search and to answer the requests of the Model-prose-writer and Prose-to-Bellman-Sym, always within the collections the job's principal may read and with the job's source clusters excluded (What Matsya reads §5). In a turn of conversation mode, which the route POST /v1/sessions/{session_id}/turns starts, the turn runner builds the controller over the turn's snapshot and binds it to the collections the person asking may read; the controller then calls search, related and read for the conversation role within the collections this person may read, and excludes no source cluster, since a turn writes no declaration (What Matsya reads §8).
The operator runs retrieval_bundle.py with Python. Its export command takes --index-root, --model-path and --output-root and copies active.json, the three snapshot files and the whole embedding model folder into a new private folder with release.json (the index digest, the embedding model's identity and its files' digest), verifies the copy and prints Verified source-free Matsya bundle: <digest>; its verify command takes --bundle-root and --expected-digest and checks a copy without any source checkout, and runs the structural check of §7 on the copied snapshot, so that a copy whose graph records were altered is refused even when its digests were written again. The bundle contains the extracted passage text, private literature included, so it may be copied only into the service account's private storage.
10 The state on 9 October 2026¶
The active index was rebuilt on 9 October 2026 (digest beginning f120df55da75) from the reviewed list of 814 files, by the extractor at version 4 into a snapshot of schema 2 with the documents, sections, links and tag memberships that the reading operations answer from: 57,636 passages, 7,678 sections, 6,868 links of which 2,820 are available in the index, and 617 tag memberships. It passed the 41 private checks and the nine public ones before activation. The snapshot of 5 October (digest beginning 482de81015fa), built from the earlier list of 1,295 files by the extractor at version 3, was deleted the same day; earlier snapshots are kept from the next rebuild on. The bundle of the new index is exported and verified and waits for the deployment.