Skip to content

namespace.tune drafts the chunk size and stride and an extractor route per format from a namespace's documents - #258

Merged
zlareb1 merged 8 commits into
mainfrom
feat/i160-doc-tune
Nov 4, 2026
Merged

zlareb1 merged 8 commits into
mainfrom
feat/i160-doc-tune

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Related: #160

Changelog category (leave one):

  • New Feature

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):

namespace.tune now drafts document settings: a chunk size and stride, checked by cutting a sample of the namespace's documents again at the current and proposed values, and an extractor route for each format whose ingests failed or lost structure. As with the other drafts, nothing is applied; each draft names the setting, the evidence and the platform-admin write that would apply it.

Why

namespace.tune drafted only the settings that create memories. A namespace's documents are cut by knowledge_chunk_size / knowledge_chunk_stride and extracted by the service LOOM_DOCUMENT_EXTRACTORS_JSON routes each format to. Until now, finding out whether those values suited a namespace meant reading knowledge.inspect by hand and guessing. Tune now turns that evidence into a draft with a real target and the same approval contract.

  • Chunking. Up to namespace_tune_document_sample live documents (default 50, picked by cityHash64(source_uri), so the sample is spread out and repeatable) are cut again in process. Each document goes through the chunker its write path uses: a text document's text through chunk_document, an ingested document's stored artifact through chunk_artifact. Which one applies is decided by whether the row has a stored artifact (artifact_sha256), in both the SQL and the loader. The sample is cut at the current values and at each candidate. No model is called, nothing is written and no text is returned. chunking reports chunk count, sizes (min, median, p90, max), sections, sections_cut, the largest embedding input in tokens and how many inputs are over the embedder's limit. A section counts as cut when the size splits it into more chunks than its structure alone makes, measured by cutting it again at an unbounded size, so a SQL statement that is its own chunk is not counted. There are two rules (version 1):
    • Over the limit. If any input is over the embedder's token limit (the provider refuses it), the draft is the largest smaller size that fits.
    • Sections cut. If more than a quarter of the sampled sections are cut, over at least 5 documents, and the limit is known, the draft is the smallest larger size, up to 4x the current one, that keeps three quarters of the sections whole within the limit.
    • With knowledge_chunk_size 0 or less, the chunkers cut no window: a text document is one chunk and an ingested one is a chunk per block. No size is drafted; the sample is still reported and skipped names the value. A knowledge_chunk_stride of 0 or less is treated the same way. The chunkers handle it without looping (a section or block longer than the size is one chunk), but scaling it would draft a stride of 1.
    • Each candidate size is tried once, nearest first, with none below 200. When knowledge_chunk_size is at or below 200 and inputs are over the limit, skipped names the value in force.
    • The stride is clamped to the size once and keeps its ratio to the size. preview holds the before and after. apply is settings.set (POST /v1/admin/settings.set, platform admin) with expected, and apply_also sets the stride.
  • Extractor routes. These come from the per-source jobs whose current job failed format_unavailable, with the format read by format_of from the job's filename, media type and format option, and from incomplete extractions per format. The service a source goes to now is read with endpoint_for(format, media type), so a media-type route (application/pdf) is the service judged. Failed sources whose service declares the format now are told to ingest again. The rest get a route for the format itself, which wins over a media-type route, when a configured service declares the format in GET /v1/capabilities. One ranking picks the service for both kinds of evidence. Of the services that declare the format (for incomplete extractions alone, those that did not make them), it prefers one the format's sources already work on, meaning extracted whole or failed sources whose service declares it now; else one its media-type routes reach; else any. Within each tier, a service that did not make the incomplete extractions comes first. A route can still move sources that extract whole on another service, and its rationale names them. A route that does not answer the incomplete extractions says so in skipped. The draft names that service by the setting that holds its URL and never shows the URL, which can carry a credential, so args_complete is false. The change takes effect at restart (via: environment). If no configured service declares the format, skipped says so (extractor.<format>) and no route is drafted.
  • Decision-extraction instructions: not drafted. loom decisions extract and the source sync's mining build their prompt from fixed text (dx.system_prompt). No request, namespace or org setting carries instructions for them, so there is no real target. Adding one would be a new extraction input on the memory write path, which belongs in its own change. skipped says this whenever the namespace has documents.
  • Embedding and retrieval settings: not drafted. The ones that exist are rank weights and similarity gates, which change only with a paired benchmark. The document-side embedding problems (chunks under another model, unembedded chunks) are actions, not settings, and knowledge.inspect already reports them with their remedy.

Scope and risk

  • Read-only and viewer-only, as before. Every new read filters on (org, namespace), the prefix of each table's sort key. loom.documents and loom.knowledge_ingestions are read with FINAL (both are ReplacingMergeTree). Parameters are bound. Each new section is guarded into skipped.
  • Bounds:
    • The sample holds at most namespace_tune_document_sample documents.
    • A text document longer than 2,000,000 characters, or an artifact larger than 8 MiB, is counted as unread.
    • The whole sample loads at most 8 MiB of text and artifact (load_cap), in sample order. The SQL leaves out text past that total with a running sum, and the loader counts artifacts against the same total. A document past it counts as unread.
    • The format-failure read is capped at 1,000 + 1 sources and the per-format coverage at 1,000 + 1 formats, each flagged when cut.
    • Every configured extractor's capabilities are read at once (asyncio.gather), 5 s in all, and only when some format failed or lost structure.
  • New in-process work: one artifact blob read per sampled ingested document, and at most six cuts of the sample (the whole-structure cut, the current values and up to four candidates).
  • document_drafts is guarded like every other section: a failure goes to skipped as documents: <error>, never a 500. Its own population read is named documents.population.
  • The chunk and route settings are deployment-wide. Each draft's scope says so, and its limits say the evidence is this namespace's alone.
  • The knowledge.inspect job read gains three columns per job (filename, content_type, the format option) to read the format from. Its output is unchanged.
  • TuneApply names a setting by its environment name, LOOM_KNOWLEDGE_CHUNK_SIZE, and derives the settings.set field from it (LOOM_<FIELD>). A bare field-name string would read to test_live_settings.py as a read of a LIVE field that the test cannot follow. The values are read once per call and passed down, so expected is the value the draft was judged on.

Compatibility, rollout and rollback

  • Wire (additive only):
    • TuneTarget gains settings.knowledge_chunking and settings.document_extractors_json.
    • TuneApply.via is new (default op).
    • TuneProposal gains apply_also and preview.
    • TuneEvidence gains documents.
    • NamespaceTuneOutput gains chunking, with its load_cap.
    • New models: ChunkStats, ChunkingPreview, ChunkingSample.
    • The namespace.tune p99 budget goes from 5000 to 8000 ms (comment updated).
  • Operator steps: none. A new live setting, namespace_tune_document_sample (default 50, 1 to 1000), is available.
  • Rollback: reverting removes the drafts and the setting. No migration, and no rows are written.

Tests

  • tests/unit/test_namespace_tune_documents.py:

    • A draft per rule with its before and after: sections cut give 1500 to 4500 with stride 3690; inputs over a 300-token limit give a smaller size.
    • No draft when the sections fit, with the sample still reported. No larger size when the limit is unknown, and too few documents judge no rule.
    • An ingested document is cut from its stored artifact, one chunk per SQL statement. An unreadable artifact and an oversized text count as unread.
    • A route is drafted to a declaring service, with no URL anywhere in the output. A format no service declares is named in skipped and nothing is invented; a format the routed service declares now is not drafted.
    • Lost structure is drafted when another service declares the format, and named in skipped when none does.
    • A section that fails is skipped, not raised, and proposal ids are stable across calls.
    • At knowledge_chunk_size 0 (five artifact documents, two paragraphs per section) and at -5, nothing is drafted, the sample is still reported and skipped names the value. A size of 100, below the smallest drafted size, still drafts 400 and tries 200, 300 and 400 once each. Inputs over the limit at 200 and at 150 name the size in force. A stride of 0 and of -3 drafts nothing.
    • The ranking: a service that extracts a format whole takes its incomplete extractions; failed sources behind a non-declaring media-type route go to a service that extracts the format whole, not to another declaring one. A route off a service that extracts some of the format whole names the sources it moves. A format no extractor is configured for says so.
    • One format with both evidence types: failed sources that work now no longer hide the format's incomplete extractions. A route for failed sources avoids the service that lost structure and answers both; when that service is the only one declaring the format, skipped says the route answers the failures alone. A route keeps the service the format's media-type route reaches.
    • A media-type route is the service judged: the application/pdf source is routed through a new pdf key, and the source the default service takes is told to ingest again.
    • The sample stops loading at its total, and two unreachable extractors are read in one timeout.
  • tests/unit/test_namespace_tune.py: failing document drafts land in skipped, and the memory drafts stand.

  • tests/unit/test_namespace_tune_documents_sql.py (clickhouse-local) covers each new statement:

    • The hash sample is stable, folded under FINAL and reads no artifact document's text. A row with an ingestion_id and no artifact is read for its text, and the text read stops at the total.
    • The document writers per agent.
    • The format_unavailable sources: replaced or later-published jobs are excluded, and each source carries its filename, media type and declared format.
    • The extractions per format, with what they lost and the media types behind the incomplete and the complete extractions, kept apart.
  • tests/integration/test_namespace_tune_documents.py, against a private server and ClickHouse:

    • Six text documents and a PDF failed through a real worker pass.
    • The sample reports 18 of 18 sections cut. No size is drafted, because the fake embedder states no limit, and skipped says why.
    • The PDF line says that no configured extractor declares pdf, and the decision line is present.
    • A second call returns the same sample, and the document and chunk snapshot is unchanged.
  • Existing suites: test_namespace_tune.py and the integration test_namespace_tune.py pass.

  • Gates:

    • make format, make lint (exit 0, also with LOOM_ENV_FILE=) and make typecheck pass.
    • The affected unit suites pass with -p randomly: settings, live settings, tunable constants, package contracts, op reach census, public copy, doc links, MCP listing budget, SDK surface, op budgets, knowledge inspect, extractors and embedding.
    • pytest tests/analyzer passes against a migrated private ClickHouse (0 rejected), and shapes.txt is regenerated.
    • npm --prefix sdk/typescript run check passes.
    • The generators were run: SDKs, docs reference, reach census, settings reference, schema and example.
  • Cost on a 2,000-document namespace (26 MB of text, 1 to 6 sections each, plus 200 failed PDF jobs), with the fake embedder:

    Run Wall time ClickHouse queries read_rows read_bytes
    Cold call 0.27 s 48 13,822 16.5 MiB
    Warm call 0.25 s 33 about 12,000 16.5 MiB
    • The largest single statement is the sample read (3,600 rows, 16.3 MiB, 18 ms). The 50 picked documents are spread across most granules, so their text is read from most of them.

    • Cutting the sample (667 chunks, token counting included) takes 8 ms at the current values and 15 ms for the four larger candidates.

    • The 50 sampled documents had 204 sections, all cut at 1500. With a known 8,191-token limit, the rule would draft 6000 (0 cut, largest input 1,500 tokens).

    • Worst case near the caps, in process, with a known 8,191-token limit so the whole ladder runs:

      Sample Loaded Unread Chunks Load Six cuts Extra RSS
      50 texts of 2,000,000 characters 4 46 7,952 under 0.01 s 1.33 s 10 MiB
      50 artifacts of about 8 MiB 1 49 8,000 0.19 s 0.81 s 28 MiB

      The extra RSS is on top of the loaded text. Without the total, the same samples load up to 100 M characters or 400 MiB.

    • To reproduce: seed loom.documents with numbers(2000) rows, call POST /v1/namespace.tune, and read system.query_log for that call's log_comment.

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. I checked the rules against the measured sample and the statements against clickhouse-local and a migrated server.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass (format, lint, typecheck, the affected unit suites and the integration tests ran; the full unit suite is still to run); the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/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).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/i160-doc-tune branch from 6ce8859 to 3c5b3af Compare November 4, 2026 08:30
zlareb1 and others added 8 commits November 4, 2026 09:28
…e per format from a namespace's documents

A chunking draft rests on a bounded sample of the live documents cut again in
process, by the chunker each one's write path uses, at the current values and at
the proposed ones; an extractor route is drafted only for a format whose jobs failed
format_unavailable or whose extractions lost structure, and only when another
configured extractor declares it. Decision extraction takes no instructions, which
`skipped` says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…the sample in all

A chunk size of 0 (one chunk per document) drafts no size, and says so, instead of
dividing by zero; the document drafts are guarded like every other section, so a
failure lands in `skipped`. The sample loads at most 8 MiB of text and artifact in all
(`load_cap`), the SQL leaving out text past it; a document is cut from its artifact
whenever it has one, in the SQL and the loader alike; the extractors' capabilities
are read at once; the stride is clamped to the size once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…oes to, media type included

A failed source's service is read with its media type, so a media-type route is the
service judged: sources it sends to a service that does not declare the format get a
route for the format itself, which wins over a media-type route, and the limits say
so. A chunk size of 0 or less is named as it is, with what it cuts; each candidate
size is tried once, and a size already at the smallest says so; the population read is
`documents.population`, apart from the section's own guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…nd routes it without moving a working source

A format whose failed sources work now is still judged on its incomplete extractions.
A route drafted for failed sources goes to a service some of them work on, else one
the format's media-type routes reach, preferring one that did not make the incomplete
extractions; when it is that service, `skipped` says the route answers the failures
alone. The over-limit line names the chunk size in force, and a stride of 0 or less
drafts nothing, as a size of 0 or less does. The analyzer case passes the module's
caps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ces a format already works on

The per-format coverage keeps the media types behind incomplete extractions apart
from those behind complete ones, so a service that extracts a format whole counts as
one its sources work on, not as one that lost structure. Failed sources and incomplete
extractions share one ranking: a declaring service the format's sources work on, else
one its media-type routes reach, else any, a service that did not make the incomplete
extractions first. The route records the URL it picked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… for a format

A failed source with no default URL and no route reads "no extractor is configured
for it", and no service stands in the sources a route moves. The route keeps no URL
field its output never reads; the tests cover the moved-sources sentence through the
public output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…rt from those routed

When a format's failed sources split between a service that does not declare it and no
service at all, the rationale names the service for its own sources and counts the
rest as having no extractor configured.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/i160-doc-tune branch from 08a76f6 to 97f5600 Compare November 4, 2026 09:29
@zlareb1
zlareb1 merged commit f764c89 into main Nov 4, 2026
21 of 22 checks passed
@zlareb1
zlareb1 deleted the feat/i160-doc-tune branch November 4, 2026 09:55
@pufit pufit mentioned this pull request Nov 4, 2026
9 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant