Skip to content
An Econ-ARK project

The Matsya handlers

Summary

A Matsya handler is one of the thirteen Python functions, each with a name and parameter list that the program fixes and checks, that together run a job; the program calls two of them directly, normalize_source and cycle, and cycle calls the rest. A configuration that enables the optional conversation role holds a fourteenth, conversation_reply, which the turn runner calls once for each turn of conversation mode (§7). They are written in the Matsya handler module of the configuration folder, outside the package, because they are the trained code \(\mathfrak{h}\): a training pass may rewrite what a Matsya handler does, and the program checks only that the thirteen names, and the fourteenth where the role is enabled, and their parameter lists are present. The word is not the Rosetta-stone handler, which names a solver that realizes an operator; the wiki page Handler defines that sense and Matsya handler this one.

Relationship with other documents

Builds on — the guide's first page §§1–2: the program and the configuration folder, the frame and the job frame, the training pass, the slots and the roles, the dossier; What Matsya reads: the texts, pages and settings the Matsya handlers assemble into messages. Function signatures — §2 lists the names and ordered parameters that the program checks. A training pass can revise the Matsya handlers’ code within those fixed signatures. See also — Collections and weights §6, for the searches a job and a turn make; What Matsya reads §§5 and 8, for reading requests and the message of a turn. The job’s record and its two views are described in §3.

1 Where the Matsya handlers are and what they may use

The module's file name is fixed by the program: HANDLERS_FILE = "matsya_handler.py" in configuration.py, which check_files requires; the qualifier distinguishes these functions from the Rosetta-stone handler. The module has 2,210 lines: the thirteen Matsya handlers, one for each slot (a slot is a Matsya handler name with its ordered parameter names, as SLOTS in configuration.py fixes them), and the optional fourteenth, conversation_reply, the slot of OPTIONAL_SLOTS; two public functions besides, structure_of, which reads the structure a description states under its heading Structure, and target_question, the fixed question of a job whose target cannot hold that structure; 47 helper functions whose names begin with an underscore; one helper class _Calls; eighteen public constants, among them the two lists of concepts from which an initial search is built (LANGUAGE_TERMS and ECONOMIC_CONCEPTS), the conversation role's key, guides and named fields (CONVERSATION_ROLE, CONVERSATION_GUIDES and CONVERSATION_FIELDS) the fixed headings STRUCTURE_HEADING of the description and FILL_HEADING of a recipe's note, ROUND_TRIP_RULES, what the files of a target cannot state, and SOURCE_KIND_LABEL, the label under which the Model-prose-writer's message names the kind of the source material; twelve private compiled regular expressions, two of them the headings of a paper in Markdown and in LaTeX, the tuple _LATEX_LEVELS of LaTeX's sectioning commands by rank, the two tuples of patterns compiled from those lists and the sets _ANSWER_FIELDS and _SUBMIT_FIELDS of the fields of the conversation role's answer and of its submit_job. Its docstring states the rules it is written under: a Matsya handler receives the job frame and uses the bellman package, the comparator, the form check and the exception classes through it; a Matsya handler calls a language model only through the Matsya handler call; and the module imports only the standard library, plus, for normalize_source and select_pages, two of the four Matsya handlers whose parameter lists have no frame parameter, the package modules matsya_service.guide_pages and matsya_service.source. Nothing enforces the import rule: the loader only imports the module.

The program calls two Matsya handlers by name, normalize_source to turn the request's source into a Source record and cycle to run the job. The other eleven run only when cycle or another Matsya handler calls them. The turn runner calls conversation_reply by name for each turn (§7).

2 The thirteen Matsya handlers

Matsya handler and parameters What it does Role it calls
cycle(frame, request) runs preparation and any distribution check, writes and elaborates the initial declaration once, then runs up to the cycle limit of iterations; each iteration writes prose from the preceding elaborated semantic object, reports the prose judge's findings, writes and elaborates one new declaration, and compares adjacent elaborated semantic objects; returns the record with status converged, not_converged or needs_input none directly
prepare(frame, source, calls, limit, formulation, target) preparation, from the source material \(P\) to the description \(M\) (Bellman-SYM writer §1): binds the reading controller to the source preparer, makes the job's initial search from the concepts the source material names, the new concepts first for a job that continues an earlier job of its session, calls the source preparer, SourceMaterial_to_BellmanStageProse, with the job's target and the kind of the source material, paper or description, for up to limit ordinary answers and its requests within its request rounds, checks the JSON answer and, on a paper, its references, each a quotation that must stand in the section of the heading it names and that the record holds with the lines it stands on, runs the form check, which the source preparer's own text states with the heading Structure before the seven of the paper form, reads the structure under that heading (structure_of), returning a description whose structure it cannot read as a failure of its form, and has the judge compare the description with the source; returns ready with the description, needs_input with questions, or not_converged with a reason SourceMaterial_to_BellmanStageProse, BellmanStageProse_judge
write(frame, description, calls, feedback, initial_refusal, references, formulation, target) writing, the map \(\Upsilon_0\) (Bellman-SYM writer): binds the reading controller to the Bellman-SYM writer, reusing preparation's passages for the initial declaration or searching from the prose of a later iteration; calls the writer with the target and structure for up to writer_rounds ordinary answers, parses and elaborates the files, and sends a refused file and the elaborator's refusal back for repair; returns the files, the elaborated semantic object or None, and the record of each round BellmanStageProse_to_BellmanSYMDeclaration
verify_distribution(frame, description, variable, evidence, calls) asks whether the description specifies the law of a named random variable; returns specified, missing or unclear with quotations and one question, after checking that every quotation occurs in the description distribution_check
prose_write(frame, outcome, calls) prose writing, the map \(\Upsilon_1\) (Prose writer): prints the dossier of the preceding elaborated stage or trellis, calls the prose writer with the stage-interface pages and the dossier, and retries a failed form check within prose_writer_rounds; returns the iteration's prose and its form findings even when the check still fails ElaboratedSemanticObject_to_BellmanStageProse
judge(frame, source_text, description, form, calls, formulation, target) calls the judge with the two texts in both orders, making up to judge_rounds attempts for each order; during an iteration it compares the prepared prose with the new prose and applies the target's comparison rule; returns the two reports and whether they agree; the result is recorded but does not decide convergence BellmanStageProse_judge
compare(frame, left, right) computes ElaboratedSemanticObject_comparator: returns the comparator's profile of two elaborated stages or trellises by calling the job frame's compare; calls no language model none
citations(files, description) reads each stage file block by block and returns, for every block, the sentences cited on # from: "..." lines and whether each occurs in the description once spacing is normalized none
unresolved_note(files) true unless note.md says exactly none or none. in any letter case, the section ## Values left to $fill of a recipe's note set aside, so a missing note counts as unresolved none
call(frame, role, parts, calls, instructions) puts the role's text, or instructions when a text is given in its place (every Matsya handler passes None), first under the label the instructions, passes the number of leading guide parts as the cached prefix, sends the message through the job frame's call, records a role_call_started event and then a completed, stopped, refused or failed event, appends the call's record to calls, and returns the answer text; a call the program refuses at a language-model token ceiling (What Matsya reads §4) raises CeilingReached and leaves no event after role_call_started the named role
writer_references(frame, index, excluded) makes the initial search of an invocation through the reading controller, which it receives as index: the query the invocation was bound with, at most retrieval_passage_limit passages, which the controller restricts to the collections the job's principal may read, requiring no mark model_prompt, with the source clusters excluded; excluded may add clusters to that exclusion; returns an empty list without an index, with a limit of 0 or without a query none
select_pages(guide, manifest_entry, selected) returns the chosen pages of one guide unaltered and in the guide's order; called by the module's helper _pages_of when a Matsya handler assembles a role's guide parts none
normalize_source(source) turns the request's source into the frame's Source record none
conversation_reply(frame, turn, calls), optional one turn of conversation mode (§7): searches once from the question, supplies the outputs of the job the conversation discusses, the session's selected job or else its latest current job, has the prose writer describe the dossier of a stage file the turn names, calls the conversation role through _requests within its request rounds, checks each answer's form, citations and decision list and sends a failed answer back within conversation_rounds; returns answered, needs_input or incomplete with its citations and decision list conversation_answer, ElaboratedSemanticObject_to_BellmanStageProse

Of the thirteen Matsya handlers, five, prepare, write, verify_distribution, prose_write and judge, call a role, each through the Matsya handler call, which sends the message; cycle calls the roles only through these five; and compare, citations, unresolved_note, writer_references, select_pages and normalize_source call none. The judge has two uses in a job: in preparation, to compare the prepared description with the source, and in each numbered iteration, to compare the prepared description \(M\) with that iteration's prose. The optional conversation_reply calls the conversation role through call and, for a stage file the turn names, the prose writer through prose_write.

3 The sequence inside cycle

cycle runs prepare first. It searches from the source material's concepts, writes the prepared model prose \(M\), and checks the prose against the source. A preparation with unresolved questions returns needs_input unless the request set force, in which case the source material is used as \(M\) and the questions and writer's assumptions are retained. The structure stated in \(M\) must fit the requested target; otherwise the job returns a question before writing files. When \(M\) names an income process only by a general distribution function, verify_distribution asks whether its law is specified. The initial write then writes \(D\) from \(M\) and elaborates \(D\) to \(E\). A supplied starting_declaration takes the place of this initial writer call; if the elaborator refuses it, the refusal is passed to write for repair. The initial writing is recorded separately, as initial_writing, at cycle 0.

For each numbered iteration, prose_write reads the dossier of the preceding elaborated semantic object and produces new prose. The judge compares that prose with the prepared \(M\) for a diagnostic report. write then writes one new declaration from the new prose and elaborates it. compare checks this elaborated semantic object against the preceding one. Thus iteration 1 is \(E \to M' \to D' \to E'\) and compares \(E\) with \(E'\). If they differ, iteration 2 is \(E' \to M'' \to D'' \to E''\) and compares \(E'\) with \(E''\). It does not repeat write(M) or produce an extra \(E'''\) in iteration 2. A successful comparison ends the job converged with the reason semantic_fixed_point; otherwise the next iteration begins from the latest \(E\), up to the cycle limit. citations checks the declaration's quotations against the prose from which that declaration was written, and unresolved_note checks its writer's note. Those results and both prose judges' reports remain available for review; none decides convergence.

A writing whose last answer requests material after its allowed request rounds ends not_converged with request_rounds_exhausted. If an iteration cannot produce an elaborated semantic object, it records no comparison for that iteration; the latest successful writing remains available. A call refused at a language-model token ceiling ends not_converged with token_ceiling_reached, retaining the calls and writings recorded so far. A cancellation stops before the next language-model call, after any call already sent finishes.

Inside prepare and write, every call to a role goes through _requests. Each message holds the cached prefix (the instruction text and the guide pages the settings name), then the reading controller's parts (the retrieved passages, the addresses the role may request with its remaining allowances, and the material its requests added with their outcomes, each item once), then the task's input, the formulation, the job's target and, for the writer, the structure the description states, and any correction feedback, which stand in every message of the invocation. _requests examines each answer for the request form before the role's own parsers; a request is answered by the controller, which consumes a request round and no ordinary round, and the role is called again with the result; the first ordinary answer goes to the role's parsers and consumes one of preparer_rounds or writer_rounds. When the role answers with a request and no request round, or no ordinary round, remains, the controller executes nothing and _requests returns None, which ends the invocation with request_rounds_exhausted.

The writer returns the files of the job's target and no other, which the job frame's elaborate_files(files, target) checks: for a stage, one stage file <key>.bl and the note note.md, elaborated as one text; for a period, the stage files and period.yml, elaborated as a trellis of that period repeated twice and then held, printed and compared as its one period; for a trellis, the stage files, a period file for each period template, period.yml or period.<name>.yml, and trellis.yml, elaborated as a trellis; and for a recipe, the files of a trellis, the recipe spec.yml, a methods file stages/<key>/methods.yml for each stage the description says how to solve, calibration/<model>.yml and settings/<model>.yml, written into a temporary folder in the model folder's layout and read by the Bellman factory's load_recipe with no fill, then elaborated and bound by specify_trellis with the kinds of binding the recipe holds, so that a calibration whose slot $fill stands unbound, or a stage without a methods file, is checked for what it holds. A recipe is held, printed and compared as the trellis of its elaborated stages, since its methods, calibration and settings are read from files and not written back into prose. A converged job's artifacts place each stage file under declaration/stages/<key>/ and every other file but the note under declaration/ at the path its name writes, which puts a recipe's methods files in their stages' folders.

The initial_writing record holds the first declaration's rounds, files, citations and digest. Each numbered cycle holds its prose writing, judging, one declaration writing, comparison, citation check and writer's-note check. The job runner reports preparation, writing, prose_writing and judging; initial writing uses cycle 0. Every language-model call is recorded with its role, message digest and length, answer digest, token counts and any provider failure. The job runner's progress callback raises JobCancelled before the next call when cancellation was requested, so a call already sent finishes and no further one starts. The processor records under reading the identities of the guide pages and index passages each call received, the searches it made and the outcome of requests; the record holds no message text.

The job store keeps this record whole, and GET /v1/model-iterations/{job_id} returns one of two views. The default products view holds the schema, target, structure, status, reason, prepared prose (description), questions, paper checks and cycles_run, the count of numbered iterations. available_writing holds the latest nonempty parsed files, their cycle number (0 for the initial declaration), and the prose from which they were written; last_cycle holds the final numbered iteration's files, judging and adjacent comparison, which may be absent if that iteration stopped early. last_completed_comparison identifies the latest pair actually compared by left and right cycle numbers, even when the final iteration stopped before comparison. reading is reduced to index and guide digests, and usage to calls and tokens charged. The full view, view=full, holds initial_writing and all numbered cycles for examination or training. products_view in processor.py derives the default view from that record.

For a period, trellis or recipe, the elaboration bridge reads Bellman's selected connections once from the stage occurrences already constructed. The dossier names the resolved stage and field at each selected connection, including connections between periods. Its digest records the ordered stage occurrences, those connections and the effective parameter values in each period. The deterministic comparison checks the connections and effective values under one matching of the stage occurrences and their names. A connection or route that Bellman cannot certify, including a backward value type that does not match, is returned as a refusal before the two declarations can compare equal. A complete recipe uses the trellis returned after its requested bindings have been applied. If $fill still leaves a parameter without a value in a period, the digest and dossier distinguish known source values from bound values and name the unresolved period. Matching partial recipes can compare equal as declarations; the missing value remains unbound.

4 The job frame a Matsya handler receives

The job frame is one record, the dataclass Frame of frame.py, built by the processor for each job; the word frame alone names the package. A Matsya handler uses the bellman package and the meaning-map-training package only through the job frame and imports neither.

Attribute What it is
texts the seven instruction texts by role key, and the conversation role's when the configuration enables it
guides, guide_manifest the three guides by short name (writer, reader, calculus) and their entries of the page manifest: the ordered pages and, for a manifest of the form matsya-guides/3, each saved page's sections, authored links and tag memberships
settings the checked settings, with roles as RoleSettings records and ceilings, the language-model token ceilings, as a Ceilings record
call(role, parts, prefix) the function that sends a message to the provider: the ordered parts of one message and the number of leading parts marked for the prompt cache; returns the answer with its token counts. It is the method call of the fixed caller ProviderCaller of roles.py, which counts the message's tokens first, refuses a message that would not fit the language model's context window with PromptTooLong and a call that would pass a token ceiling with CeilingReached, and charges every attempt to the job's token ledger
record, progress the job's record, begun by the processor, and the job runner's progress callback
index, source, references, earlier the reading controller ReadingController of retrieval/context.py, which the processor builds over the snapshot of the retrieval index the job holds and which is a Matsya handler's only access to the index and to the guides' records: bind binds it to the role of an invocation of prepare or write, search makes the invocation's initial search, reuse places passages an earlier invocation retrieved, request_of and resolve examine an answer for the request form and answer a request through the snapshot's related and read (The retrieval index §9) or the guides' records, parts gives the parts it writes into the next message, and called, ordinary and end record the calls, the ordinary answers and why the invocation stopped (What Matsya reads §5); the job's Source record; the passages of preparation's initial search; and earlier, the job of the same session that this job continues, with its identity, status, source digest, description, questions, formulation and concepts, or None
join_parts, sha256 the joining of a message's parts under ===== <label> ===== lines, and the digest function
elaborate_text, elaborate_trellis, period_joins, dossier_lines the four functions of the bellman package that the frame calls: the elaboration of one text and of a trellis, the joins of a period, and the dossier printer
elaborate_files, dossier_of, parse_writer_files, digest_of, profile_equal, allowed_declaration_name, form_check (check_reader_form in the module), compare (compare_outcomes in the module) the functions of meaning.py: parse a Bellman-SYM writer's answer into files, elaborate them (elaborate_files, which computes the Bellman-SYM elaborator BellmanSYMDeclaration_to_ElaboratedSemanticObject), print the dossier with the stage names hidden, compare two elaborations with the comparator of packages/meaning-map-training (compare, which computes ElaboratedSemanticObject_comparator), check a description's form
targets the four targets of a job, stage, period, trellis and recipe, in the order in which each holds the one before it (TARGETS of meaning.py), which the Matsya handler cycle reads to decide whether the job's target holds the level of the structure the description states
errors the exception classes a Matsya handler raises or catches: ModelAnswerError, MeaningRefusal, IncompleteResponse, PromptTooLong, ProviderError, ProviderRefusal, ProviderRejected, and the set STOP_REASONS

For a turn of conversation mode the turn runner fills the same record: index is the reading controller bound to the turn (§7), source is None, record holds the turn's identifiers, and call is the fixed caller's, wrapped so that the turn runner records each call and its events itself; the call list a Matsya handler receives for a turn is its own and no record reads it.

A Matsya handler raises ModelAnswerError when a language model's answer lacks the required structure or evidence, with one of the 27 validation codes the program fixes, such as json_decode, judge_quotes or writer_input_quote; the job runner records such an error as invalid_model_response.

5 How the program loads and checks the module

configuration.load runs its checks in a fixed order and stops at the first failure: the files against manifest.json; the three guides against their page manifest, the page markers and, for a manifest of the form matsya-guides/3, each page's saved digest, its sections' spans and the targets of its available links; settings.json; the import of the Matsya handler module under the module name matsya_configuration_handlers; and the thirteen signatures, with conversation_reply when the settings name the conversation role, each name present and callable with exactly the slot's parameter names in the slot's order, read with inspect.signature. Type annotations, default values and return types are not compared, and no other function is checked, so helpers may be added, renamed or removed freely, and a configuration that does not name the conversation role may hold a function named conversation_reply, which is then not checked. Before the signatures the loader reads the conversation role's parts together, after the settings' types and before the readers of roles, ceilings and reading: the role's reading entry, its entry in ceilings.roles, ceilings.turn, conversation_rounds and conversation_pages, then the text texts/conversation-answer.md; a part missing with the role, or present without it, refuses the folder naming that part. A failed check raises ConfigurationRefused, whose detail names the file or the Matsya handler: when a check fails at the start of a job, the job fails with the code configuration_refused and no language model is called; when it fails before the server starts, matsya-serve refuses to start. The folder is checked on three occasions on a server: by matsya-serve before the server starts, by the application's start-up, and at the start of every job, so an edit to the folder takes effect at the next job. Two commands act on the folder: python -m matsya_service.configuration manifest <folder> --version <version> rewrites manifest.json from the files present, and python -m matsya_service.configuration check <folder> loads the folder as a job would and prints its version and digest, then a line that names the form of the guides' page manifest and says whether its relationship records were checked, or configuration_refused with the detail.

6 Changing a Matsya handler, adding a helper, adding a slot

To change what a Matsya handler does while keeping its name and parameter names, edit the module, rewrite the manifest with the manifest command, and run the check command. The package's tests do not load the configuration folder that the service uses: they copy a second configuration kept for the tests under packages/matsya/tests/fixtures/configuration/, whose Matsya handler module and eight texts, the conversation role's among them, are byte-identical with the service's folder on 9 October 2026, so a change to the service's module is tested only when the same change is made to the test copy. The test copy's guides are written by the guide builder from the small documentation tree of packages/matsya/tests/fixtures/documentation/, which holds a stand-in for each core page and the pages that test the links and tags, under that tree's own construction policy.

Adding a helper needs only that it be written in the module and called from one of the thirteen Matsya handlers, since the program neither calls nor checks it.

Adding a slot, renaming one, changing a slot’s parameter names, adding a role or adding a setting changes the program. Each requires coordinated changes to the program and configuration. An optional slot, such as conversation_reply, stands in OPTIONAL_SLOTS with the role that requires it in ROLE_SLOTS, an optional role in OPTIONAL_ROLES of roles.py and its settings in OPTIONAL_SETTINGS, and the loader checks them only in a configuration that names the role. A new slot needs its entry with ordered parameter names in SLOTS of configuration.py, a call to it from the program or from another Matsya handler, the function in every configuration's module including the test copy, rewritten manifests, and a corresponding row in the handler table in §2. A new role needs its key in ROLES of roles.py, a text texts/<role key with hyphens for underscores>.md, an entry in the roles object of settings.json, and a Matsya handler that calls call(frame, "<role key>", parts, calls, None). A new setting needs its key and type in SETTINGS of configuration.py, the key in settings.json, and a Matsya handler that reads frame.settings["<key>"], because the loader refuses a key present in only one of the two.

A trained candidate is a new configuration folder with its own manifest and version, and a candidate whose Matsya handler module differs from its parent's is recorded as a commit together with the run that accepted it.

7 One turn of conversation mode

A configuration that enables the conversation role, conversation_answer, answers a question asked in a session in a turn, which the route POST /v1/sessions/{session_id}/turns appends to the session as an entry of the user and records as queued. The turn runner, TurnRunner of conversation.py, which the program holds and a training pass does not change, then loads the configuration, fixes the turn's snapshot of the index, builds the turn's language-model token ledger, binds the reading controller (What Matsya reads §8), reads again the passages the previous turn cited, elaborates a stage file the request names, and calls conversation_reply(frame, turn, calls). turn is the record Turn of conversation.py: the turn's identifier and session, the question and its entry number, the named fields, the elaborated stage file or its refusal, never the file's text, the session's entries up to the question, the previous turn's decision list, the retained passages and the snapshot's digest.

The starting conversation_reply places the guide pages conversation_pages names, which the controller reports as frame.index.pages, after the instruction text as the cached prefix; makes one search from the question through frame.index.search; has the controller supply, with frame.index.supply_job, the outputs of the job the conversation discusses, which the turn runner names: the session's selected job or else its latest job that holds a record and was current at its end, never a job that was not current unless the selection names it; the label of each output of a job that was not current states the version of the session's text the job was built from and the version the text is at now, the turn's result names the job under job, and the job's stage files are never supplied this way; and, for a stage file that elaborated, calls prose_write on the elaborated semantic object, so that the role receives the dossier and the prose writer's description of it. It then calls the role through _requests, as prepare and write call theirs, so that every answer is examined for the request form before any other parser and a request is resolved by the controller within the role's request rounds. An ordinary answer is read as one JSON object with _json_answer and checked: its status and fields, each citation with frame.index.check_citation, the check the turn runner makes again, and the form of each item of the decision list. A failed answer is sent back with your previous answer and the faults of your previous answer until conversation_rounds answers have been given. The Matsya handler returns answered with the answer, and with submit_job when the role starts a job at the user's request, checked against cycle_maximum, or needs_input with the role's questions, each with its citations and decision list, or incomplete with request_rounds_exhausted or conversation_rounds_exhausted, no citation and the previous decision list, and records why the invocation stopped with frame.index.end.

The turn runner checks the return: a return of another form ends the turn failed with processing_failed; a citation of material not supplied in the turn, or with a quote absent from it, ends the turn incomplete with unsupported_citation; an incomplete status must agree with the turn's record of allowances, ceilings and calls; and a call refused at a ceiling, or one the provider could not complete, ends the turn incomplete whatever conversation_reply returns or raises. It decides whether the turn is current, appends the answer, or the questions, as entries whose origin is the turn and which reply to the question, and stores the record. The turn's states, statuses, reasons, fixed sentences and record are the program's, so that a Matsya handler can change what the role reads and how its answers are repaired, but not the permissions, the snapshot, the limits or the acceptance of an answer.