Skip to content

Document originals can be kept in an S3-compatible bucket - #167

Merged
zlareb1 merged 3 commits into
mainfrom
feat/knowledge-object-store
Nov 3, 2026
Merged

zlareb1 merged 3 commits into
mainfrom
feat/knowledge-object-store

Conversation

@zlareb1

@zlareb1 zlareb1 commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Related: #157

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

Uploaded document originals can be kept in an S3-compatible bucket (LOOM_DOCUMENT_OBJECT_STORE=s3, LOOM_DOCUMENT_S3_BUCKET), with ClickHouse keeping each one's catalog row. Downloads, the originals sweep and erasure all cover the bucket.

Why

The file-ingestion proposal keeps large binaries and extraction artifacts out of the query databases: object storage is the content substrate for originals, with its own access, durability and erasure obligations. Today an original is the data column of loom.document_blobs, sent as base64 inside a JSON request. This change adds the object store as a first-class, erasure-covered substrate and moves the bytes of new originals there when a deployment chooses it. The streamed upload endpoint and the server-side parsing that read these objects follow in the next pull request.

Design:

  • One catalog, two places for bytes. loom.document_blobs stays the catalog (one row per (org, namespace, sha256), the sweep and erasure predicates unchanged). A new location column is '' for bytes in data, or s3://<bucket>/<key> for an object. A row is read from wherever it says, so originals written before a switch keep downloading; a write goes to the configured store. There is no per-request fallback between stores.
  • Every write is its own immutable object (keys at most 512 characters, what the sweep's cursor keeps), <prefix>/<org>/<namespace>/<sha256>/<write id> (org and namespace percent-encoded, so a / in a name cannot place an object under another namespace's prefix), written with the store's SHA-256 check before the row that names it. So a row never names an object that was never written, and deleting one write's object can never delete another write's: the race between a re-upload of the same bytes and the sweep of their previous copy, which a shared key would turn into a row naming a deleted object, cannot happen.
  • Objects leave with their rows. The sweep's delete (blobs.delete) takes an unreferenced original's rows, then the objects no row names any more, then the upload records.
    • It reads the rows' locations under its own age bound and deletes only rows it can name (location = '', or one in the configured bucket), so a fresh write or a lagging replica can only make it keep a row or an object.
    • A row naming an object outside the bucket, or with no bucket set, is kept and recorded as the pass's failure: deleting it would leave bytes nothing can find.
    • If the bucket refuses the delete, the upload records stay so a user erasure still finds the bytes; the walk retries the objects and then drops those records once the original's prefix lists empty. A recount the store fails keeps the records (who uploaded which bytes, no content) until an erasure of that user or namespace.
    • Each write has its own key, so no later row can name an object the sweep deleted. A download whose object is gone reads once more under sequential reads and answers 410 BLOB_GONE only if that finds nothing.
  • The sweep owns unnamed objects. A row a re-upload replaced is merged away, and a write whose row insert failed leaves an object; the document_blob_gc bucket walk deletes both once older than LOOM_DOCUMENT_BLOB_MIN_AGE_SECONDS.
    • It runs before the namespace walk, since it is bounded and the namespace walk is not: LOOM_DOCUMENT_BLOB_GC_OBJECT_PAGES (20) pages of 1,000 keys per pass, resuming from the pass cursor, which goes back to the root prefix at the end of the bucket.
    • For each page it asks the catalog, by sort key and with sequential consistency, which objects a row names (replaced rows not yet merged count), as many keys to a statement as one bound parameter carries.
    • Ages are read on the store's clock (the listing's Date; without one, this host's clock less 15 minutes, the most SigV4 lets two clocks differ), so a wrong clock cannot make a new object look old.
    • A page whose delete the store refuses is recorded and passed over. Keys that are not an original's are left alone, so the bucket and prefix must be the deployment's alone.
  • Erasure fails closed. Objects go before rows; a user erasure lists its prefixes again and fails on any object left, and for a namespace the saga's census counts what is left and re-opens the step.
    • Namespace scope: every object under the namespace prefix that parses back to the scope's own org and namespace is deleted (after a prefix moved up a level another org's keys can sit under it), then the rows; the census counts what is left (objects.document_originals, owned by documents.tombstone, which a resumed saga re-opens). Deletes and counts go a listing page at a time.
    • User scope: the user's own originals (their (namespace, sha256) pairs, from the upload records and their documents, so bytes whose row never landed are found) lose every write under each <namespace>/<sha256>/, the prefixes are listed again, then the rows go by the same pairs, each batch read again right before its delete, and what those prefixes still hold that no row names is deleted, so the user's own upload of those bytes whose row the mutation took leaves no object; an upload of those bytes still in flight when the step runs, by any writer (object stored, row not yet in), loses its object, and its row, once in, answers 410. Every read runs with sequential consistency.
    • The pairs go as many to a mutation as one bound parameter carries (ch_params.chunks, 64 KiB), on the ClickHouse store too; no mutation carries a subquery, which a replicated table refuses. Each batch is read again right before its delete, so an original another writer's document named since the first read stays. A batch's bound pairs make its mutation tag its own (mutation_tag hashes the bound values), so a re-run waits only for its own batch.
    • Another writer storing the same bytes in the same namespace between that read and the delete can lose them, as on the ClickHouse store, where the bytes are the row; a narrower rule needs write-level ownership the catalog does not have.
    • A row naming an object with no bucket set, or outside the bucket and prefix, or not four segments below it as Loom lays keys out (<org>/<namespace>/<sha256>/<write id>, a former setting nested in the current one; the segments are not matched to the row's own scope, since every writer builds the key from it), fails the step. A bucket error is a 503 BACKEND_UNAVAILABLE naming the operation and the store's code, never the bucket or a key. After a failed step the saga's census tail, and loom erasure-re-verify, list the bucket apart from the tables (census.evidence_census), so a bucket that cannot be listed costs only the object count.
  • Misconfiguration fails closed. A row naming an object no bucket is configured for, or one outside the configured bucket and prefix, fails the step with an error naming the settings, not the 503 a store outage is; the saga's retries repeat it, and after max_attempts the erasure is marked failed and must be resubmitted once the settings are fixed. A configured bucket without boto3 installed refuses to start the server (checked at startup, so the CLI alone needs no aws extra).
  • Bounded bucket threads. The 16 bucket threads are split into slots: 4 for streams, 8 for transfers, 4 for listings and deletes, each a constant of the object store's own.
    • A download over 4 MB streams; an upload (for its object only, after its record, so a slow ClickHouse insert holds no bucket slot) and a smaller download each take a transfer slot. Either answers 503 OVERLOADED after LOOM_CH_POOL_WAIT_MS when its slots are busy, so a stalled bucket refuses a burst rather than queueing it. Listings and deletes (erasure, its census, the sweep) wait for a slot instead.
    • A slot is held until every bucket thread started under it is done, so a cancelled caller cannot free a slot whose thread is still blocked; the upload passes its transfer slot to object_store.put explicitly.
    • A buffered read requests, reads and closes on one thread; a stream stopped mid-read closes its body only after that read returns, and its close and release run shielded against a second cancel. The wait is ch.acquire_slot, shared with ClickHouse streams.
  • The S3 client is boto3 (already the aws extra the image installs; the aws and ingest extras now need 1.36, the first whose client config takes the checksum options below, and startup refuses an older one with a bucket set), built once per endpoint under a lock on its own session and called in worker threads, credentials from the AWS chain. It lives in server/core/object_store.py so the erasure store layer can reach it under the package contract. Calls run on a pool of 16 threads of its own (so a stalled bucket never holds the threads other asyncio.to_thread callers share), with a 5 s connect and 30 s read timeout and three standard-mode attempts. The client computes request and response checksums only where an operation needs one (request_checksum_calculation and response_checksum_validation set to when_required; put sends its own SHA-256), since boto3's default of one on every request is refused by some S3-compatible stores. Tested against moto and AWS-shaped responses only; other S3-compatible stores are untested here. Its connect and read timeouts are LOOM_DOCUMENT_S3_CONNECT_TIMEOUT_S (5) and LOOM_DOCUMENT_S3_READ_TIMEOUT_S (30, per streamed chunk).

Alternatives considered: a separate document_objects table would split the sweep and erasure predicates in two for no gain; keying objects by sha alone (shared by writes) is the race above; leaving every object to the walk would keep a deleted document's bytes in the bucket for a whole walk (weeks on a bucket of millions of objects).

Invariant. "Nothing replica-wide lives outside ClickHouse" gains one exception, named in rule 9 of docs/architecture/rolling-upgrades.md: with the S3 store, the bytes of originals live in the bucket, which every replica reads the same way, while the catalog row naming each object stays in ClickHouse. Large immutable binaries are what object storage is for; keeping them in ClickHouse rows costs merges and backup size for data no query scans.

Postgres authority for source revisions and manifests is planned on top of the related issue's Postgres authority; this change does not depend on it.

Scope and risk

knowledge.upsert now stores the new original before it retires the current version's chunks, so an upload the bucket refuses or is too busy for leaves the document searchable (on main it retired them first; no ClickHouse failure sat between the two). The originals sweep reads 800 originals per statement (was 2,000), 25 batches a pass, so one batch's shas bind as one parameter under ClickHouse's field limit; the bound per namespace per pass stays 20,000. loom.document_blobs reads take the latest row (ORDER BY created_at DESC LIMIT 1) because the location differs per write; blobs.size becomes blobs.locate (size and location in the one statement), so a download still makes two statements on the default store. Default deployments (clickhouse) write what they did; each erasure step adds one count of the scope's rows that name objects. A user erasure on the ClickHouse store deletes the user's originals in batches by bound pairs, as main does, with no objects to keep in step. With a bucket it deletes the rows by the pairs it read, as many originals per mutation as one bound parameter carries (ch_params.chunks: 840 with a short namespace name), so a user with 2,000 originals costs three part rewrites of the parts holding them. A lightweight DELETE FROM would cost one mask write each, but on the ClickHouse store the bytes are the rows, and a mask leaves them on disk until a merge, which the reclaim worker's thresholds may never call for; a mutation removes them when the step ends. The sweep's bucket walk runs only with a bucket configured.

Rolling upgrade: a build without location reads the empty data of an S3 row and answers the download 410, so the S3 store is switched on only after every replica runs this build (documented in the migration and the knowledge page).

Compatibility, rollout and rollback

  • Wire: erasure.status and the saga listing's residue map can carry the key objects.document_originals, the bucket objects a census found left; no field is added or removed.
  • Schema: 078_document_blob_location.sql adds loom.document_blobs.location String DEFAULT ''. PR Live memory can be held in Postgres, with search and history in ClickHouse #158 also takes 078; whichever merges second renumbers.
  • Settings: LOOM_DOCUMENT_OBJECT_STORE (clickhouse default, s3), LOOM_DOCUMENT_S3_BUCKET, LOOM_DOCUMENT_S3_PREFIX (loom/originals), LOOM_DOCUMENT_S3_ENDPOINT_URL, LOOM_DOCUMENT_S3_REGION, LOOM_DOCUMENT_S3_CONNECT_TIMEOUT_S (5), LOOM_DOCUMENT_S3_READ_TIMEOUT_S (30), LOOM_DOCUMENT_BLOB_GC_OBJECT_PAGES (20). s3 without a bucket refuses to start.
  • Operator steps: none for the default. For s3: finish the rollout, create a bucket (or a prefix) used by this deployment alone, grant the server PutObject, GetObject, ListBucket, DeleteObject, set the settings, and back the bucket up with its own versioning or replication, with a lifecycle rule that expires noncurrent versions (and the replica's copies): its window is how long an erased original stays restorable (backup page).
  • Rollback: reverting leaves the column. Do not roll back past this build while rows name objects: an older build answers their downloads 410, and its erasure deletes the rows without reaching the objects. The bucket and prefix stay fixed while rows name objects under them.
  • CI: the integration job starts a local S3-compatible store (moto, pinned by digest) and exports LOOM_TEST_S3_ENDPOINT.

Tests

  • With a bucket configured, the settings refuse to load unless LOOM_DOCUMENT_BLOB_MIN_AGE_SECONDS is at least a minimum covering a write's row-insert retry ladders after its original is stored (a minimum, not a bound on every reconnect or schema check the client may add, so the docs say to keep it well above; the 3600 default is about four times it): 2 x (1 + LOOM_CH_REPLICA_BOUND_RETRIES) x (LOOM_CH_TIMEOUT_READ_S + LOOM_CH_TIMEOUT_WRITE_S + 2 x LOOM_CH_POOL_WAIT_MS / 1000) plus 300 s for the upload and a minute for reconnects, 906 s at the defaults (the store may date an object from the start of its upload, so a write whose upload takes longer than 300 s, DOCUMENT_UPLOAD_BUDGET_S, is refused with 503 and its object, which no row names, is left to the walk; deleting it in the request would queue it behind every listing in flight): the insert describes the table (a read ladder) and writes (a write ladder), and runs both again after a stale column cache; the pool wait is counted on every attempt, an upper bound, since a ladder takes its connection slot once. The settings also refuse an unbounded (0) LOOM_CH_TIMEOUT_WRITE_S, LOOM_CH_TIMEOUT_READ_S or LOOM_CH_POOL_WAIT_MS, which no floor can outlast. The bucket walk would delete an object in that gap. The floor assumes the walk's sequential catalog read sees every acknowledged row, true on one server and on SharedMergeTree; on a self-managed ReplicatedMergeTree cluster with several replicas that read waits only for quorum inserts, so the docs say to keep the min age well above the floor there, and loom doctor's replica_consistency line now names document_blobs and blob_uploads. The walk's catalog read runs with sequential consistency, since a replica behind a just-written row would call its object unnamed.
  • tests/unit/conftest.py: the leaked-thread check also spares the bucket pool's threads (loom-object-store), which, like the event loop's default executor, outlive every test by design.
  • tests/unit/test_document_object_store.py (73, fake S3 client with paging, the SHA-256 check and botocore's error shape): object written before its row and read back buffered and streamed across chunks; each write its own object; a failed write leaves no row, and its 503 names no bucket; mismatched bytes refused; a row read from where it says after a store switch; a missing object reads as nothing, a failing bucket as an error; the sweep spares fresh and named objects and keys that are not an original's, pages from a cursor, a pass stops at its page budget, a refused delete is recorded and the walk goes on, a failed listing or catalog read stops only the walk (the namespace walk still runs), and the walk starts over at the end of the bucket through the supervisor's cursor rule; a namespace team/x is encoded and neither the sweep nor an erasure of team reaches it; namespace erasure deletes only the scope's objects and the census counts them; user erasure deletes every write of the user's bytes, including one with no catalog row, and no one else's, with the catalog rows deleted by the pairs bound, each batch read again first, in batches each with its own mutation tag; a deleted row's object goes with it before any walk, a re-upload during the sweep keeps its object, a refused object delete keeps the upload record while the rows still count, a row naming an object in another bucket or with no bucket configured is kept, a missing object reads as missing while a 0-byte original reads as empty, the walk drops the upload record of an original whose last object it deleted, user erasure reads the user's originals and counts their rows with sequential consistency, the walk reads object ages against the store's clock (and this host's less the signature skew without a Date), reads the catalog and the namespace step its bucket check sequentially, keeps an upload record while an object of the original is left (at either edge of a page too), a per-key refusal in a bulk delete fails the namespace erasure while NoSuchKey does not, and the settings refuse a min age shorter than a write's retry ladder; for a user erasure, a store that keeps an object; for either scope, a store that refuses a delete, fails a listing partway, or is unconfigured, and a row naming an object outside the bucket and prefix, each fail the step; a key too long for the sweep's cursor is refused at write; a bucket failing on the first read of a streamed download answers 503 (a failure after the first chunk ends the response short, the status already sent); a download answers 410 for a missing object and 503 for a failing bucket through the route; object residue re-opens documents.tombstone; the client takes its connect and read timeouts from the settings; the settings validator.
  • Rebased onto main after the replicated-table erasure change: user erasure takes main's read-then-delete per batch (with the re-read) for both stores, the aged delete binds its cutoff read from the ClickHouse clock, and mutation tags come from the bound values (the tag_key argument is gone). At the head: format, lint, typecheck and the whole tests/unit pass. Against a private ClickHouse, moto and a server from the branch: tests/integration/test_document_object_store_live.py 6 passed, and pytest tests/integration -k "knowledge or erasure or document or blob or census or analyzer" -m "not slow and not destructive" 156 passed, 2 skipped (both at the head). The upload-record cleanup the walk sends reads its cutoff and the keys a row holds first and binds both, so its delete carries no subquery or now64() (a replicated table refuses either); test_new_mutations_bind_parameters_only.py now runs the sweep's deletes too.
  • Mixed versions: CI's "builds N-1 and N on one ClickHouse" job (make test-mixed-version) passes, so build N-1 serves on migration 078's schema.
  • tests/integration/test_document_object_store_live.py (6, live ClickHouse and a local S3-compatible store; 6 passed at this head against moto): round trip of a 2.3 MB original with the catalog row checked field by field; a deleted row's object goes with the row, the walk deletes an orphan, and the named one stays; namespace erasure and the full residue_census at zero; user erasure deletes alice's objects and rows and keeps bob's object and row; a row laid out under a former nested prefix fails the erasure; the upload-record cleanup statement the walk sends runs on ClickHouse, dropping an orphan's record and keeping one whose original still has a row.
  • End to end on a server with LOOM_DOCUMENT_OBJECT_STORE=s3 against the local store: knowledge.add with a 300 KB and a 6 MB original, knowledge.download byte-identical (buffered and streamed paths), catalog row with empty data; erasure.request for the namespace completed with residue_count 0 and no object left in the bucket.
  • Updated fakes and pins in test_blob_store.py, test_document_blob_gc.py, test_erasure_documents.py, test_erasure_step_order.py, test_knowledge_download_text.py, test_doctor_replica_consistency.py, test_erasure_backend_failure_logs_one_line.py and test_rmt_write_paths.py for the location read, the object count, the new tables and a bucket outage logged on one line. make format, make lint, make typecheck pass; make schema-dump on a private ClickHouse migrated from empty shows only the new column.

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. The end-to-end download and erasure runs above were done by hand against a local 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; 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.
  • 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/knowledge-object-store branch 2 times, most recently from 6938fb0 to 1e546c7 Compare November 2, 2026 19:17
@zlareb1
zlareb1 force-pushed the feat/knowledge-object-store branch from 00ca779 to b216168 Compare November 2, 2026 23:01
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-object-store branch from 20d3d2d to bb99ff5 Compare November 2, 2026 23:26
@zlareb1
zlareb1 merged commit aa47f16 into main Nov 3, 2026
20 of 22 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-object-store branch November 3, 2026 00:12
@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