Repository navigation
An extractor service parses SQL, TOML, Markdown and HTML, and the server checks what it returns - #166
Merged
Merged
Conversation
…ver checks what it returns Related: #157 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-extraction-contract
branch
from
November 3, 2026 08:11
9c9b4fc to
9d5c243
Compare
…at decodes to a lone surrogate Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…t version as the integer 1 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…ce whose parser crashes as corrupt Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…arser's exception from a child that never ran it Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
… keep a missing parser dependency retryable Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…ending in a bare ? or # Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…its digits Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…he contract's integers are signed Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…lure reason Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…hon's digit limit as set Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
…tead of counting its calls Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related: #157
Related: #142
Changelog category (leave one):
Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):
A reference extractor service (
extractor/) parses SQL, TOML, Markdown and HTML files into one extraction artifact (ordered blocks with line spans, SQL statement and TOML key-path locators, exact lookup keys, a coverage record), and the server can send an original to the extractor each format is routed to (LOOM_DOCUMENT_EXTRACTOR_URL,LOOM_DOCUMENT_EXTRACTORS_JSON) and checks what comes back. No operation uses it yet; the server parses no original itself.Why
This is the first workstream of the file-ingestion proposal: the source, locator and capability contract that every later piece (server-side ingestion jobs, revision-qualified citations, office and tabular formats) reads. Today the knowledge plane takes text the client extracted: the CLI reads an unknown extension with a lossy decode, and every format is cut into the same character windows after its headings, so a SQL statement or a TOML key has no locator and no exact name to be found by.
Parsing an uploaded file runs a parser over input the uploader controls, and operators may want their own utilities for some formats. So extraction runs in a separate service, never in the server's process (
docs/architecture/document-extraction.md):server/knowledge/domain/extract/:Artifact,Block,Locator,Coverage), format routing (server/core/document_formats.py, where the settings can check route keys against it), the structural chunker and the client (server/knowledge/app/extractors.py). The extractor (extractor/loom_extractor/, its ownpyproject.toml) holds detection, decoding and every parser, and imports nothing from the server;test_package_contracts.pychecks that no server module imports it,sqlglot, or (in the knowledge plane) a parser library. The extractor gets bytes and returns JSON: no Loom token, no database credential, no bucket access.LOOM_DOCUMENT_EXTRACTORS_JSON's entry for the format (or for its media type, when the media type names that format), elseLOOM_DOCUMENT_EXTRACTOR_URL. Each service gets its own token fromLOOM_DOCUMENT_EXTRACTOR_TOKENS_JSON(every key must be a configured URL, so a typo is refused at load rather than sending the shared token), elseLOOM_DOCUMENT_EXTRACTOR_TOKEN. A format is extracted only if that service's/v1/capabilitiesdeclares it (read again after a minute). No service, an undeclared format, an unreachable service, a call pastLOOM_DOCUMENT_EXTRACTOR_TIMEOUT_S(one deadline for each whole call: reading the capabilities, and sending the original and reading its artifact), a refused token (401,403,407),408,429,format_unavailable, a5xxor any other answer that is neither200nor4xx(a redirect) isExtractorUnavailable(try again later); a refused source, or a response that breaks the contract (invalid_artifact), isExtractionFailedwith its code. There is no in-process fallback. A.doc,.xlsor.pptname is refused before any call.LOOM_DOCUMENT_EXTRACTOR_MAX_ARTIFACT_BYTES, thenparse_artifact(in a thread, off the event loop; its error paths name at most 40 characters of a key, so checking stays linear in the response) checks the schema version, the format asked for, block types, unique ids, parents that are earlier blocks, at most 10,000 keys of 1,024 characters and 64 section-path entries of 500 characters per block (the reference extractor fits every block to these before it answers, marking a block it cut and naming the loss incoverage.lost, so the artifact does not report itself complete), locator ranges, coverage counts, valid Unicode, JSON numbers (noNaN; signed 64-bit integers, other numbers within a double, so not1e999) and nesting depth (the reference TOML parser leaves outattrs.valuefor a value nested past 8, so its own output stays inside it);completeis recomputed and a disagreeing flag refused; unknown fields are dropped. The server addresses the artifact by the SHA-256 of its own serialization./v1call needs the bearer token; the service refuses to start without one of 16 characters or more. The service and each child are non-dumpable (PR_SET_DUMPABLE), so a child cannot read the service's environment (the token) through/proc. A child can start no process (RLIMIT_NPROC0; the service refuses to start as root or withCAP_SYS_ADMINorCAP_SYS_RESOURCEpermitted, which the kernel does not hold to that limit, and sets no-new-privileges, so no setuid binary or file capability gives a child one), so nothing a parser starts outlives the extraction; a child still running at a timeout, a disconnect or a cancelled handler is killed with its process group before its slot is freed. A limit of 0, or a non-finite one (such asLOOM_EXTRACTOR_CONCURRENCY=0orLOOM_EXTRACTOR_TIMEOUT_S=nan), is refused at start. Extractions run one at a time by default (LOOM_EXTRACTOR_CONCURRENCY1): a child is readable by its user's other processes until it makes itself non-dumpable, so a concurrent child taken over by a hostile source could read its source in that moment; scale with replicas, and the docs say so. Closing that moment for concurrent children needs a user or namespace per child, which is for the packaging pull request. Each extraction runs in a child started in/with-Pand onlyPYTHONPATH,PATHandLC_ALLin its environment, its command line holding only its limits (the file name and options come on stdin); before it reads the source it sets its own address-space, CPU and file-size limits. The service kills it at the wall-clock timeout, when its caller disconnects (answering 499), or when its output passes the artifact bound, and reads a source only under one ofLOOM_EXTRACTOR_CONCURRENCYslots, so that bounds the originals held in memory too. Network and file-system reads are left to the container, in the packaging pull request.docs/reference/extractor-contract.md, so another extractor can serve the sameGET /v1/capabilitiesandPOST /v1/extract.What the reference extractor's parsers do:
blocks(type, text, section path, parent, locator, exactkeys),coverage(unit, total, extracted, failed units with reasons, lost capabilities),warnings,options,attrs. Serialized as sorted compact JSON with aschema_versionand addressed by its SHA-256, so a parser or option change is a new artifact (an extraction generation) of the same source revision, never an edit.format_mismatch; legacy DOC/XLS/PPT are refused. Text decodes strictly (UTF-8, a UTF-16 or UTF-32 byte-order mark, or a declared encoding): an undecodable byte is anencodingfailure naming its offset, never a replacement character in the index.;in a string or comment does not end one; each keeps its line and char span, kind, the object it creates, the objects it writes (a materialized view'sTOtable, what aDROPdrops), the tables it reads (not its CTEs), its columns and comments; every qualified name is also a key by its last part, unquoted (my.tablefordb.`my.table`, since sqlglot writes"for every dialect's quoting). The dialect is declared, or detected: a candidate whose tokenizer reads a longer window of the script ranks first (so one that refuses the script cannot win on a shorter cut), then the one that turns the largest share of the first statements' text into syntax trees (a share, so a dialect that splits a$$body into fragments does not win; a script of at most 50,000 characters is read whole); a tie is reported with the tied candidates, and the script is split with the first of them whose tokenizer reads it whole; past 50,000 characters a first statement or quoted body longer than the window may be detected wrongly, and the docs say to declare the dialect. An unparsable statement stays searchable and setscoverage.lost = ["sql_structure"].retention.rules[1].days), its line span (multi-line values included), comments and original text. An invalid file stays text withcoverage.lost = ["toml_types"].markdown.py); the server'sknowledge.addheading splitter is unchanged.Alternatives considered: tomlkit keeps comments but gives no line positions, so the scanner would be needed anyway; a regular-expression SQL splitter breaks on
;inside strings and dollar-quoted bodies, which the dialect tokenizer handles. A client's own command lines (GO, a lone/,DELIMITER, backslash commands) are not split on: the script splits on its;tokens, and a statement a command line joins, or a body the client sends whole, comes outUNKNOWNand recorded in coverage. Splitting by each client's rules needs a lexer that knows where a line may start outside strings, comments and bodies; the code index'slang_sql_splithas one, but its segments carry trailing comments that sqlglot then reads as extra statements, and two attempts to combine it with the dialect tokenizer here each lost statements on scripts the other handled. Ingestion of SQL files can take it up with its own test corpus. The code index's cue-based dialect detector (lang_sql_dialect) scores keywords; this parser scores what each dialect actually parses, which is what its blocks need. The code index'slang_sql_objectsalso names what a statement creates, reads and writes, but over that splitter's statement records, and the knowledge plane does not import the code plane; the two keep separate parsers. The Markdown, text and HTML parsers count coverage from their blocks (the non-blank lines inside a block's span or that are markup, and the visible HTML characters the blocks hold), a guard against a change that drops text rather than a measure of loss within a block; the SQL and TOML parsers can lose structure and record it. The extractor needssqlglot>=30.27,<31(the version tested, below the next major, since it importssqlglot.tokenizer_core; about 1 MB, pure Python); it is installed with the extractor, not the server.Alternatives for the boundary: parsing in the server's process behind a child-process sandbox (as the code index runs repository jobs) keeps the parsers' dependencies in the server image and gives an operator no way to plug in another utility; a gRPC contract adds a schema toolchain for two calls that JSON over HTTP serves.
The extractor's image with compose and Helm entries, the PDF/office and spreadsheet/CSV/Parquet parsers (a layout-aware extractor, if adopted, as another extractor behind the same contract), the object store, ingestion jobs (whose worker calls this client) and search changes follow in separate pull requests. The CommonMark fixes to the
knowledge.addheading splitter found while building the Markdown parser landed on their own (#171); this pull request leaves that splitter as it is onmain. The source revisions, serving pointers and jobs are planned to live in Postgres under the Postgres authority the related issue introduces, with ClickHouse holding them on a ClickHouse-only deployment, which stays the default.Scope and risk
extractor/(the reference service, not part of the server wheel or image),server/knowledge/domain/extract/(contract,validate.parse_artifact,structural),server/core/document_formats.py,server/knowledge/app/extractors.py. Nothing in the server calls the client yet.document_extractor_urlanddocument_extractors_json(secrets, read from the environment only: a URL can carry a credential, and a listing logs only a service's scheme, host and port),document_extractor_tokenanddocument_extractor_tokens_json(secrets),document_extractor_timeout_s(180),document_extractor_max_artifact_bytes(64 MiB). Both URL settings must be http(s) with a host and port the client can parse (a port such as87a0or99999, a host that is not valid IDNA, or a query or fragment is refused at load); the error names the entry, never the URL. A route key must be a format or a media type that names one (matched without parameters or case, and given once), and a token key a configured URL.extractorextra (sqlglot) is for tests in a development environment;devincludes it. Lint, format, mypy and pytest coverextractor/(src,mypy_pathandpythonpathname it).knowledge.addchunker, its logging setup and the server image are unchanged frommain.Compatibility, rollout and rollback
Tests
tests/unit/test_document_extraction.py(128 tests, 187 cases, a TOML integer outside signed 64 bits (a 4,301-digit decimal and a long hex literal among them) making the file invalid TOML, its reason naming that key path in key order (a table reopened later in the file comes with its first part; a path is spelled only for that integer, so the check is linear: 20,000 levels of 1,000-character keys take 0.08 s, where a path per value took over 60 s), among them a heading past the section-entry bound, a statement past the key bound, a TOML header past the section bound, a key past the length bound and a 50,000-part header in bounded time; the structural-chunk tests read each artifact back throughparse_artifactfirst, as the server reads any extractor's response) over hand-labelled fixtures intests/unit/fixtures/knowledge/: ClickHouse and Postgres DDL/DML (line spans and char offsets equal the source text,;in a literal, comments attributed to their statement, kinds, created/written/read objects), dialect detection (a $$ body cut by every prefix, a tokenizer that refuses the script, a first statement past the window), a declared dialect and the default when nothing parses, an unparsable statement, an untokenizable script; TOML key paths, nested arrays of tables, multi-line values, quoted keys, types and values, comments, invalid TOML; Markdown and HTML block types, line spans and dropped invisible elements, HTML blocks whose end tags are left out, plain text without headings, code-block windows that cite their own lines; CTEs, self-reads and comments around a;; format detection and strict decoding (an error's byte offset counts a byte order mark; an escape codec decoding to a lone surrogate, and a punycode or idna error, refused asencoding); thematic breaks as markup (spaced ones too); a long heading line kept whole with its markup read in a bounded head; a heading line with a long run of blanks; the declared dialect stored assql_dialect; an ATX line whose title cleans to nothing kept as a one-line paragraph; a comment's closing-->over---refused as a title; an HTML page's<title>kept asattrs.title; block-tag and tag-only HTML lines refused as titles; a comment,<!, or raw-text HTML block ending at its end marker, so the next line can be a setext title, and a tag-only line inside a paragraph kept as its text; a TOML key with DEL escaped in its path; a deck opening with a rule then# Agendakeeping its heading; a block comment starting on a;line kept with that statement, and a comment on the line it ends on too; a bare#as an empty heading; a function, procedure, rename andCOMMENT ONdescribed by what they define and write, never as reads of themselves; hostile Markdown and TOML inputs parsed in bounded time; empty front matter; a long heading windowed with a bounded title in its section paths, each window citing the heading's whole span; a tree sqlglot cannot describe read as an unparsed statement; a numbered line inside a wrapped paragraph kept as prose; a NUL byte behind a UTF-8 byte-order mark read as binary; a declaredutf-8orutf-8-sigerror offset counting the mark; a page with only an unclosed<head>read whole; two spellings of one codec addressing one artifact; a declared byte-order codec (utf-16-le) dropping the mark; a padded dialect name addressing the same artifact; a dialect with sqlglot settings refused asinvalid_option;USE dbreading no table; a U+FEFF character after the byte-order mark kept as text; a quoted dotted name's last-part key, unquoted; a client command line read as no SQL and recorded in coverage; a zip whose entry name is not its flagged encoding; a quote line ending a paragraph, while the lines of one quote stay one block; text inside an unclosed hidden HTML element recorded as not read; emphasis around a code span in a heading; a bare list marker over a rule kept as an empty item; a multi-line TOML string closing on extra quotes; HTML and TOML parser versions naming the Python whose parser read them; quoted and escaped TOML key paths; a sqlglot crash read as an unparsed statement;<li><p>list items; rules ending the block above; mixed chunk types; slides that open with a rule; non-ASCII SQL char offsets; JSON round trip and content addressing; structural chunk packing, per-statement chunks and windows that cite their own lines.tests/unit/test_extractor_service.py(28): the token on every/v1call and none on/healthz; no start without a 16-character token; the declared formats and options; an extraction run in a child; typed 422s (format_unavailable,invalid_option,format_mismatch,encoding, a bad dialect,too_large); a child past its time killed (timeout), past its memory (resource_limit), past the artifact bound stopped and its pipes drained (resource_limit); a child that sees no environment (no token) and cannot write a file; a parser's exception a422 corrupt(a retry would crash the same way, so the source is refused), and a child that fails before its parser runs, or a parser whose dependency is missing, a 500 (the service's fault, worth a retry); a child non-dumpable, in/, with its directory offsys.pathand no request on its command line; the service process non-dumpable (another process of the same user cannot read its environment); a cancelled extraction's child killed, a disconnected caller's, and a cancelled handler's before its slot is freed; a handler cancelled while it reaps a gone caller's child stays cancelled; a child that cannot fork (skipped as root); no start as root, withCAP_SYS_ADMINorCAP_SYS_RESOURCEpermitted (read fromCapPrm, refused when unreadable), or with a limit of 0 ornan/inf; a child under no-new-privileges; the service and the test environment pinning one sqlglot.tests/unit/test_knowledge_extractors.py(116), the reference service in process over ASGI and stub services for chosen answers: extraction read back checked; options reach the service; routing by format key, then media type, then the default URL; no service configured, an undeclared format, an unreachable service and a refused token each unavailable with no fallback; a refused source keeps its code, and a legacy name is refused with no call; a response asked for uncompressed and read as sent, a compressed200,422or capabilities answer unavailable and never inflated, a URL ending in a bare?or#refused, declarations read once a minute, and a listing reading an unreachable service once and logging none of its URL's credentials; acontract_versionoftrue,1.0or"1"refused; a source over the declared size not sent;5xx,401/403/407/408/429, a redirect and a204unavailable (a502with a long error page too: the status is read before the body, and a refusal's body only up to 64 KiB),422/400refused with an invalid code read asrefused; a stub's artifact read through the contract and a wrong format refused asinvalid_artifact; a422body nested too deep read asrefused,format_unavailableas unavailable; capabilities nested too deep unavailable and declaring nothing; a response dripped past the timeout unavailable; each service's own token, and no header without one; a token for no configured URL, not a string, or for a URL an earlier entry already names, refused at load; a format routed only by media type available, and one whose own route hides its media type's listed asextractwould send it; a media-type route used only for its own format, its key matched without case or parameters by both listing and extracting, and a key that names no format, or a second spelling of one media type, refused at load; a TOML value nested 20 deep extracted and accepted; an artifact over the bound refused while read (resource_limit, as the service names it); 36 contract breaks each refused (schema version,trueor1.0among them, format, parser, block type, text, lone surrogate, duplicate or empty id, parent, depth, keys, section path, line and char spans, locator type, nesting, options, warnings, coverage counts and unit, acompletethat disagrees, failed entries); oversized, non-JSON,NaN,1e999and past-signed-64-bit integer bodies; a 2 MB key over a million-item list checked in linear time; too many or too long keys or section entries refused, and a refused value not repeated whole in the error; the ~850 windows of a 1 MB block with 10,000 keys chunked in linear time, sharing one keys tuple;completerecomputed and unknown fields dropped; format naming from declaration, name and media type; legacy names and unknown declared formats refused; URL settings validated without naming the URL; the client's timeout and token from the settings.tests/unit/test_package_contracts.py: the server imports no parser orloom_extractor, and the extractor no server module.test_settings_defaults.py,test_settings_env_contract.py,test_settings_json_fields.py,test_settings_file.py,test_tunable_constants.py,test_test_inventory.py,test_doc_links.py,test_public_copy.py,test_agent_instructions.py: pass with the new settings and pages.Linear in input size (line numbers by bisection over newline offsets): with the dialect declared, 5,000 SQL statements extract in 0.6 s and 20,000 in 2.3 s; a 1 MB and a 4 MB single-paragraph log extract and chunk in 0.08 s and 0.29 s. With the dialect detected, a 50-statement script takes 0.06 s and a single 456 KB
INSERT ... VALUES3.5 s, of which detection is 1.4 s (each of the eight dialects reads at most 50,000 characters per window; one whose tokenizer refuses a window reads the next shorter one, up to about seven windows) and the chosen dialect's parse of the whole statement 1.9 s, the same as with it declared. Reproduce with:make format-check,make lint, the mypy gate: pass.pytest tests/uniton the rebased branch at 10cbb54: 25,654 passed, 20 skipped, 1 xfailed, none failed (test_rmt_version_unit.py::test_no_writer_builds_a_millisecond_versiondeselected, as it fails onmaintoo). The commits after it touch only the TOML parser, the artifact check's number bounds, one client comment and their docs; the extraction, client, service, package-contract, settings and docs test files pass at the head (584).AI assistance in the code (leave one; writing this description with AI is fine):
AI-generated (an agent wrote most of the diff): Claude Code. Every locator in the parser tests was read off the fixture files by hand.
I can explain every line of this diff and how it interacts with the rest of Loom.
Checklist
make format-check,make lint,make typecheckandmake test-unitpass; the integration suite passes if server behaviour changed.docs/reference/configuration.mdand thedocs/reference/tables (python scripts/codegen/docs_reference.py), the reach manifest,schemas/schema.sql(make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).docs/describe the system as it now is, and this description names any operator steps and wire changes.tests/unit/test_public_copy.py).git commit -s), as CONTRIBUTING.md asks.🤖 Generated with Claude Code