Repository navigation
feat(node): model release publishing and ingest - #631
Open
beardthelion wants to merge 95 commits into
Open
beardthelion wants to merge 95 commits into
beardthelion wants to merge 95 commits into
Conversation
Adds the operator flags for open-weight model hosting (off by default) and the tables later work builds on: upload sessions, content-addressed blocks, releases, quota, and the durability outbox. Nothing reads or writes them yet, so a node with the flag off behaves exactly as before.
A content-neutral store for verified, content-addressed objects: writes stream while hashing and become visible only when the bytes match the id (atomic link on fs, conditional complete on S3), reads are ranged, and a lost S3 answer reports Unknown rather than a false failure. Built only when model hosting is enabled, and a bad backend config fails closed. Kept deliberately separate from the whole-object archive store proposed elsewhere.
Adds the shared model-block format: FastCDC chunking (8/64/128 KiB) that streams a reader, a packer that seals blocks at the 64 MiB target, and the versioned reconstruction object mapping files to block terms. Dedup reuses terms from prior reconstruction objects by chunk hash, so a fine-tune stores only the chunks that differ. Rebuild verifies every chunk and block hash as it writes.
Adds gitlawb/model-release/v1: the manifest a release commit carries, its detached Ed25519 signature over a domain tag plus the exact manifest bytes, format detection (safetensors, GGUF, pickle, text, other), and verification anchored on a caller-supplied DID so a forged manifest naming another publisher fails. A frozen v1 fixture guards the format against silent change.
Sealing the staged block on every dedup hit turned a fine-tune with scattered edits into one tiny block per changed region, multiplying the object and pin count that blocks exist to keep low. New chunks now accumulate into a single pending block that seals only at the target size or at EOF; their terms carry a placeholder block id that is patched in when the block seals. Also classify sentencepiece .model files as binary rather than text: tokenizer.model is a protobuf, so it now falls through to `other`.
Fetching an entire block per term re-read up to 64 MiB every time a file's terms revisited a block or named a middle chunk range. The fetcher is now a range read over the term's chunk span, computed from the same prefix-sum walk map_file_range uses. Blocks are hash-verified when stored, so verification keeps the per-chunk hashes plus the whole-file digest and drops the whole-block hash check.
A hard link is atomic but not durable: a crash after reporting Stored could lose the entry while the content survives as an orphan. Fsync the destination directory after a successful link, and when the <aa>/<bb> levels were just created, fsync each parent so their entries persist too. Unix only; other platforms keep the link as the best guarantee.
Slice parameter, iterator loop, and a fetch type alias; no behavior change.
Reuse crate::cid::sha256_hex instead of a module-local copy; drop the unused BlockPacker/BLOCK_CAP (pack_file does the packing), the unused FileFormat Display impl, and a one-line entry/or_insert wrapper; share the tests' byte generator; verify releases against the caller's DID directly instead of re-parsing the proven-equal manifest field; and fold the duplicated multipart part-flush into one helper.
get_range disagreed across backends on both edge axes: fs accepted an empty range and rejected an end past the object size, while S3 rejected the empty range and let S3 clamp an over-long end to EOF, silently returning a short body. Callers cannot depend on either behavior being stable across backends. The S3 backend now resolves the object size with HEAD first, maps a missing object to NotFound, enforces the same bounds fs does, and serves an empty in-bounds range without a GET. The trait documents the contract explicitly, and a shared parity test pins the edge cases on both backends.
INSERT ... ON CONFLICT DO UPDATE only applies its WHERE to the update branch, so a DID's first claim inserted bytes_used over the cap unchecked. Gate the insert attempt with SELECT ... WHERE.
Published model releases pin their commits under refs/gitlawb/releases/; advertise them like the requests namespace and every clone fetches internal bookkeeping.
authorize_repo_read always lets an owner read their own repo, so a session kept accepting bytes after the repo went private. Refuse the PUT alongside the other session-dead cases.
The verify worker ran rebuild_file inside spawn_blocking with futures::executor::block_on per fetch, which panics on the S3 backend whose client needs a tokio reactor. Walk map_file_range's ordered slices and await each read instead.
Match the other spawned workers: select each tick against the shutdown watch channel instead of looping until the runtime dies.
A size-lookup or record_block error after put_verified leaked the session charge until expiry.
Publish open-weight model releases from a local clone: classify and chunk model files, open an upload session, PUT content-addressed blocks through the unsigned session bearer route, sign a manifest with the publisher identity, commit and push the release metadata, claim the release with a signed body, and poll verification until it settles. Supports parent reconstruction dedup and resumable local state. Adds NodeClient::put_unsigned for the raw block PUT.
Exercise the U5/U6/U7 model endpoints over the real HTTP server: session open and status authorization, the unsigned block PUT bearer path (missing, bogus, expired, cross-repo, digest mismatch, duplicate, success), signed claims (valid claim, replay dedup, missing commit, non-owner and anonymous denial), and read-gated release status. Includes a required fix in model_queries.rs: SUM over bigint returns numeric in Postgres, which failed to decode into i64 and made every valid claim 500; cast the aggregates back to bigint.
Drop the pass-through models seam so handlers call the Db methods directly, deduplicate the timestamp helpers and the hidden-refs config list, and serve the reconstruction GET from the stored release ref instead of re-verifying the manifest per request. Batch the claim's block-link writes and the sweep's session-link drops so they no longer pay a round trip per block or per expired session, and prefetch rebuild ranges in bounded concurrency during verification. In the CLI, open the upload session before packing so blocks stream out as they seal rather than buffering the whole model in memory, index only each file's fresh block entries for dedup, and sign the manifest through the shared helper via the keypair seed. Tests: make the duplicate-refund and expiry-slide assertions falsifiable, seed the expired-session fixture through the shared helper, and cover the private-repo denial legs for the reconstruction and claims routes.
Address the correctness and security review findings on the publish path: - claim-side block reachability now honors wall-clock session expiry, so a session swept lazily cannot launder references between expiry and the periodic sweep. - the node-wide quota check runs after claimed blocks leave the session charge; before, they counted twice and could falsely exhaust the cap. - claim and release-reject take the same advisory lock, closing the freed-vs-referenced race that could refund quota for live blocks. - block admission serializes through a global advisory lock so racing PUTs on different sessions cannot overshoot per-owner or node caps. - the sweep's liveness re-check locks the row first, then tests in a second statement; the folded form read a pre-lock snapshot and could delete a block a racing claim just referenced. - charge moves off sessions subtract exactly the claimed set, preserving bytes admitted but not yet recorded by a PUT still in flight. - verification consumes the ordered prefetch stream instead of collecting it, so a rebuilt file costs block-sized memory; the CLI packs on a blocking thread and uploads each block as it seals. - all-git releases (no reconstruction object) verify instead of being admitted then deterministically rejected; manifests naming chunked files without one are refused at claim. - the verifier refuses commits carrying files the manifest never named, and claims require manifest.repo to name the claimed repository. - publish is conditional on the row still verifying; a mid-verify rejection now unwinds the just-written release ref instead of leaving it advertised. - the claim path pins the commit under the hidden release ref immediately, closing the force-push-plus-gc window before publish, and write_release_ref ensures the hideRefs config itself rather than relying on the warn-and-proceed push path. - block PUT error paths refund admission AND delete the orphaned store object; a vanished object after write is an error, not a fabricated size, and body-stream failures return 400 instead of 500. - stale verifying rows past six hours are rejected by the sweep so a wedged release frees the publisher's one-verifying slot. - the CLI stages exactly the scanned publishable set via a NUL pathspec rather than `git add -A`, resolves staged blobs through the index instead of revspec syntax, escapes gitignore metacharacters in the managed block, and retries transient status-read failures while polling. - misc: owner DIDs are canonicalized before manifest verification, reconstruction block sums are validated, range arithmetic is checked, and attacker-controlled ids are truncated safely in error messages.
The CLI is a short-lived process driving git synchronously; the unbounded-child guidance targets request handlers holding a concurrency permit, which does not apply here.
A mirror row's publicity pair is vacuous (is_public is hardcoded true, rules never sync), so a mirror without a canonical twin would pass the fully-public gate end to end. Fail closed on slash-form ids at session open, claim, parent resolution, and the verify recheck, with a mirror-without-twin test.
Extend the mirror guard to block PUTs and reconstruction reads, and mark the verify recheck for the push gate's mirror-pair scan.
…n S3 ambiguity Allowlist fastcdc for the twigpine-core purity gate. Add pack_file_with so each sealed block goes to a sink and drop per-chunk buffers after sealing. Detect safetensors before the pickle prefix test. Require the unclaimed TTL to exceed the session TTL. Refuse empty blocks in both backends to match model_blocks.size > 0. Persist the fs ancestor chain on every store and on AlreadyPresent. Report a retried complete's NoSuchUpload and 409 as Unknown, and split oversized stream items across bounded S3 parts.
…n status read Enroll model.rs in CONVERTED_IN_186 so no_parse_before_status passes. GET session status now answers 404 once expires_at has passed, matching the block PUT, so the CLI resume path abandons a lapsed session. Add a guard test that a block larger than its declared Content-Length is rejected.
…ancelled block writes
Reconstruction validation now uses checked arithmetic, rejects duplicate
block rows and block sizes that disagree with their chunks, and
map_file_range shares rebuild_file's bounds guard. Safetensors detection
caps the header length at 100 MB so a pickle with '{' at byte 8 stays
pickle. A dropped put_verified removes its staged file (fs) or aborts its
multipart upload (s3) unless the complete request may have committed.
The managed block is written after the scan, so a first chunked publish staged .gitignore without naming it in the manifest and the node rejected the commit as unlisted.
A clean filter could rewrite the signed manifest at git add; the .twigpine files are hashed with --no-filters and the staged blobs are re-read and signature-checked before the push.
…h tail When the post-record size check fails after a duplicate record, this request created no link, so unlinking and refunding undoes the first PUT's work.
A block-store error in size() or get_range() was flattened to NotFound; backend failures now surface as 500 while a proven-empty lookup or the store's own NotFound stays 404.
model_record_block could read own_release_carries just before a claim moved the block to a release and keep both the link and the charge; the transaction now takes CLAIM_LOCK_KEY first.
A block relinked after being marked unreferenced kept its old stamp, so dropping the link again made it deletable with no new grace period; the session-link and claim release-link inserts now clear unreferenced_since.
run_git_bounded_capped treated a pipe read failure as EOF and could report truncated output as complete; only Ok(0) ends the loop now.
run_git_blob_digest treated every cat-file exit 128 as a missing path, so a broken repo config read as absence; an empty ls-tree is now the only None and other failures are errors the verifier retries.
claim_release shelled out to the row's disk_path string; it now acquires the RepoStore checkout like the other repo handlers, and the tests seed the repo at that path.
Every read_verified_manifest error used to reject the release outright; AppError::Internal now returns to the worker's bounded retry while deterministic errors still reject.
A nonzero ls-tree used to read as an empty tree and could publish past the committed-but-unlisted check; its exit status is checked before stdout is trusted.
The understated Content-Length probe only checked the status was not 200; it now also proves the block is absent from the store, the session is untouched, and the socket read is bounded.
The owner GET leg 404ed at the release lookup even without the publicity check; it now proves a 200 on the public repo first, so the private-repo 404 is the gate firing.
cargo fmt reflow of the T1 test
cargo fmt reflow of the T3 test
cargo fmt reflow of the T4 helper
cargo fmt reflow of the T5 helper
cargo fmt reflow of the T6 changes
cargo fmt reflow of the T8 changes
cargo fmt reflow of the T9 test
cargo fmt reflow of the T10 change
cargo fmt reflow of the T11 change
cargo fmt reflow of the T12 test
cargo fmt reflow of the T14 test
cargo fmt reflow of the T15 test
cargo fmt reflow of the T16 test
cargo fmt reflow of the T17 test
clippy non_octal_unix_permissions fix for the T1 test
claim_release reads through repo_store.acquire, so the fixture repo sits at the store-managed disk path.
Collaborator
Author
|
Pushed fixes for the 17 open CodeRabbit threads, each answered on its thread. All 17 reproduced or held on reading; none were declined. Format, clippy, workspace check and the CLI, node lib, models_api and deny suites pass locally. jatmn's earlier requests (non-zero exit on poll timeout, bounded verify retries, owner 400 case) are already in this head. |
This branch has not been deployed
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.
Summary
Brings the model release publishing and ingest work (#622) onto main. #622 merged into feat/model-hosting-foundation, so main has the storage foundation from #620 but not this work.
Motivation & context
Main has migrations up to v49. This work carries v50, and #628 carries v51, whose migration ledger test needs v50 on main. #623 is stacked on this work and should be retargeted to main after this merges.
Closes #
Kind of change
Unticked: this is a feature, none of the others apply.
What changed
twigpine model publishNothing beyond what was reviewed and merged in #622.
How a reviewer can verify
git diff origin/main...origin/feat/model-hosting-foundation --stat cargo test --workspaceBefore you request review
cargo test --workspacepasses locallycargo fmt --allandcargo clippy --workspace --all-targets -- -D warningsare cleanfeat(...),fix(...),docs(...)).env.exampleupdated if behavior or config changed (or N/A)Unticked boxes were not re-run on this branch tip; the code was reviewed and tested in #622.
Protocol & signing impact
did:key, Ed25519 / RFC 9421 signatures, UCAN, ref certs, or P2P wire formatsThe signed model release manifest is a new format introduced in this work. The last two boxes are unticked because I have not verified them here; they were covered in #622 review.
Notes for reviewers
This PR only moves reviewed code to main.
Summary by CodeRabbit
model publishto publish signed model releases from a local repository, with confirmation prompts, resumable uploads, and optional parent releases.