Skip to content

feat(node): add model release publishing and ingest - #622

Merged
beardthelion merged 22 commits into
feat/model-hosting-foundationfrom
feat/model-hosting-publish
Nov 23, 2026
Merged

beardthelion merged 22 commits into
feat/model-hosting-foundationfrom
feat/model-hosting-publish

Conversation

@beardthelion

@beardthelion beardthelion commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds the publishing half of model hosting: resumable upload sessions, content-addressed block ingest, signed release claims, asynchronous verification, and the twigpine model publish CLI. Stacked on #620, which carries the storage and format foundation.

Motivation & context

Part 2 of the model hosting milestone. #620 landed the block store, the chunk/reconstruction format, and the signed release format. This PR wires them into the publish path: a repo owner pushes a model, the node verifies it against the signed manifest, and it becomes a release.

Kind of change

  • Feature

What changed

  • twigpine-node: model upload sessions with a 256-bit bearer capability, sliding TTL, and atomic per-identity and node-wide admission caps
  • twigpine-node: unsigned content-addressed block PUTs (the session capability is the credential, Content-Length is declared, the digest is verified on the stream, dedup-aware accounting)
  • twigpine-node: signed release claims under an advisory lock: manifest verified against the repo owner DID, replay dedup by request digest, one verifying release per publisher, block reachability through the publisher's session, own live release, or declared public parent, atomic quota reservation
  • twigpine-node: a verify worker that rebuilds chunked files from blocks, rehashes and format-checks them, checks commit coverage, and writes hidden release refs before publishing
  • twigpine-node: a sweep worker that expires sessions, rejects stale verifying releases, and reclaims unreferenced blocks after a grace period
  • twigpine-cli: twigpine model publish classifies files, chunks large ones, streams new blocks as they seal, signs the manifest, commits and pushes the git metadata, claims the release, and polls for verification
  • new HTTP tests covering every model route including deny cases, deny-harness rows for the new routes, DB state tests, and CLI tests

How a reviewer can verify

cargo test -p twigpine-node --features test-harness --test models_api
cargo test -p twigpine-node --features test-harness --test deny_harness
cargo test -p twigpine-cli
cargo clippy --workspace --all-targets -- -D warnings

Before you request review

  • Scope is one logical change; no unrelated churn
  • cargo test --workspace passes locally
  • New behavior is covered by tests (required for fixes)
  • cargo fmt --all and cargo clippy --workspace --all-targets -- -D warnings are clean
  • Commit titles use Conventional Commits (feat(...), fix(...), docs(...))
  • Docs / .env.example updated if behavior or config changed (or N/A)
  • Checked existing PRs so this isn't a duplicate

Protocol & signing impact

  • Touches DID / did:key, Ed25519 / RFC 9421 signatures, UCAN, ref certs, or P2P wire formats
  • Discussed in an issue before implementation
  • Backward-compatible with existing nodes and previously signed history

Notes for reviewers

Stacked on #620; the base is feat/model-hosting-foundation, so the diff shows only this PR's 19 commits (plus one merge of the base). The claim request is a new signed wire format verified against the repo owner DID, not against an identity taken from the artifact.

The workspace-test box is unchecked: the full run on the final tree had 29 failures in the twigpine-node lib tests that all pass on re-run, and twigpine-cli task::tests::test_view_task_not_found fails the same way without this PR's changes (501 from the task endpoint).

Publishing requires a fully public canonical repo; mirror rows fail closed at session open, claim, block PUT, reconstruction read, and the verify recheck. Known bound: a persistently failing release holds the publisher's one verifying slot for up to 6 hours until the sweep rejects it.

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.
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bab5bb57-60e5-4237-93b9-6d394b85ff0e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found issues that need to be addressed before this is ready.

Merge readiness

  • Required CI is red on head. test (stable), test (beta), and test (windows, non-blocking) fail on converted_handlers_never_parse_before_status because model.rs is not enrolled in CONVERTED_IN_186 (PR-owned).
  • Stacked base is feat/model-hosting-foundation, not main. Merge planning should keep the stack order (#620 → #622 → #623) explicit.
  • PR template drift: the body asks reviewers to run --test models_db, but there is no models_db integration test target on head (DB coverage lives in model_queries.rs #[cfg(test)] and models_api). Update the verification snippet so reviewers run the suites that exist.
  • Workspace test checkbox remains unchecked in the PR body; reconcile with the failing required test (*) jobs before merge.

Drift check (head 27e971ca vs merge-base 6c5431bf): All findings below are PR-introduced on this diff; corrections stay inside the new model publish surfaces. None require rewriting unchanged node/CLI core.

Findings

🟡 P2 — Enroll model publish on the #186 read_json handler gate

📍 Where: crates/twigpine-cli/src/model.rs, crates/twigpine-cli/tests/no_parse_before_status.rs

💥 What fails: cargo test -p twigpine-cli --test no_parse_before_status fails with unpinned handler ["model.rs"], which matches the required CI test (stable|beta|windows) failures on head.

🔎 Root cause: New CLI code routes node responses through read_json / json_or_denial but was not added to the authoritative CONVERTED_IN_186 pin list, so the enrollment gate fails closed.

📜 Stated contract:

A file that uses read_json but is not pinned is a conversion that was never enrolled, so its own later revert would escape unseen; RED until it is added to the pin.

🏷️ Attribution: PR-introduced (model.rs does not exist at merge-base 6c5431bf).

📌 In this PR:

  • model.rs — uses read_json at session status, block upload, and release status reads
  • no_parse_before_status.rs — CONVERTED_IN_186 list unchanged

🔒 Unchanged on main: Other pinned handlers already listed in CONVERTED_IN_186.

🔧 Required correction: Add "model.rs" to CONVERTED_IN_186 (alphabetically with peers). Re-run cargo test -p twigpine-cli --test no_parse_before_status and the workspace test jobs.

🛠️ Author fix: Close the enrollment on both in-diff rows in one pass: pin model.rs and keep every model HTTP read on read_json / json_or_denial (no raw resp.json().await on node bodies).

🚫 Out of scope: Converting unrelated pre-existing debt handlers (init.rs, profile.rs).


🟠 P1 — Bind block PUT admission to the bytes actually stored, not understated Content-Length

📍 Where: crates/twigpine-node/src/api/models.rs put_model_block, crates/twigpine-node/src/db/model_queries.rs model_admit_bytes / model_record_block

💥 What fails: A session bearer (owner or anyone holding the session id) can send a small Content-Length while streaming the full content-addressed body. Admission charges declared against per-owner session caps and node-wide open-session caps, but put_verified accepts the stream until EOF (up to MAX_BLOCK_BYTES) and model_record_block books the store size without reconciling bytes_received on the success path.

The bundled twigpine model publish path is not affected: reqwest sets Content-Length from the body it sends. The gap is custom or hostile clients using the unsigned session PUT.

Claim-time quota on real model_blocks.size can still reject a release later; it does not restore honest open-session cap accounting during ingest.

🔎 Root cause: The PUT path treats Content-Length as the admission charge but never requires the stored object length to equal that charge, so cap math and operator-visible bytes_received diverge from disk usage.

📜 Stated contract:

Adds … atomic per-identity and node-wide admission caps … unsigned content-addressed block PUTs (the session capability is the credential, Content-Length is declared, the digest is verified on the stream, dedup-aware accounting).

Atomically admit claimed bytes against the caller's per-identity open-session cap and the node-wide quota …

🏷️ Attribution: PR-introduced (new put_model_block route).

📌 In this PR:

  • put_model_block — admits on header Content-Length, streams with put_verified(..., MAX_BLOCK_BYTES)
  • model_admit_bytes — increments bytes_received by claimed only
  • model_record_block — inserts true size without post-success adjustment
  • models_api.rs tests — happy paths always send matching Content-Length via reqwest

🔒 Unchanged on main: Block store implementations predate this PR; honor them, do not redesign.

🔧 Required correction: After a successful digest verify, require stored_size == declared (reject with 400 and refund admission otherwise), or admit/charge the measured size (refund the delta) so session and node caps cannot be bypassed via understating headers. Add a regression test that sets a small Content-Length and sends a larger valid block body.

🛠️ Author fix: Close the cap contract on handler, DB accounting, and HTTP test in one pass; do not patch only admission SQL without the handler check.

🚫 Out of scope: Changing global block size limits or claim-time quota reservation rules.


🔵 P3 — Align session liveness across PUT, GET status, and CLI resume on expires_at

📍 Where: crates/twigpine-node/src/api/models.rs get_model_session vs put_model_block, crates/twigpine-cli/src/model.rs resume block

💥 What fails: After wall-clock expiry, put_model_block already rejects uploads (expires_at <= ts_now()), so ingest stays fail-closed. Until sweep flips state, get_model_session can still return state: "open" with a past expires_at, and the CLI resume path only checks state == "open", so a resumed publish loops on 404 PUTs until the operator deletes local state.

This is a resumability / operator-coherence gap, not a bypass of the PUT gate or a public read leak.

🔎 Root cause: Expiry is enforced on the write path but not on the operator-facing read/resume surfaces that define whether a session is resumable.

📜 Stated contract:

Resumable upload sessions … sliding TTL …

PUT handler already treats expiry as dead:

session.expires_at <= models::ts_now()

🏷️ Attribution: PR-introduced.

📌 In this PR:

  • put_model_block — hard TTL gate
  • get_model_session — no expires_at filter
  • model.rs resume — ignores expires_at in JSON
  • models_api.rs — tests PUT expiry, not GET/resume coherence

🔒 Unchanged on main: Sweep interval behavior on unchanged workers.

🔧 Required correction: Treat expires_at <= now as not found (or closed) on GET session status, and have the CLI discard resumed state when expiry has passed (parse expires_at or honor 404). Add a test that backdates expires_at, expects GET/CLI to abandon the session while state is still open.

🛠️ Author fix: Implement the same liveness rule on every in-diff resume/status surface in one pass.

🚫 Out of scope: Changing sweep cadence or TTL configuration defaults.

…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.
@beardthelion

Copy link
Copy Markdown
Collaborator Author

Pushed 85e4124.

  • P2 (model.rs pin): added "model.rs" to CONVERTED_IN_186. no_parse_before_status failed on 27e971c naming ["model.rs"] and passes now. This is the required test (*) failure.
  • P3 (session liveness): get_model_session now returns 404 once expires_at has passed, same rule as the block PUT. The CLI resume path already resets its state on a 404, so no CLI change. New test get_session_expired_open_session_not_found read 200 before the fix and 404 after.
  • P1 (understated Content-Length): not reproducible at this head. I sent a PUT with Content-Length: 4 and a chunked 4096-byte body over a raw socket and got 400 "length limit exceeded", nothing stored. The blocks route's RequestBodyLimitLayer cuts the body at the declared length. With that layer removed the same request returned 200, so I kept the request as put_block_understated_content_length_is_not_stored_under_small_charge to pin it. No admission or accounting change.
  • PR body: the models_db snippet is wrong (no such target; node coverage is models_api), and the workspace checkbox is stale. I am correcting both in the description.
  • Stack order feat(node): add model hosting storage and format foundation #620 then feat(node): add model release publishing and ingest #622 then feat(node): add the HF read surface, release durability, and model fetch #623 is unchanged.

Not run locally: the full workspace test job (the Windows and beta legs included).

@beardthelion
beardthelion requested a review from jatmn November 20, 2026 22:55

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up on head 85e41245: the prior read_json pin, session GET expiry, and required CI failures are addressed. Remaining issues below are verified on this head after a drift recheck (not pre-existing main debt, not out-of-scope framework work).

Merge readiness

  • Stacked base is feat/model-hosting-foundation, not main. Keep merge order #620 → #622 → #623 explicit.
  • Required CI on head 85e41245 is green (test (stable|beta|windows), fmt+clippy, build).
  • PR template: the cargo test --workspace checkbox is still unchecked while targeted suites pass in CI; reconcile the template or note full-workspace status before merge.
  • twigpine model publish poll: after 300s still verifying, the CLI exits 0 and leaves resume state — automation may treat that as success unless operators read the printed status URL. (No stated contract requiring a non-zero exit; tracked here only, not as a code finding.)

Drift and attribution (head 85e41245 vs merge-base 6c5431bf)

Pre-existing on target branch: None of the paths below exist at merge-base (e.g. crates/twigpine-node/src/db/model_queries.rs is absent at 6c5431bf). These are PR-introduced contracts, not main-head cleanup.

Withdrawn after drift recheck (not in Findings):

  • Understated Content-Length cap bypass (prior P1): not reproducible at head with the block route body limit; regression test pins non-200. Not a live defect on this head.
  • read_json enrollment / GET session expiry (prior P2/P3): fixed on 85e41245.
  • Same-commit re-claim after rejected: behavior is real in code, but the repo does not state a retry policy — see Needs maintainer decision only (not a mandatory author fix without product call).
  • Verify worker Internal wedging verifying for up to 6h: matches the PR’s documented bound, not a new defect class.

Scope drift: Corrections for the three Findings stay inside this PR’s new surfaces (model_queries.rs SUM/refund rules, put_model_block, model.rs save_state reusing secret_file). They do not require rewriting unchanged node/CLI core, blockstore implementations, or claim quota design.

Findings

🟡 P2 — Open-session caps must not count wall-clock-dead sessions

📍 Where: crates/twigpine-node/src/db/model_queries.rs — model_admit_bytes, model_tx_node_used; crates/twigpine-node/src/models/sweep.rs (60s expire tick)

💥 What fails: Block PUT and GET treat expires_at <= now as dead, but quota math still sums every row with state = 'open', ignoring expiry, until the sweep flips state to expired. Between expiry and the next sweep (~60s), dead sessions still inflate per-owner session totals and the node-wide open-session term, so unrelated uploads or claims can spuriously hit caps.

🔎 Root cause: The admission and claim node-cap queries key only on state = 'open', not the same liveness rule the HTTP handlers already apply on expires_at.

📜 Stated contract:

Adds … atomic per-identity and node-wide admission caps …

PUT handler already treats expiry as dead:

session.expires_at <= models::ts_now()

🏷️ Attribution: PR-introduced (model_admit_bytes, model_tx_node_used are new at 6c5431bf).

📌 In this PR:

  • model_admit_bytes — per-owner and node-wide SUMs over state = 'open' only (no expires_at > now() on peer rows)
  • model_tx_node_used — same SUM for claim-time node cap
  • models_api.rs — PUT/GET expiry gates and tests
  • sweep.rs — eventual state = 'expired', not immediate cap relief

🔒 Unchanged on main: Sweep cadence and TTL defaults are configuration, not redesigned here.

🔧 Required correction: Add expires_at > now() (same clock helper as handlers) to every open-session byte SUM used for caps — admit’s cross-session terms and model_tx_node_used. Add a regression test that backdates expires_at, leaves state = 'open', and proves admit/claim cap math ignores the row before sweep runs.

🛠️ Author fix: Close the liveness rule on every cap SUM in this PR in one pass; do not patch only PUT handlers.

🚫 Out of scope: Changing sweep interval or session TTL configuration defaults.


🟡 P2 — Global block dedup must not bill open-session caps for bytes already stored

📍 Where: crates/twigpine-node/src/api/models.rs put_model_block; crates/twigpine-node/src/db/model_queries.rs model_admit_bytes / model_record_block; crates/twigpine-cli/src/model.rs upload loop

💥 What fails: A PUT of a block that already exists on disk (new session, or a re-publish) still runs model_admit_bytes for the full Content-Length, then put_verified returns AlreadyPresent, then model_record_block links the block to the session without refunding admission unless the duplicate is within the same session (ON CONFLICT (session_id, block_sha256)). Open-session and node-wide caps stay inflated until claim moves bytes to the release row — even though claim authorization already allows blocks from prior published releases without re-upload.

This is an accounting / 429-before-claim defect, not a claim-authorization bypass.

The bundled CLI always PUTs every packed block not in local resume state, so it routinely hits this path on incremental publishes.

🔎 Root cause: Dedup refund is scoped to within-session duplicate links only; cross-session / global AlreadyPresent is not dedup-aware for cap accounting.

📜 Stated contract:

unsigned content-addressed block PUTs (… dedup-aware accounting).

🏷️ Attribution: PR-introduced (new PUT path and model_record_block).

📌 In this PR:

  • put_model_block — admit before store; success path always records block with admitted = declared
  • model_record_block — refunds admitted bytes only when linked == 0 (same session duplicate)
  • model_tx_publisher_release_blocks — claim may authorize prior-release blocks without session links
  • model.rs — upload loop keys on local uploaded, not node-side presence
  • models_api.rs — duplicate-within-session test only

🔒 Unchanged on main: Block store AlreadyPresent semantics; do not redesign store.

🔧 Required correction: After a successful put_verified (including AlreadyPresent), if the block was already globally present and this session just gained a new link, refund the admission charge (or skip admit when model_blocks already holds the sha). Add HTTP or DB regression: second session PUT of an existing block must not increase bytes_received / node open-session totals. Optionally skip CLI PUTs when the node already holds the block from the publisher’s prior release (same correction family).

🛠️ Author fix: Close dedup-aware accounting on handler, SQL refund/skip, and regression test in one pass; align CLI upload loop if it remains in this PR’s scope.

🚫 Out of scope: Changing per-publisher quota reservation at claim or global block size limits.


🔵 P3 — Resume publish state must use owner-only permissions like other CLI secrets

📍 Where: crates/twigpine-cli/src/model.rs — save_state, STATE_FILE_NAME (twigpine-model-publish.json under .git)

💥 What fails: Resume state stores the session bearer (session_id) and uploaded block list using plain File::create without 0600. On shared machines, default umask can leave the bearer readable to group/other; the unsigned block PUT path trusts that capability.

🔎 Root cause: New resume file path bypasses the crate’s existing owner-only write helper used for comparable secrets.

📜 Stated contract:

Write contents to path with owner-only permissions.

(from crates/twigpine-cli/src/secret_file.rs)

🏷️ Attribution: PR-introduced (save_state is new in model.rs).

📌 In this PR:

  • model.rs — save_state / load_state for .git/twigpine-model-publish.json
  • http.rs — put_unsigned + session header (consumer of bearer)

🔒 Unchanged on main: secret_file helper; call it, do not fork permission logic.

🔧 Required correction: Write resume state through secret_file (or equivalent 0600 + fsync) on every save. Add a unit test asserting mode 0o600 on the state file, matching secret_file tests.

🛠️ Author fix: Close permissions on every save_state call site in this PR in one pass.

🚫 Out of scope: Encrypting the bearer or changing session wire format.

Needs maintainer decision

Same commit_sha re-claim after rejected: claim_release returns the existing row from model_tx_release_by_commit for any state, including rejected, without re-queueing verification. That blocks a same-commit retry after a rejected verify unless the publisher mints a new commit. The PR does not state whether that is intentional permanence or operators should be able to re-claim. Drift note: this is not listed under Findings because there is no stated contract to violate; confirm expected behavior before encoding a fix (e.g. allow re-claim only from rejected, or document that a new commit is required).

…sed blocks, write resume state owner-only

Open-session byte sums used for the per-owner and node-wide caps (and the
claim-time node total) now require expires_at > now, matching the PUT and
GET liveness rule, so a session past its TTL stops counting before the
sweep flips its state.

A block PUT that links a block a verifying or published release already
carries refunds the admission charge; that release was billed at claim.
Blocks held only by other open sessions stay charged.

The CLI resume file holds the session bearer and now goes through
secret_file::write (0600, no symlink follow), then fsync.
…blish

Conflicts in reconstruction.rs (took the base's validate and checked_len_sum
version, which supersedes the earlier overflow check here) and git/store.rs
(kept this branch's HIDDEN_REFS list with the base's deadline-bounded
run_git).
…'s own live release carries

A refunded link outlives its release: a rejection frees the quota and
deletes the release's block rows, leaving the session holding the block
unbilled while its expiry keeps sliding. Claim already authorizes a
publisher's own verifying or published release blocks without a link, so
the PUT is neither charged nor linked in that case. Blocks carried by
another publisher's release, or held by other open sessions, stay charged
and linked.
@beardthelion

Copy link
Copy Markdown
Collaborator Author

Addressed on 2a3497c, with the base branch merged in.

  • Dead sessions in the caps: the per-owner and node-wide sums in model_admit_bytes and the sum in model_tx_node_used now require expires_at > now. The new test failed before (node total 1800, expected 0), and removing any one of the three clauses fails it again.
  • Dedup accounting: done differently from the remedy you named. A PUT of a block that the session owner's own verifying or published release already carries is now neither charged nor linked, since claim already authorizes those blocks without a link. I did not refund and keep the link, because a rejection deletes the release's block rows and frees its quota, which would leave the session holding that block unbilled while its expiry keeps sliding. Blocks carried only by another publisher's release, a rejected release, or other open sessions stay charged. The CLI upload loop is unchanged.
  • Resume state: save_state writes through secret_file::write and then fsyncs. The mode test failed before (0o664 against 0o600).
  • Same commit after rejected: stays final for that commit. Verification judges the pinned commit, so a retry would rerun the same checks, and the publisher retries with a new commit. The behavior is now stated where the lookup happens in claim.rs.
  • The exit 0 while still verifying is left as is; the CLI prints the status URL.

fmt, clippy -D warnings and cargo metadata --locked pass on the merged head. The full workspace run had 29 failures in the twigpine-node lib tests, and they all pass on re-run. twigpine-cli task::tests::test_view_task_not_found fails the same way without these changes.

@beardthelion
beardthelion requested a review from jatmn November 21, 2026 05:53

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked on head 2a3497ce after prior jatmn review rounds: read_json pin, session GET expiry, cap sums ignoring wall-clock-dead sessions, dedup accounting for own-release blocks, and Unix resume permissions are addressed on this head. The two findings below survived a drift challenge (merge-base c122683b, live target feat/model-hosting-foundation); corrections stay inside this PR's new CLI surfaces.

Merge readiness

  • Stacked base is feat/model-hosting-foundation, not main. Keep merge order #620 → #622 → #623 explicit.
  • Required CI on head is green on Linux (test (stable), test (beta), fmt+clippy, build).
  • test (windows, non-blocking) fails on head with model::tests::publish_state_round_trips (PR-owned; see finding below).
  • PR template: the full-workspace cargo test --workspace checkbox remains unchecked; author notes flaky lib tests and a pre-existing task::tests::test_view_task_not_found failure — reconcile template vs CI reality before merge.
  • twigpine model publish poll: after 300s still verifying, the CLI exits 0 and leaves resume state (same as prior review; no repo contract requires non-zero exit — tracked here only).

Drift and attribution (head 2a3497ce vs merge-base c122683b)

Scope for author fixes: Both findings are PR-introduced (crates/twigpine-cli/src/model.rs is absent at c122683b). Neither asks to rebuild unchanged node/core, implement model_durability_jobs, or fix pre-existing main debt.

Withdrawn after drift recheck (not in Findings):

  • Cap sums / GET session / read_json enrollment / dedup refund semantics — fixed and tested on this head.
  • Understated Content-Length cap bypass — not reproducible at head; put_block_understated_content_length_is_not_stored_under_small_charge pins behavior.
  • secret_file loose permissions on Windows — existing off-Unix contract in secret_file.rs (caller supplies a private directory); not activated by this PR beyond reusing that helper.
  • Verify worker Internal wedging verifying for up to 6h — documented PR bound, not a new defect class.
  • Poll exit 0 while still verifying — no stated non-zero exit contract (merge-readiness only).
  • Session link liveness vs claim reachability before sweep — intentional; session_blocks_ignore_expired_sessions documents it.
  • Same-commit re-claim after rejected — product choice; now stated in claim.rs (no mandatory fix without maintainer call).
  • Stale docs/RUN-A-NODE.md "not yet usable" prose — file not in this diff; separate doc refresh, not a #622 code finding.

Findings

🟡 P2 — Resume state fsync breaks Windows unit tests

📍 Where: crates/twigpine-cli/src/model.rs — save_state; test model::tests::publish_state_round_trips

💥 What fails: cargo test -p twigpine-cli --bin twigpine on Windows fails:

called `Result::unwrap()` on an `Err` value: Access is denied. (os error 5)

at save_state after secret_file::write, on std::fs::File::open(path)?.sync_all()?.

🔎 Root cause: The resume file is written through secret_file::write, then reopened with the default read-only File::open for sync_all. On Windows CI this returns Access is denied, so the cross-platform round-trip test fails even though Linux passes.

📜 Stated contract:

The test (windows, non-blocking) job runs the workspace/unit test suite; a failing test is a regression on that head.

🏷️ Attribution: PR-introduced (model.rs and save_state are new on this diff; fsync landed with resume-state hardening in 8d6cae2). Not pre-existing Windows CI debt on an unchanged file.

📌 In this PR:

  • save_state — owner-only write then separate read-only open + sync_all
  • publish_state_round_trips — calls save_state without #[cfg(unix)]
  • Prior pattern in ucan_cmd.rs — sync_all on the writable handle before close, not a second read-only open

🔒 Unchanged on main: secret_file Unix owner-only contract; honor it, do not weaken.

🔧 Required correction: Durably sync on every platform: extend the write path to sync_all on the same writable descriptor (as write_private_file does on Windows), or open with read/write access before sync. Keep secret_file::write for permissions; add a Windows-safe sync helper if needed. Re-run the Windows job or publish_state_round_trips on Windows.

🛠️ Author fix: Close the resume durability contract on save_state and the round-trip test in one pass; do not drop fsync on Unix without an equivalent durability guarantee.

🚫 Out of scope: Changing session wire format or encrypting the resume file.


🔵 P3 — Confirm prompt misstates permanence (IPFS / Arweave)

📍 Where: crates/twigpine-cli/src/model.rs — publish confirm eprintln! (~625–627)

💥 What fails: Before --yes / interactive confirm, the CLI tells the operator:

publishing is permanent: blocks are pinned to IPFS and the manifest anchors
to Arweave, so the bytes stay fetchable even if this repo is later removed

This PR's path stores blocks in the node block store (filesystem or S3 per operator config), runs claim + verify workers, and does not enqueue IPFS/Pinata/Arweave durability for model releases (model_durability_jobs is schema-only; no worker references it in models/).

🔎 Root cause: The confirm copy conflates future protocol-wide durability with what twigpine model publish actually does today, so operators may assume automatic IPFS/Arweave pinning that never runs.

📜 Stated contract:

weights are stored as content-addressed blocks outside git.

(docs/RUN-A-NODE.md — Model hosting)

PR description: content-addressed block ingest and verify worker on the node.

🏷️ Attribution: PR-introduced (new CLI command copy). Not drift from unchanged pinning code paths — those stacks exist elsewhere and are explicitly out of scope below.

📌 In this PR:

  • model.rs confirm banner — IPFS/Arweave claim
  • Actual publish path — session PUTs → claim → verify; block store only

🔒 Unchanged on main: Repo-wide IPFS/Pinata stacks in pinata.rs / STORAGE-AND-PINNING.md for other features; do not conscript them into this PR.

🔧 Required correction: Rewrite the confirm text to match the implemented surface: blocks live in the node's configured block store, the release is a signed manifest in git, and availability depends on that node (and fully public repo policy) — not automatic IPFS/Arweave pinning. If a durability milestone is planned, say so without stating it already happens.

🛠️ Author fix: Close the operator-copy contract on the in-diff confirm string in one pass; do not add IPFS/Arweave wiring in this PR unless maintainers explicitly expand scope.

🚫 Out of scope: Implementing model_durability_jobs or pinning pipelines in the same merge.

…d correct the publish confirm text

save_state reopened the file read-only for sync_all, which fails with Access is denied on Windows and broke publish_state_round_trips there. Sync through a write handle instead.

The confirm prompt claimed IPFS pinning and Arweave anchoring, which this path does not do. State what it does: blocks go to the node's block store and the signed manifest to git.
@beardthelion

Copy link
Copy Markdown
Collaborator Author

Both findings from the last review are fixed in 5902079, on top of a merge of current feat/model-hosting-foundation (it had moved two commits and conflicted in reconstruction.rs).

  • P2 (resume fsync on Windows): confirmed from the Windows job log, publish_state_round_trips panics with os error 5 inside save_state. The sync now goes through a handle opened for write, so it still fsyncs on every platform and secret_file::write is unchanged. The round-trip and owner-only mode tests pass on Linux. I have not run it on Windows; the Windows job on this head will show it.
  • P3 (confirm text): confirmed, the publish path has no IPFS or Arweave step and model_durability_jobs is schema only here. The prompt now says the blocks go to this node's block store, the signed manifest goes to git, availability depends on the node keeping them, and nothing is pinned or anchored.

The merge conflict was in DedupIndex::add_block_entries: the base now skips a block id it already holds a layout for, and this branch had split add into add/add_block_entries. I kept both, with the layout check inside the per-entry loop.

#623 is built on this branch and its publish confirm text will need to restore the IPFS and Arweave wording when it picks this up, since it adds that durability work.

fmt and clippy -D warnings pass on the workspace, and the full workspace suite passes on the merge.

@beardthelion
beardthelion requested a review from jatmn November 22, 2026 23:32

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked on head 590207909b755ac9a0f6c5e84f62a8fb7dcafb8a after the prior jatmn rounds (read_json pin, session GET expiry, cap sums, dedup accounting, resume save_state fsync, confirm copy). Required CI on this head is green (including test (windows, non-blocking)).

Merge readiness

  • Stacked base is feat/model-hosting-foundation, not main. Keep merge order #620 → #622 → #623 explicit when landing the stack.
  • PR template: the full-workspace cargo test --workspace checkbox is still unchecked in the body. Author notes on head say the full suite passes after the latest base merge—reconcile the template or the note before merge so reviewers are not sent to stale failure expectations.
  • twigpine model publish poll: after POLL_BUDGET (300s), a release still in verifying prints the status URL and the CLI exits 0 (crates/twigpine-cli/src/model.rs). There is no repo contract requiring a non-zero exit; treat this as operator/automation awareness, not a merge blocker.

Drift and attribution (head vs merge-base a3edf072)

Prior code findings on this diff are addressed on this head. Blind-search candidates (overstated Content-Length cap inflation, verify-worker internal Err wedging, missing HTTP e2e verify, mixed 400/429 quota codes, Windows secret_file semantics) were re-verified and withdrawn: either not reproduced, documented bounds (6h stale verifying), pre-existing non-Unix secret_file behavior, test-harness gaps without demonstrated production failure, or intentional async-verify architecture. Corrections would stay inside this PR's surfaces only—none require rewriting unchanged node/core.

🟢 Thanks for the contribution. I do not see any actionable issues from my review.

@beardthelion
beardthelion merged commit c2c6fc1 into feat/model-hosting-foundation Nov 23, 2026
17 checks passed
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.

2 participants