Repository navigation
Document originals can be kept in an S3-compatible bucket - #167
Merged
Merged
Conversation
zlareb1
force-pushed
the
feat/knowledge-object-store
branch
2 times, most recently
from
November 2, 2026 19:17
6938fb0 to
1e546c7
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-object-store
branch
from
November 2, 2026 23:01
00ca779 to
b216168
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-object-store
branch
from
November 2, 2026 23:26
20d3d2d to
bb99ff5
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
7 of 9 tasks
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
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):
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
datacolumn ofloom.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:
loom.document_blobsstays the catalog (one row per(org, namespace, sha256), the sweep and erasure predicates unchanged). A newlocationcolumn is''for bytes indata, ors3://<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.<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.blobs.delete) takes an unreferenced original's rows, then the objects no row names any more, then the upload records.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.410 BLOB_GONEonly if that finds nothing.document_blob_gcbucket walk deletes both once older thanLOOM_DOCUMENT_BLOB_MIN_AGE_SECONDS.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.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.objects.document_originals, owned bydocuments.tombstone, which a resumed saga re-opens). Deletes and counts go a listing page at a time.(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.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_taghashes the bound values), so a re-run waits only for its own batch.<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 503BACKEND_UNAVAILABLEnaming the operation and the store's code, never the bucket or a key. After a failed step the saga's census tail, andloom 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.max_attemptsthe 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 noawsextra).OVERLOADEDafterLOOM_CH_POOL_WAIT_MSwhen 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.object_store.putexplicitly.ch.acquire_slot, shared with ClickHouse streams.awsextra the image installs; theawsandingestextras 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 inserver/core/object_store.pyso 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 otherasyncio.to_threadcallers 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_calculationandresponse_checksum_validationset towhen_required;putsends 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 areLOOM_DOCUMENT_S3_CONNECT_TIMEOUT_S(5) andLOOM_DOCUMENT_S3_READ_TIMEOUT_S(30, per streamed chunk).Alternatives considered: a separate
document_objectstable 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.upsertnow 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 (onmainit 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_blobsreads take the latest row (ORDER BY created_at DESC LIMIT 1) because the location differs per write;blobs.sizebecomesblobs.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, asmaindoes, 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 lightweightDELETE FROMwould 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
locationreads the emptydataof 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
erasure.statusand the saga listing'sresiduemap can carry the keyobjects.document_originals, the bucket objects a census found left; no field is added or removed.078_document_blob_location.sqladdsloom.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.LOOM_DOCUMENT_OBJECT_STORE(clickhousedefault,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).s3without a bucket refuses to start.s3: finish the rollout, create a bucket (or a prefix) used by this deployment alone, grant the serverPutObject,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).LOOM_TEST_S3_ENDPOINT.Tests
LOOM_DOCUMENT_BLOB_MIN_AGE_SECONDSis 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_SorLOOM_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, andloom doctor'sreplica_consistencyline now namesdocument_blobsandblob_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 namespaceteam/xis encoded and neither the sweep nor an erasure ofteamreaches 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 aDate), 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 whileNoSuchKeydoes 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-opensdocuments.tombstone; the client takes its connect and read timeouts from the settings; the settings validator.mainafter the replicated-table erasure change: user erasure takesmain'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 (thetag_keyargument is gone). At the head: format, lint, typecheck and the wholetests/unitpass. Against a private ClickHouse, moto and a server from the branch:tests/integration/test_document_object_store_live.py6 passed, andpytest 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 ornow64()(a replicated table refuses either);test_new_mutations_bind_parameters_only.pynow runs the sweep's deletes too.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 fullresidue_censusat 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.LOOM_DOCUMENT_OBJECT_STORE=s3against the local store:knowledge.addwith a 300 KB and a 6 MB original,knowledge.downloadbyte-identical (buffered and streamed paths), catalog row with emptydata;erasure.requestfor the namespace completed withresidue_count0 and no object left in the bucket.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.pyandtest_rmt_write_paths.pyfor the location read, the object count, the new tables and a bucket outage logged on one line.make format,make lint,make typecheckpass;make schema-dumpon 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 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).main; no merged migration is edited.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