From 31140ff715fd67cc05216a76f3affb452c6b8ba8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:10:22 -0600 Subject: [PATCH 01/20] feat(node): add model upload sessions, release claims, and reclamation --- crates/twigpine-node/src/api/mod.rs | 13 + crates/twigpine-node/src/api/models.rs | 361 ++++++++ crates/twigpine-node/src/api/status/mod.rs | 4 +- crates/twigpine-node/src/db/mod.rs | 30 +- crates/twigpine-node/src/db/model_queries.rs | 888 +++++++++++++++++++ crates/twigpine-node/src/git/store.rs | 2 +- crates/twigpine-node/src/lib.rs | 11 + crates/twigpine-node/src/models/claim.rs | 272 ++++++ crates/twigpine-node/src/models/mod.rs | 173 ++++ crates/twigpine-node/src/models/sweep.rs | 80 ++ crates/twigpine-node/src/models/verify.rs | 307 +++++++ crates/twigpine-node/src/server.rs | 72 +- crates/twigpine-node/src/test_harness.rs | 54 +- crates/twigpine-node/tests/deny_harness.rs | 18 + crates/twigpine-node/tests/support/probe.rs | 15 + crates/twigpine-node/tests/support/routes.rs | 78 ++ 16 files changed, 2369 insertions(+), 9 deletions(-) create mode 100644 crates/twigpine-node/src/api/models.rs create mode 100644 crates/twigpine-node/src/db/model_queries.rs create mode 100644 crates/twigpine-node/src/models/claim.rs create mode 100644 crates/twigpine-node/src/models/mod.rs create mode 100644 crates/twigpine-node/src/models/sweep.rs create mode 100644 crates/twigpine-node/src/models/verify.rs diff --git a/crates/twigpine-node/src/api/mod.rs b/crates/twigpine-node/src/api/mod.rs index 75a560be..5d69fadd 100644 --- a/crates/twigpine-node/src/api/mod.rs +++ b/crates/twigpine-node/src/api/mod.rs @@ -13,6 +13,7 @@ pub mod events; pub mod ipfs; pub mod issues; pub mod labels; +pub mod models; pub mod peers; pub mod profiles; pub mod protect; @@ -219,6 +220,7 @@ mod authz_guard { let repos = include_str!("repos.rs"); let register = include_str!("register.rs"); let ipfs = include_str!("ipfs.rs"); + let models = include_str!("models.rs"); // (source, handler, expected gate marker) let rows: &[(&str, &str, &str)] = &[ @@ -323,6 +325,14 @@ mod authz_guard { (visibility, "remove_visibility", "require_owner("), (visibility, "list_visibility", "authorize_repo_read("), (visibility, "list_visibility", "require_owner("), + // Model hosting writes: session open and claim are owner-only + // behind the shared read gate; the unsigned block PUT read-gates + // as the session's owner. + (models, "open_model_session", "authorize_repo_read("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "authorize_repo_read("), + (models, "claim_model_release", "require_repo_owner("), + (models, "put_model_block", "authorize_repo_read("), ]; // Rows above prove each visibility handler calls authorize_repo_read and @@ -352,6 +362,8 @@ mod authz_guard { (issues, "close_issue", "did_matches("), (protect, "protect_branch", "did_matches("), (protect, "unprotect_branch", "did_matches("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "require_repo_owner("), ] { let body = fn_body(src, func); let gate = body.find("authorize_repo_read(").expect("gate marker"); @@ -1194,6 +1206,7 @@ mod tests { async fn t() { let _ = did_matches(x, y); } } (include_str!("events.rs"), "events.rs"), (include_str!("issues.rs"), "issues.rs"), (include_str!("labels.rs"), "labels.rs"), + (include_str!("models.rs"), "models.rs"), (include_str!("protect.rs"), "protect.rs"), (include_str!("pulls.rs"), "pulls.rs"), (include_str!("replicas.rs"), "replicas.rs"), diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs new file mode 100644 index 00000000..e916da1b --- /dev/null +++ b/crates/twigpine-node/src/api/models.rs @@ -0,0 +1,361 @@ +//! Open-weight model hosting routes: signed upload-session open, unsigned +//! bearer-session block ingest, signed release claim, and the publisher +//! status reads. Mounted only when the operator enables model hosting; every +//! handler re-checks `state.block_store` so a disabled node answers the same +//! not-found as an unmounted route. + +use axum::extract::{Path, Request, State}; +use axum::http::HeaderMap; +use axum::response::IntoResponse; +use axum::{Extension, Json}; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::json; + +use crate::api::{authorize_repo_read, require_repo_owner}; +use crate::auth::{AuthenticatedDid, SignatureMaterial}; +use crate::blockstore::{BlockId, BlockStoreError}; +use crate::db::{RepoRecord, VisibilityRule}; +use crate::error::{AppError, Result}; +use crate::models; +use crate::state::AppState; + +/// `X-Twigpine-Model-Session`: the bearer credential on block PUTs. The +/// session id is a 256-bit random capability minted at session open; there +/// is no HTTP signature on the PUT because a 64 MiB signed body would have +/// to be buffered whole to verify. +pub const SESSION_HEADER: &str = "x-twigpine-model-session"; + +fn hosting_enabled(state: &AppState) -> Result<()> { + if state.block_store.is_some() { + Ok(()) + } else { + Err(AppError::NotFound( + "model hosting is not enabled on this node".into(), + )) + } +} + +/// Model hosting only serves fully public repositories: a private repo, or +/// a public one carrying any path-scoped visibility rule, refuses with a +/// clear 4xx rather than partially publishing. +fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { + if !record.is_public || !rules.is_empty() { + return Err(AppError::BadRequest( + "model hosting requires a fully public repository".into(), + )); + } + Ok(()) +} + +#[derive(Debug, Deserialize, Default)] +pub struct OpenSessionBody { + /// Optional commit sha of the declared parent release. Informational at + /// open time; the claim re-anchors the parent through the manifest. + #[serde(default)] + pub parent_release: Option, +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/sessions` — open an upload +/// session. Owner-only (a session writes bytes the owner is billed for) on a +/// fully public repo. +pub async fn open_model_session( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + _body: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + let session = models::open_session( + &state.db, + caller, + &record.id, + state.config.model_session_ttl_secs, + ) + .await?; + Ok(( + axum::http::StatusCode::CREATED, + Json(json!({ + "session_id": session.id, + "expires_at": session.expires_at, + })), + )) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/sessions/{id}` — owner-only +/// session status. +pub async fn get_model_session( + State(state): State, + Path((owner, name, id)): Path<(String, String, String)>, + Extension(auth): Extension, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, _rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + let session = models::load_session(&state.db, &id) + .await? + .filter(|s| s.repo_id == record.id) + .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; + Ok(Json(json!({ + "session_id": session.id, + "state": session.state, + "bytes_received": session.bytes_received, + "expires_at": session.expires_at, + }))) +} + +/// PUT `/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}` — stream one +/// content block under a session bearer. Unsigned by design (see +/// [`SESSION_HEADER`]); the gate resolves the session, then runs the repo +/// read check as the session's owner so a repo turned private or withheld +/// mid-upload stops accepting bytes. +pub async fn put_model_block( + State(state): State, + Path((owner, name, sha)): Path<(String, String, String)>, + headers: HeaderMap, + request: Request, +) -> Result> { + hosting_enabled(&state)?; + let Some(session_id) = headers + .get(SESSION_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + else { + return Err(AppError::Unauthorized( + "a model block PUT requires the session header".into(), + )); + }; + let pool = &state.db; + let Some(session) = models::load_session(pool, &session_id).await? else { + return Err(AppError::NotFound("model upload session not found".into())); + }; + // authorize_repo_read 404s a repo the session owner can no longer read; + // the session-to-repo binding check below keeps foreign-session PUTs + // indistinguishable from a missing session. + let (record, _rules) = + authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; + if session.repo_id != record.id + || session.state != "open" + || session.expires_at <= models::ts_now() + { + return Err(AppError::NotFound("model upload session not found".into())); + } + let block_id = + BlockId::parse(&sha).map_err(|e| AppError::BadRequest(format!("block id: {e}")))?; + let declared: u64 = headers + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .ok_or_else(|| AppError::BadRequest("Content-Length is required".into()))?; + if declared == 0 || declared > models::MAX_BLOCK_BYTES { + return Err(AppError::BadRequest(format!( + "block bodies are 1..{} bytes", + models::MAX_BLOCK_BYTES + ))); + } + + // Admission before any byte is stored: the conditional update is the + // atomic charge against both the per-identity session cap and the + // node-wide quota, and it slides the session expiry in the same write. + let session_cap = state.config.effective_model_max_session_bytes() as i64; + let node_cap = state.config.model_node_quota_bytes as i64; + let Some(_) = models::admit_bytes( + pool, + &session.id, + declared as i64, + state.config.model_session_ttl_secs, + session_cap, + node_cap, + ) + .await? + else { + // Not admitted: re-check whether the session died (404 hides the + // session) or a cap refused (named quota). + let session = models::load_session(pool, &session_id) + .await? + .filter(|s| s.state == "open" && s.expires_at > models::ts_now()); + return match session { + None => Err(AppError::NotFound("model upload session not found".into())), + Some(_) => Err(AppError::TooManyRequests(format!( + "the upload would exceed a model storage cap \ + (session cap {session_cap} bytes, node cap {node_cap} bytes)" + ))), + }; + }; + + let store = state.block_store.clone().expect("checked above"); + let stream = request + .into_body() + .into_data_stream() + .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); + let outcome = store + .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) + .await; + let outcome = match outcome { + Ok(o) => o, + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(match e { + BlockStoreError::DigestMismatch => { + AppError::BadRequest(format!("block body does not hash to the named id {sha}")) + } + BlockStoreError::TooLarge(cap) => { + AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + } + BlockStoreError::Unknown => AppError::Conflict( + "the write's outcome is unknown; check the object before retrying".into(), + ), + other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), + }); + } + }; + let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. + + let size = store + .size(&block_id) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")))? + .unwrap_or(declared); + let duplicate = models::record_block(pool, &session.id, &sha, size, declared as i64).await?; + let fresh = models::load_session(pool, &session.id).await?; + Ok(Json(json!({ + "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), + "duplicate": duplicate, + "expires_at": fresh.map(|s| s.expires_at).unwrap_or_default(), + }))) +} + +#[derive(Debug, Deserialize)] +pub struct ClaimBody { + pub commit: String, + pub branch: String, +} + +fn release_view(r: &models::ReleaseRow) -> serde_json::Value { + json!({ + "release_id": r.id, + "commit": r.commit_sha, + "branch": r.branch, + "state": r.state, + "manifest_sha256": r.manifest_sha256, + "failure_reason": r.failure_reason, + "created_at": r.created_at, + "published_at": r.published_at, + }) +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/claims` — claim a pushed commit +/// as a model release. Runs the ordered KTD5 checks; a replay resolves to the +/// original row via the persisted request digest. +pub async fn claim_model_release( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + material: Option>, + Json(body): Json, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + + let Some(Extension(material)) = material else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its signature material" + ))); + }; + let Some(body_bytes) = material.body.clone() else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its persisted request body" + ))); + }; + crate::api::status::require_body_bound_signature(&material, &body_bytes)?; + if body.commit.len() != 40 || !body.commit.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(AppError::BadRequest("commit must be a 40-hex sha".into())); + } + let material = models::claim::ClaimMaterial { + request_digest: crate::api::status::request_digest(&material, &body_bytes), + signature: material.signature, + signature_input: material.signature_input, + signing_string: material.signing_string, + body: body_bytes.to_vec(), + }; + let release = models::claim::claim_release( + &state, + &record, + caller, + &body.commit, + &body.branch, + &material, + ) + .await?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}` — release +/// status. Same read gate as the repo's other listing surfaces: anonymous on +/// a public repo, 404 where the caller cannot read. +pub async fn get_model_release( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result> { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + let (record, _rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + let release = models::release_by_commit(&state.db, &record.id, &commit) + .await? + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}/reconstruction` +/// — the reconstruction object of a published release, for publisher-side +/// dedup (KTD6). The repo read gate applies, plus the current-public check: +/// once a repo stops being fully public it stops serving model objects, +/// owner included. +pub async fn get_model_reconstruction( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + let (record, rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + if !record.is_public || !rules.is_empty() { + return Err(AppError::NotFound("model release not found".into())); + } + let release = models::release_by_commit(&state.db, &record.id, &commit) + .await? + .filter(|r| r.state == "published") + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + let (manifest_bytes, manifest) = models::claim::read_verified_manifest( + &state.git_bin, + &std::path::PathBuf::from(&record.disk_path), + &release.commit_sha, + &record.owner_did, + ) + .await?; + let _ = manifest_bytes; + let Some(rec_ref) = &manifest.reconstruction else { + return Err(AppError::NotFound( + "release has no reconstruction object".into(), + )); + }; + let store = state.block_store.clone().expect("checked above"); + let bytes = models::read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; + Ok(( + [(axum::http::header::CONTENT_TYPE, "application/octet-stream")], + bytes, + )) +} diff --git a/crates/twigpine-node/src/api/status/mod.rs b/crates/twigpine-node/src/api/status/mod.rs index ab736a80..7fe8cf21 100644 --- a/crates/twigpine-node/src/api/status/mod.rs +++ b/crates/twigpine-node/src/api/status/mod.rs @@ -278,7 +278,7 @@ pub async fn create_status( /// /// A 400, not a 500: the material is exactly what the client signed, and what /// they signed does not cover what they sent. -fn require_body_bound_signature( +pub(crate) fn require_body_bound_signature( material: &crate::auth::SignatureMaterial, body: &[u8], ) -> Result<()> { @@ -317,7 +317,7 @@ fn require_body_bound_signature( /// This is not a nonce, and deliberately so. A nonce table needs pruning and a /// pruning window is a second replay window; the claim row IS the record of what /// was accepted, so uniqueness on it is self-maintaining. -fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { +pub(crate) fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); for part in [ diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 486a3391..0fe0d0d9 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -529,6 +529,8 @@ pub struct MarkerCleanup { /// spellings, and tests + the recovery drain all use them so a typo on one /// side or the other cannot silently mismatch the other. #[allow(dead_code)] // constants are used by tests + the next-slice handler +pub mod model_queries; + pub mod pending_state { #[allow(dead_code)] pub const PREPARED: &str = "prepared"; @@ -2820,6 +2822,30 @@ const MIGRATIONS: &[Migration] = &[ "CREATE INDEX IF NOT EXISTS idx_model_durability_jobs_pending ON model_durability_jobs (state, created_at)", ], }, + Migration { + version: 50, + name: "model_release_claim_digest_and_cascades", + stmts: &[ + // Replayed claims resolve by request digest instead of writing a + // second row, mirroring status_claims' dedupe. + "ALTER TABLE model_releases ADD COLUMN IF NOT EXISTS claim_request_digest TEXT", + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_request_digest ON model_releases (claim_request_digest) WHERE claim_request_digest IS NOT NULL", + // One in-flight verification per publisher: claim admission's + // check is check-then-act under the advisory lock, and this index + // is the backstop that makes a bug there still fail closed. + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_one_verifying ON model_releases (publisher_did) WHERE state = 'verifying'", + // A deleted repo takes its sessions, releases, and links with it. + // The FK constraints are re-declared with ON DELETE CASCADE; the + // names are Postgres defaults (table_column_fkey). + "ALTER TABLE model_upload_sessions DROP CONSTRAINT IF EXISTS model_upload_sessions_repo_id_fkey, ADD CONSTRAINT model_upload_sessions_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_session_id_fkey, ADD CONSTRAINT model_session_blocks_session_id_fkey FOREIGN KEY (session_id) REFERENCES model_upload_sessions(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_block_sha256_fkey, ADD CONSTRAINT model_session_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_releases DROP CONSTRAINT IF EXISTS model_releases_repo_id_fkey, ADD CONSTRAINT model_releases_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_release_id_fkey, ADD CONSTRAINT model_release_blocks_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_block_sha256_fkey, ADD CONSTRAINT model_release_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_durability_jobs DROP CONSTRAINT IF EXISTS model_durability_jobs_release_id_fkey, ADD CONSTRAINT model_durability_jobs_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -14430,7 +14456,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ($1, $2, 'main', 'did:key:zOwner', 'verifying', + VALUES ($1, $2, 'main', 'did:key:zOwner', 'published', $3, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(repo_id) @@ -14507,7 +14533,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'verifying', + VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'published', $2, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(SHA_A) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs new file mode 100644 index 00000000..9a5a1eb6 --- /dev/null +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -0,0 +1,888 @@ +//! Model-hosting queries. Timestamps follow the repo convention: rfc3339 +//! text in TEXT columns, written and compared through the helpers here. + +#[cfg(any(test, feature = "test-harness"))] +use sqlx::PgPool; +use sqlx::{Postgres, Transaction}; + +use super::{Db, Result}; + +fn ts_now() -> String { + chrono::Utc::now().to_rfc3339() +} + +fn ts_from_now(secs: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() +} + +#[derive(Debug, Clone)] +pub struct ModelSession { + pub id: String, + pub owner_did: String, + pub repo_id: String, + pub expires_at: String, + pub bytes_received: i64, + pub state: String, +} + +type SessionTuple = (String, String, String, String, i64, String); + +const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; + +impl From for ModelSession { + fn from(t: SessionTuple) -> Self { + ModelSession { + id: t.0, + owner_did: t.1, + repo_id: t.2, + expires_at: t.3, + bytes_received: t.4, + state: t.5, + } + } +} + +#[derive(Debug, Clone)] +pub struct ModelRelease { + pub id: i64, + pub repo_id: String, + pub commit_sha: String, + pub branch: String, + pub publisher_did: String, + pub state: String, + pub manifest_sha256: String, + pub failure_reason: Option, + pub created_at: String, + pub published_at: Option, + pub request_digest: Option, +} + +#[allow(clippy::type_complexity)] +pub type ReleaseTuple = ( + i64, + String, + String, + String, + String, + String, + String, + Option, + String, + Option, + Option, +); + +impl From for ModelRelease { + fn from(t: ReleaseTuple) -> Self { + ModelRelease { + id: t.0, + repo_id: t.1, + commit_sha: t.2, + branch: t.3, + publisher_did: t.4, + state: t.5, + manifest_sha256: t.6, + failure_reason: t.7, + created_at: t.8, + published_at: t.9, + request_digest: t.10, + } + } +} + +pub const RELEASE_COLS: &str = "id, repo_id, commit_sha, branch, publisher_did, \ + state, manifest_sha256, failure_reason, created_at, published_at, \ + claim_request_digest"; + +/// Fields of the signed claim persisted on the release row (the status-claim +/// pattern: the row is the replay ledger). +pub struct ClaimPersist { + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, + pub request_digest: String, +} + +impl Db { + pub async fn model_open_session( + &self, + owner_did: &str, + repo_id: &str, + ttl_secs: u64, + ) -> Result { + let id = hex::encode(rand::random::<[u8; 32]>()); + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1, $2, $3, $4, $5, 0, 'open') + RETURNING {SESSION_COLS}" + )) + .bind(&id) + .bind(owner_did) + .bind(repo_id) + .bind(ts_now()) + .bind(ts_from_now(ttl_secs as i64)) + .fetch_one(&self.pool) + .await?; + Ok(row.into()) + } + + pub async fn model_load_session(&self, id: &str) -> Result> { + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "SELECT {SESSION_COLS} FROM model_upload_sessions WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Atomically admit `claimed` bytes against the caller's per-identity + /// open-session cap and the node-wide quota, sliding expiry forward in + /// the same update. `None` when the session is closed, expired, or a cap + /// would be exceeded; the caller re-reads the session to pick the honest + /// denial. + pub async fn model_admit_bytes( + &self, + session_id: &str, + claimed: i64, + ttl_secs: u64, + session_cap: i64, + node_cap: i64, + ) -> Result> { + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "UPDATE model_upload_sessions s + SET bytes_received = s.bytes_received + $1, + expires_at = $2 + WHERE s.id = $3 + AND s.state = 'open' + AND s.expires_at > $4 + AND s.bytes_received + $1 + COALESCE(( + SELECT SUM(o.bytes_received) FROM model_upload_sessions o + WHERE o.owner_did = s.owner_did AND o.state = 'open' AND o.id <> s.id + ), 0) <= $5 + AND COALESCE((SELECT SUM(q.bytes_used) FROM model_quota_usage q), 0) + + COALESCE(( + SELECT SUM(o2.bytes_received) FROM model_upload_sessions o2 + WHERE o2.state = 'open' + ), 0) + + $1 <= $6 + RETURNING {SESSION_COLS}" + )) + .bind(claimed) + .bind(ts_from_now(ttl_secs as i64)) + .bind(session_id) + .bind(ts_now()) + .bind(session_cap) + .bind(node_cap) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Refund an admitted charge when the store or the bookkeeping fails. + /// Best-effort under races; an expired session frees the bytes anyway. + pub async fn model_refund_bytes(&self, session_id: &str, bytes: i64) -> Result<()> { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(bytes) + .bind(session_id) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Book the stored block against the session in one transaction. `true` + /// when this PUT was a duplicate within the session (the admission + /// credit was refunded). + pub async fn model_record_block( + &self, + session_id: &str, + block_sha: &str, + size: u64, + admitted: i64, + ) -> Result { + let mut tx = self.pool.begin().await?; + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at, unreferenced_since) + VALUES ($1, $2, $3, $3) + ON CONFLICT (sha256) DO NOTHING", + ) + .bind(block_sha) + .bind(size as i64) + .bind(ts_now()) + .execute(&mut *tx) + .await?; + let linked = sqlx::query( + "INSERT INTO model_session_blocks (session_id, block_sha256) + VALUES ($1, $2) + ON CONFLICT (session_id, block_sha256) DO NOTHING", + ) + .bind(session_id) + .bind(block_sha) + .execute(&mut *tx) + .await? + .rows_affected(); + if linked == 0 { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(admitted) + .bind(session_id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(linked == 0) + } + + pub async fn model_release_by_commit( + &self, + repo_id: &str, + commit: &str, + ) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_release_by_id(&self, id: i64) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_begin(&self) -> Result> { + Ok(self.pool.begin().await?) + } + + // ── claim transaction steps ─────────────────────────────────────────── + + pub async fn model_tx_advisory_lock( + &self, + tx: &mut Transaction<'_, Postgres>, + key: i64, + ) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(&mut **tx) + .await?; + Ok(()) + } + + pub async fn model_tx_release_by_digest( + &self, + tx: &mut Transaction<'_, Postgres>, + digest: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE claim_request_digest = $1" + )) + .bind(digest) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + pub async fn model_tx_release_by_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + /// Lock and return the present subset of `shas` (`FOR UPDATE` so a + /// racing sweep cannot delete a block mid-claim). + pub async fn model_tx_lock_present_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result> { + if shas.is_empty() { + return Ok(Vec::new()); + } + Ok( + sqlx::query_scalar("SELECT sha256 FROM model_blocks WHERE sha256 = ANY($1) FOR UPDATE") + .bind(shas) + .fetch_all(&mut **tx) + .await?, + ) + } + + pub async fn model_tx_session_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + owner_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sb.block_sha256 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE s.owner_did = $1 AND s.state = 'open'", + ) + .bind(owner_did) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_publisher_release_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.publisher_did = $1 AND r.state IN ('verifying', 'published')", + ) + .bind(publisher_did) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_release_blocks_at_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.repo_id = $1 AND r.commit_sha = $2 AND r.state = 'published'", + ) + .bind(repo_id) + .bind(commit) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_has_verifying( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT id FROM model_releases + WHERE publisher_did = $1 AND state = 'verifying' LIMIT 1", + ) + .bind(publisher_did) + .fetch_optional(&mut **tx) + .await? + .is_some()) + } + + /// Bytes of `shas` not already referenced by any live release: the + /// first-claimer-pays charge. + pub async fn model_tx_unclaimed_bytes( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result { + if shas.is_empty() { + return Ok(0); + } + Ok(sqlx::query_scalar::<_, Option>( + "SELECT SUM(b.size) FROM model_blocks b + WHERE b.sha256 = ANY($1) + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published'))", + ) + .bind(shas) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + /// Atomic per-identity reservation; `None` when the cap would be + /// exceeded. + pub async fn model_tx_reserve_quota( + &self, + tx: &mut Transaction<'_, Postgres>, + did: &str, + delta: i64, + cap: i64, + ) -> Result> { + Ok(sqlx::query_scalar::<_, i64>( + "INSERT INTO model_quota_usage (did, bytes_used) VALUES ($1, $2) + ON CONFLICT (did) DO UPDATE + SET bytes_used = model_quota_usage.bytes_used + $2 + WHERE model_quota_usage.bytes_used + $2 <= $3 + RETURNING bytes_used", + ) + .bind(did) + .bind(delta) + .bind(cap) + .fetch_optional(&mut **tx) + .await?) + } + + /// Node-wide used bytes: claimed quota plus every open session's bytes. + pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions + WHERE state = 'open'), 0)", + ) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + #[allow(clippy::too_many_arguments)] + pub async fn model_tx_insert_release( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + branch: &str, + publisher_did: &str, + manifest_sha256: &str, + reconstruction_sha256: Option<&str>, + claim: &ClaimPersist, + ) -> Result { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + reconstruction_sha256, claim_signature, claim_signature_input, + claim_signing_string, claim_body, claim_request_digest, created_at) + VALUES ($1,$2,$3,$4,'verifying',$5,$6,$7,$8,$9,$10,$11,$12) + RETURNING {RELEASE_COLS}" + )) + .bind(repo_id) + .bind(commit) + .bind(branch) + .bind(publisher_did) + .bind(manifest_sha256) + .bind(reconstruction_sha256) + .bind(&claim.signature) + .bind(&claim.signature_input) + .bind(&claim.signing_string) + .bind(&claim.body) + .bind(&claim.request_digest) + .bind(ts_now()) + .fetch_one(&mut **tx) + .await?; + Ok(row.into()) + } + + /// Link `sha` to the release and drop it from the publisher's open + /// sessions, so the same bytes stop counting twice node-wide. + pub async fn model_tx_link_release_block( + &self, + tx: &mut Transaction<'_, Postgres>, + release_id: i64, + publisher_did: &str, + sha: &str, + ) -> Result<()> { + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) + VALUES ($1, $2) ON CONFLICT DO NOTHING", + ) + .bind(release_id) + .bind(sha) + .execute(&mut **tx) + .await?; + sqlx::query( + "DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE s.id = sb.session_id AND s.owner_did = $1 + AND s.state = 'open' AND sb.block_sha256 = $2", + ) + .bind(publisher_did) + .bind(sha) + .execute(&mut **tx) + .await?; + Ok(()) + } + + pub async fn model_tx_recount_open_session_bytes( + &self, + tx: &mut Transaction<'_, Postgres>, + owner_did: &str, + ) -> Result<()> { + sqlx::query( + "UPDATE model_upload_sessions s + SET bytes_received = COALESCE(( + SELECT SUM(b.size) FROM model_session_blocks sb + JOIN model_blocks b ON b.sha256 = sb.block_sha256 + WHERE sb.session_id = s.id), 0) + WHERE s.owner_did = $1 AND s.state = 'open'", + ) + .bind(owner_did) + .execute(&mut **tx) + .await?; + Ok(()) + } + + // ── verification ─────────────────────────────────────────────────────── + + pub async fn model_mark_published(&self, release_id: i64) -> Result<()> { + sqlx::query( + "UPDATE model_releases + SET state = 'published', published_at = $2 + WHERE id = $1 AND state = 'verifying'", + ) + .bind(release_id) + .bind(ts_now()) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Reject: mark the release, drop its refs, and refund the publisher the + /// bytes no other live release still references. + pub async fn model_reject_release(&self, release_id: i64, reason: &str) -> Result<()> { + let mut tx = self.pool.begin().await?; + let released: Option<(String,)> = sqlx::query_as( + "UPDATE model_releases + SET state = 'rejected', failure_reason = $2 + WHERE id = $1 AND state = 'verifying' + RETURNING publisher_did", + ) + .bind(release_id) + .bind(reason) + .fetch_optional(&mut *tx) + .await?; + let Some((publisher,)) = released else { + tx.commit().await?; + return Ok(()); + }; + let freed: i64 = sqlx::query_scalar::<_, Option>( + "SELECT COALESCE(SUM(b.size), 0) FROM model_blocks b + JOIN model_release_blocks rb ON rb.block_sha256 = b.sha256 + WHERE rb.release_id = $1 + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks r2 + JOIN model_releases r ON r.id = r2.release_id + WHERE r2.block_sha256 = b.sha256 AND r2.release_id <> $1 + AND r.state IN ('verifying', 'published'))", + ) + .bind(release_id) + .fetch_one(&mut *tx) + .await? + .unwrap_or(0); + sqlx::query("DELETE FROM model_release_blocks WHERE release_id = $1") + .bind(release_id) + .execute(&mut *tx) + .await?; + if freed > 0 { + sqlx::query( + "UPDATE model_quota_usage SET bytes_used = GREATEST(bytes_used - $2, 0) + WHERE did = $1", + ) + .bind(&publisher) + .bind(freed) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(()) + } + + pub async fn model_verifying_ids(&self, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases WHERE state = 'verifying' + ORDER BY created_at LIMIT $1", + ) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + // ── sweep ────────────────────────────────────────────────────────────── + + pub async fn model_expire_sessions(&self) -> Result> { + Ok(sqlx::query_scalar( + "UPDATE model_upload_sessions SET state = 'expired' + WHERE state = 'open' AND expires_at <= $1 + RETURNING id", + ) + .bind(ts_now()) + .fetch_all(&self.pool) + .await?) + } + + pub async fn model_drop_session_blocks(&self, session_id: &str) -> Result<()> { + sqlx::query("DELETE FROM model_session_blocks WHERE session_id = $1") + .bind(session_id) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Stamp `unreferenced_since` on blocks that lost every live reference, + /// and clear it on blocks that regained one. Returns rows marked. + pub async fn model_remark_liveness(&self) -> Result { + let marked = sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = $1 + WHERE b.unreferenced_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open')", + ) + .bind(ts_now()) + .execute(&self.pool) + .await? + .rows_affected(); + sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = NULL + WHERE b.unreferenced_since IS NOT NULL + AND (EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + OR EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open'))", + ) + .execute(&self.pool) + .await?; + Ok(marked) + } + + pub async fn model_stale_blocks(&self, grace_secs: i64, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sha256 FROM model_blocks + WHERE unreferenced_since < $1 + LIMIT $2", + ) + .bind(ts_from_now(-grace_secs)) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + /// Under the same row lock the claim path takes, confirm the block is + /// still unreferenced. The caller keeps the transaction open across the + /// store delete, then calls `model_tx_delete_block_row`. + pub async fn model_tx_block_still_dead( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + ) -> Result { + Ok(sqlx::query_scalar::<_, bool>( + "SELECT NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = $1 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = $1 AND s.state = 'open') + FROM model_blocks b + WHERE b.sha256 = $1 FOR UPDATE", + ) + .bind(sha) + .fetch_optional(&mut **tx) + .await? + .unwrap_or(false)) + } + + pub async fn model_tx_delete_block_row( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + ) -> Result<()> { + sqlx::query("DELETE FROM model_blocks WHERE sha256 = $1") + .bind(sha) + .execute(&mut **tx) + .await?; + Ok(()) + } +} + +/// The PgPool behind a `Db`, for test fixtures that seed rows directly. +#[cfg(any(test, feature = "test-harness"))] +pub fn test_pool(db: &Db) -> &PgPool { + db.pool() +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn migrated(pool: sqlx::PgPool) -> Db { + let db = Db::for_testing(pool.clone()); + db.run_migrations().await.unwrap(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r1', 'repo', 'did:owner', TRUE, 'main', 't', 't', '/r1')", + ) + .execute(&pool) + .await + .unwrap(); + db + } + + #[sqlx::test] + async fn admit_bytes_enforces_session_cap_and_slides_expiry(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let first = db + .model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); + assert_eq!(first.bytes_received, 100); + assert!(first.expires_at > s.expires_at || first.expires_at == s.expires_at); + // Over the per-identity session cap: refused. + assert!(db + .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) + .await + .unwrap() + .is_none()); + // Within the cap still admits. + assert!(db + .model_admit_bytes(&s.id, 900, 3600, 1000, 10_000) + .await + .unwrap() + .is_some()); + } + + #[sqlx::test] + async fn record_block_refunds_duplicate_within_session(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "a".repeat(64); + assert!(!db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + // Same block again: duplicate, admission refunded. + assert!(db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + let s2 = db.model_load_session(&s.id).await.unwrap().unwrap(); + assert_eq!(s2.bytes_received, 0); + } + + #[sqlx::test] + async fn expire_then_sweep_marks_and_deletes_dead_blocks(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "b".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + // Blocks are born stamped; while the session is open, remarking + // clears the stamp. + db.model_remark_liveness().await.unwrap(); + let stamp: Option = + sqlx::query_scalar("SELECT unreferenced_since FROM model_blocks WHERE sha256 = $1") + .bind(&sha) + .fetch_one(&pool) + .await + .unwrap(); + assert!(stamp.is_none()); + + // Force the session expired and drop its links. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_expire_sessions().await.unwrap(), + vec![s.id.clone()] + ); + db.model_drop_session_blocks(&s.id).await.unwrap(); + + // The block is now unreferenced: marked, then deletable past grace. + assert_eq!(db.model_remark_liveness().await.unwrap(), 1); + sqlx::query("UPDATE model_blocks SET unreferenced_since = $1 WHERE sha256 = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_stale_blocks(3600, 10).await.unwrap(), + vec![sha.clone()] + ); + let mut tx = db.model_begin().await.unwrap(); + assert!(db.model_tx_block_still_dead(&mut tx, &sha).await.unwrap()); + db.model_tx_delete_block_row(&mut tx, &sha).await.unwrap(); + tx.commit().await.unwrap(); + } + + #[sqlx::test] + async fn release_blocks_keep_a_block_alive(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "c".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 5, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1','c1','main','did:owner','published','m','s','i','ss','\\x00','t') + RETURNING id", + ) + .execute(&pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar("SELECT id FROM model_releases WHERE repo_id = 'r1'") + .fetch_one(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1,$2)") + .bind(rid) + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + // Live release reference: the block never goes stale. + assert_eq!(db.model_remark_liveness().await.unwrap(), 0); + assert!(db.model_stale_blocks(-1, 10).await.unwrap().is_empty()); + let mut tx = db.model_begin().await.unwrap(); + assert!(!db.model_tx_block_still_dead(&mut tx, &sha).await.unwrap()); + tx.commit().await.unwrap(); + } +} diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index bfedeb72..e330c0c1 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -348,7 +348,7 @@ pub async fn delete_marker_bounded( /// serving) or a live push's admission permits, lease, and write lock. /// `kill_on_drop(true)` makes the timeout real for these plumbing commands /// (no helper processes to reparent, unlike receive-pack's pack-objects). -async fn run_git_bounded( +pub(crate) async fn run_git_bounded( git_bin: &str, repo_path: &Path, args: &[&str], diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index d068d669..881632ec 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -22,6 +22,7 @@ mod graphql; mod icaptcha; mod ipfs_pin; mod metrics; +pub mod models; mod operator; mod p2p; mod pinata; @@ -914,6 +915,16 @@ pub async fn run() -> Result<()> { // with the one-shot reconcile/drain on backlog rows. let _due_request_worker = spawn_due_request_worker(&state); + // Model hosting workers (verify + sweep) only run while the operator + // flag is on; the block store is the flag's live form. + let mut model_workers = Vec::new(); + if state.block_store.is_some() { + model_workers.push(tokio::spawn(models::verify::run_verify_worker( + state.clone(), + ))); + model_workers.push(tokio::spawn(models::sweep::run_sweep_worker(state.clone()))); + } + // `into_make_service_with_connect_info` exposes the socket peer address as // `ConnectInfo` so the push limiter can key on the real client // when no trusted proxy header applies (see `rate_limit::client_key`). diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs new file mode 100644 index 00000000..5d92cca8 --- /dev/null +++ b/crates/twigpine-node/src/models/claim.rs @@ -0,0 +1,272 @@ +//! Release claim: the commit point. The ordered checks from KTD5 run here; +//! the check-then-act tail (other-verifying probe, quota reservation, release +//! insert) runs inside one transaction under the claim advisory lock. + +use twigpine_core::model::manifest::Manifest; + +use crate::db::model_queries::ClaimPersist; +use crate::db::RepoRecord; +use crate::error::AppError; +use crate::state::AppState; + +use super::{ReleaseRow, CLAIM_LOCK_KEY}; + +/// Everything the handler verified about the signed request, threaded so the +/// release row is the replay ledger: a replayed claim resolves by request +/// digest to the original row instead of writing a second one. +pub struct ClaimMaterial { + pub request_digest: String, + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, +} + +fn bad_request(msg: impl Into) -> AppError { + AppError::BadRequest(msg.into()) +} + +/// Read `commit:path` bytes from the repo on disk, bounded. +pub(crate) async fn git_show( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + path: &str, +) -> Result>, AppError> { + let spec = format!("{commit}:{path}"); + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["show", &spec], + b"", + std::time::Duration::from_secs(30), + "git show", + ) + .await + .map_err(AppError::Internal)?; + if out.status.success() { + return Ok(Some(out.stdout)); + } + match out.status.code() { + // Path missing inside a real commit: honest absence. + Some(128) => Ok(None), + _ => Err(AppError::Internal(anyhow::anyhow!( + "git show {spec} failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))), + } +} + +/// Whether commit `sha` resolves in the repo. +pub async fn commit_exists( + git_bin: &str, + disk_path: &std::path::Path, + sha: &str, +) -> Result { + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["cat-file", "-e", &format!("{sha}^{{commit}}")], + b"", + std::time::Duration::from_secs(30), + "git cat-file", + ) + .await + .map_err(AppError::Internal)?; + Ok(out.status.success()) +} + +/// Read and anchor-verify the release manifest at `commit`. The verifying key +/// comes from the repo owner DID (the independent anchor), never the artifact. +pub(crate) async fn read_verified_manifest( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + owner_did: &str, +) -> Result<(Vec, Manifest), AppError> { + let manifest_bytes = git_show(git_bin, disk_path, commit, ".twigpine/model-release.json") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.json"))?; + let sig_text = git_show(git_bin, disk_path, commit, ".twigpine/model-release.sig") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; + let sig_text = + String::from_utf8(sig_text).map_err(|_| bad_request("model-release.sig is not utf-8"))?; + let did: twigpine_core::did::Did = owner_did + .parse() + .map_err(|_| bad_request("repo owner DID does not resolve"))?; + let manifest = twigpine_core::model::manifest::verify(&manifest_bytes, &sig_text, &did) + .map_err(|e| bad_request(format!("manifest signature rejected: {e}")))?; + Ok((manifest_bytes, manifest)) +} + +/// Claim `commit` on `branch` as a model release. The handler has already +/// proven the feature flag, the owner gate, and full publicity; everything +/// from the manifest read down runs here. +pub async fn claim_release( + state: &AppState, + record: &RepoRecord, + caller: &str, + commit: &str, + branch: &str, + material: &ClaimMaterial, +) -> Result { + let db = &state.db; + let disk_path = std::path::PathBuf::from(&record.disk_path); + + // The pushed commit must exist and carry the signed manifest. + if !commit_exists(&state.git_bin, &disk_path, commit).await? { + return Err(bad_request("commit not found in this repository")); + } + let (manifest_bytes, manifest) = + read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; + let m_sha = super::manifest_sha256(&manifest_bytes); + let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); + let blocks = super::referenced_blocks(state, &manifest).await?; + + let mut tx = db.model_begin().await?; + db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; + + // Replay by request digest, then idempotent re-claim by (repo, commit): + // both return the original row. + if let Some(existing) = db + .model_tx_release_by_digest(&mut tx, &material.request_digest) + .await? + { + tx.commit().await?; + return Ok(existing); + } + if let Some(existing) = db + .model_tx_release_by_commit(&mut tx, &record.id, commit) + .await? + { + tx.commit().await?; + return Ok(existing); + } + + // Lock the referenced block rows so a racing sweep cannot delete one + // mid-claim, and require each to exist. + if !blocks.is_empty() { + let present = db.model_tx_lock_present_blocks(&mut tx, &blocks).await?; + if let Some(missing) = blocks.iter().find(|b| !present.contains(b)) { + return Err(bad_request(format!( + "manifest references block {} which is not stored on this node", + &missing[..16] + ))); + } + } + + // Authorization: every referenced block must arrive through the caller's + // open session, a live release of the caller's, or the declared parent. + let caller_session_blocks = db.model_tx_session_blocks(&mut tx, caller).await?; + let caller_release_blocks = db + .model_tx_publisher_release_blocks(&mut tx, caller) + .await?; + let parent_blocks: Vec = match &manifest.parent { + None => Vec::new(), + Some(parent) => { + let (powner, pname) = parent + .repo + .split_once('/') + .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; + // A parent only confers blocks while its repo is fully public: + // a withdrawn parent cannot launder references. + let (precord, prules) = + crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; + if !precord.is_public || !prules.is_empty() { + return Err(bad_request( + "declared parent's repo is no longer fully public", + )); + } + let rows = db + .model_tx_release_blocks_at_commit(&mut tx, &precord.id, &parent.commit) + .await?; + if rows.is_empty() { + return Err(bad_request( + "declared parent is not a published release on this node", + )); + } + rows + } + }; + for b in &blocks { + let allowed = caller_session_blocks.contains(b) + || caller_release_blocks.contains(b) + || parent_blocks.contains(b); + if !allowed { + return Err(bad_request(format!( + "block {} is not reachable through an open session, a prior \ + release, or the declared parent", + &b[..16] + ))); + } + } + + // One verifying release per publisher. + if db.model_tx_has_verifying(&mut tx, caller).await? { + return Err(AppError::Conflict( + "another release is still verifying; wait for it to settle".into(), + )); + } + + // New bytes are the distinct blocks not already claimed by any live + // release anywhere: first claimer pays, dedup stays free. + let new_bytes = db.model_tx_unclaimed_bytes(&mut tx, &blocks).await?; + + // Per-identity quota, atomically. + let did_cap = state.config.model_quota_bytes as i64; + let admitted = db + .model_tx_reserve_quota(&mut tx, caller, new_bytes, did_cap) + .await?; + if new_bytes > 0 && admitted.is_none() { + return Err(bad_request(format!( + "per-publisher model quota ({did_cap} bytes) would be exceeded" + ))); + } + + // Node-wide quota in the same transaction: claimed bytes plus open + // session bytes. + let node_cap = state.config.model_node_quota_bytes as i64; + let node_total = db.model_tx_node_used(&mut tx).await?; + if node_total > node_cap { + return Err(AppError::TooManyRequests(format!( + "node model storage cap ({node_cap} bytes) would be exceeded" + ))); + } + + let persist = ClaimPersist { + signature: material.signature.clone(), + signature_input: material.signature_input.clone(), + signing_string: material.signing_string.clone(), + body: material.body.clone(), + request_digest: material.request_digest.clone(), + }; + let row = db + .model_tx_insert_release( + &mut tx, + &record.id, + commit, + branch, + caller, + &m_sha, + rec_sha.as_deref(), + &persist, + ) + .await?; + let release_id = row.id; + + for b in &blocks { + // Claimed blocks leave the caller's open sessions' charge: the + // release now carries them, so session bytes stop double-counting. + db.model_tx_link_release_block(&mut tx, release_id, caller, b) + .await?; + } + db.model_tx_recount_open_session_bytes(&mut tx, caller) + .await?; + + tx.commit().await?; + Ok(row) +} diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs new file mode 100644 index 00000000..ee45d2b5 --- /dev/null +++ b/crates/twigpine-node/src/models/mod.rs @@ -0,0 +1,173 @@ +//! Open-weight model hosting: upload sessions, release claims, verification, +//! and reclamation. Feature-gated by `model_hosting_enabled`; the routes are +//! mounted only when `state.block_store` is `Some`, and every handler +//! re-checks it. +//! +//! All SQL lives in `crate::db::model_queries` as typed `Db` methods; the +//! free functions here are the thin `&Db`-taking seams the handlers and +//! workers share. + +pub mod claim; +pub mod sweep; +pub mod verify; + +use std::sync::Arc; + +use crate::db::model_queries::{ModelRelease, ModelSession}; +use crate::db::Db; +use crate::error::AppError; +use crate::state::AppState; + +/// Transport + store hard cap on one block (KTD1: 64 MiB target, 128 MiB cap). +pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; + +/// Advisory-lock key serializing claim admission: the "one verifying release +/// per publisher" check and the quota reservations are check-then-act, so the +/// lock is what makes them safe under racing claims. +pub(crate) const CLAIM_LOCK_KEY: i64 = 0x6D6F64656C636C61; // "modelcla" + +pub type SessionRow = ModelSession; +pub type ReleaseRow = ModelRelease; + +/// rfc3339 UTC `secs` from now: the repo's TEXT timestamp convention. +pub fn ts_from_now(secs: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() +} + +pub fn ts_now() -> String { + chrono::Utc::now().to_rfc3339() +} + +/// 256-bit random session id, hex-encoded: the bearer capability for block +/// PUTs. Anyone holding it may append blocks to the session it names, so it +/// is never logged or returned to anyone but its creator. +pub fn new_session_id() -> String { + hex::encode(rand::random::<[u8; 32]>()) +} + +pub async fn open_session( + db: &Db, + owner_did: &str, + repo_id: &str, + ttl_secs: u64, +) -> Result { + Ok(db.model_open_session(owner_did, repo_id, ttl_secs).await?) +} + +pub async fn load_session(db: &Db, id: &str) -> Result, AppError> { + Ok(db.model_load_session(id).await?) +} + +/// Atomically admit `claimed` bytes against the caller's per-identity +/// open-session cap and the node-wide quota (claimed quota plus every open +/// session's bytes), sliding the session's expiry forward in the same +/// update. Returns the post-update row when admitted, `None` when the +/// session is closed, expired, or the admission would exceed a cap; the +/// caller re-checks the session to pick the honest denial. +pub async fn admit_bytes( + db: &Db, + session_id: &str, + claimed: i64, + ttl_secs: u64, + session_cap: i64, + node_cap: i64, +) -> Result, AppError> { + Ok(db + .model_admit_bytes(session_id, claimed, ttl_secs, session_cap, node_cap) + .await?) +} + +/// Refund a previously admitted charge when the store or the bookkeeping +/// fails. Best-effort under races; an expired session frees the bytes anyway. +pub async fn refund_bytes(db: &Db, session_id: &str, bytes: i64) -> Result<(), AppError> { + db.model_refund_bytes(session_id, bytes).await?; + Ok(()) +} + +/// Book the stored block against the session inside one transaction. Returns +/// `true` when this PUT was a duplicate within the session (the admission +/// credit was refunded). +pub async fn record_block( + db: &Db, + session_id: &str, + block_sha: &str, + size: u64, + admitted: i64, +) -> Result { + Ok(db + .model_record_block(session_id, block_sha, size, admitted) + .await?) +} + +pub async fn release_by_commit( + db: &Db, + repo_id: &str, + commit: &str, +) -> Result, AppError> { + Ok(db.model_release_by_commit(repo_id, commit).await?) +} + +pub async fn release_by_id(db: &Db, id: i64) -> Result, AppError> { + Ok(db.model_release_by_id(id).await?) +} + +/// sha256 of the manifest bytes, as hex. +pub fn manifest_sha256(manifest_bytes: &[u8]) -> String { + use sha2::Digest; + hex::encode(sha2::Sha256::digest(manifest_bytes)) +} + +/// Collect `len` bytes of a stored object starting at `start`. +pub async fn read_range( + store: &Arc, + sha: &str, + start: u64, + len: u64, +) -> Result, crate::blockstore::BlockStoreError> { + use futures::StreamExt; + let id = crate::blockstore::BlockId::parse(sha) + .map_err(|e| crate::blockstore::BlockStoreError::Backend(e.to_string()))?; + let mut stream = store.get_range(&id, start, start + len).await?; + let mut out = Vec::with_capacity(len.min(1 << 22) as usize); + while let Some(chunk) = stream.next().await { + out.extend_from_slice(&chunk?); + } + Ok(out) +} + +/// Collect a stored object's whole body via a range read. +pub async fn read_block( + store: &Arc, + sha: &str, + size: u64, +) -> Result, crate::blockstore::BlockStoreError> { + read_range(store, sha, 0, size).await +} + +/// The set of blocks a manifest references: the reconstruction object itself +/// (stored as its own content block) plus every data block the parsed +/// reconstruction names. The reconstruction object is read from the block +/// store and validated before its block table is trusted. +pub async fn referenced_blocks( + state: &AppState, + manifest: &twigpine_core::model::manifest::Manifest, +) -> Result, AppError> { + use twigpine_core::model::reconstruction::Reconstruction; + let Some(rec_ref) = &manifest.reconstruction else { + return Ok(Vec::new()); + }; + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::NotFound("model hosting is not enabled".into()))?; + let bytes = read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|e| AppError::BadRequest(format!("reconstruction object unreadable: {e}")))?; + let rec = Reconstruction::parse(&bytes) + .map_err(|e| AppError::BadRequest(format!("reconstruction object invalid: {e}")))?; + let mut out = vec![rec_ref.sha256.clone()]; + for b in &rec.blocks { + out.push(b.sha256.clone()); + } + Ok(out) +} diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs new file mode 100644 index 00000000..edf12187 --- /dev/null +++ b/crates/twigpine-node/src/models/sweep.rs @@ -0,0 +1,80 @@ +//! Reclamation: expire upload sessions, drop their block links, mark blocks +//! unreferenced, and delete unreferenced blocks after the unclaimed grace +//! period. Blocks referenced by a live release or an open session survive. +//! The claim path locks block rows (`FOR UPDATE`) before referencing them, +//! and the sweep's delete candidate is re-checked inside its own +//! transaction, so a claim in flight can never lose a block mid-reference. + +use crate::error::AppError; +use crate::state::AppState; + +#[derive(Debug, Default)] +pub struct SweepStats { + pub sessions_expired: u64, + pub blocks_marked: u64, + pub blocks_deleted: u64, +} + +/// One sweep pass. Exposed for tests; the worker calls it on a tick. +pub async fn sweep_once(state: &AppState) -> Result { + let db = &state.db; + let mut stats = SweepStats::default(); + + // Expire sessions past TTL, then drop their block links: an expired + // session no longer confers liveness. + let expired = db.model_expire_sessions().await?; + stats.sessions_expired = expired.len() as u64; + for sid in &expired { + db.model_drop_session_blocks(sid).await?; + } + + // Re-mark liveness both ways: blocks that lost every live reference get + // an unreferenced_since stamp; blocks that regained one clear theirs. + stats.blocks_marked = db.model_remark_liveness().await?; + + // Delete blocks past the grace period. The store object goes first so a + // crash leaves a dangling row (an honest "missing" at next claim) rather + // than an untracked object the sweep can never find again. + let grace = state.config.model_unclaimed_ttl_secs as i64; + let stale = db.model_stale_blocks(grace, 128).await?; + let Some(store) = state.block_store.clone() else { + return Ok(stats); + }; + for sha in stale { + // Re-check liveness under the row lock the claim path also takes, + // held across the store delete so a racing claim blocks rather than + // wins a reference to an object we just removed. + let mut tx = db.model_begin().await?; + if !db.model_tx_block_still_dead(&mut tx, &sha).await? { + tx.commit().await?; + continue; + } + let Ok(id) = crate::blockstore::BlockId::parse(&sha) else { + tx.commit().await?; + continue; + }; + match store.delete(&id).await { + Ok(()) | Err(crate::blockstore::BlockStoreError::NotFound) => {} + Err(e) => { + tracing::warn!("block {sha} store delete failed: {e}"); + tx.commit().await?; + continue; + } + } + db.model_tx_delete_block_row(&mut tx, &sha).await?; + tx.commit().await?; + stats.blocks_deleted += 1; + } + Ok(stats) +} + +/// Periodic sweep; spawned once when model hosting is enabled. +pub async fn run_sweep_worker(state: AppState) { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); + loop { + interval.tick().await; + if let Err(e) = sweep_once(&state).await { + tracing::warn!("model sweep failed: {e}"); + } + } +} diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs new file mode 100644 index 00000000..118ecc5a --- /dev/null +++ b/crates/twigpine-node/src/models/verify.rs @@ -0,0 +1,307 @@ +//! Release verification: rebuild every chunk-stored file, hash it against +//! the manifest, check the declared format against detected bytes, and only +//! then mark the release published (and pin the hidden ref). Rejection frees +//! the quota reservation and drops the block refs. + +use sha2::Digest; +use std::io::Write; +use twigpine_core::model::manifest::{detect_format, StorageKind}; +use twigpine_core::model::reconstruction::{rebuild_file, Reconstruction}; + +use crate::error::AppError; +use crate::state::AppState; + +/// Sink hashing rebuilt bytes and keeping the head for format detection. +struct VerifySink { + hasher: sha2::Sha256, + head: Vec, + digest: Option, +} + +impl Write for VerifySink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.hasher.update(buf); + if self.head.len() < 64 { + let take = (64 - self.head.len()).min(buf.len()); + self.head.extend_from_slice(&buf[..take]); + } + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Verify one release end to end. Idempotent: a release no longer in +/// `verifying` returns immediately. +pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), AppError> { + let Some(release) = super::release_by_id(&state.db, release_id).await? else { + return Ok(()); + }; + if release.state != "verifying" { + return Ok(()); + } + + // The repo must still be fully public: a repo turned private or given + // visibility rules mid-verification never publishes. + let record = state + .db + .get_repo_by_id(&release.repo_id) + .await? + .ok_or_else(|| AppError::NotFound("repo gone".into()))?; + let rules = state.db.list_visibility_rules(&record.id).await?; + if !record.is_public || !rules.is_empty() { + return reject_release(state, release_id, "repository is no longer fully public").await; + } + + let disk_path = std::path::PathBuf::from(&record.disk_path); + let (manifest_bytes, manifest) = match super::claim::read_verified_manifest( + &state.git_bin, + &disk_path, + &release.commit_sha, + &record.owner_did, + ) + .await + { + Ok(v) => v, + Err(e) => { + return reject_release(state, release_id, &format!("manifest re-check failed: {e}")) + .await; + } + }; + if super::manifest_sha256(&manifest_bytes) != release.manifest_sha256 { + return reject_release(state, release_id, "manifest digest changed since claim").await; + } + + let Some(rec_ref) = &manifest.reconstruction else { + return reject_release(state, release_id, "manifest has no reconstruction object").await; + }; + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object unreadable: {e}"), + ) + .await; + } + }; + let rec = match Reconstruction::parse(&rec_bytes) { + Ok(r) => r, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object invalid: {e}"), + ) + .await; + } + }; + + for file in &manifest.files { + match file.storage { + StorageKind::Chunked => { + let Some(entry) = rec.files.iter().find(|f| f.path == file.path).cloned() else { + return reject_release( + state, + release_id, + &format!("reconstruction object has no entry for {}", file.path), + ) + .await; + }; + if entry.sha256 != file.sha256 || entry.size != file.size { + return reject_release( + state, + release_id, + &format!("{}: reconstruction disagrees with the manifest", file.path), + ) + .await; + } + // The rebuild runs on the blocking pool: `rebuild_file` is a + // sync walker over a range-fetch callback, and the store is + // async. block_on inside spawn_blocking is honest — the + // fetch itself is chunk-sized and bounded. + let store2 = store.clone(); + let rec2 = rec.clone(); + let path = file.path.clone(); + let declared = file.format; + let built = tokio::task::spawn_blocking(move || { + let mut sink = VerifySink { + hasher: sha2::Sha256::new(), + head: Vec::new(), + digest: None, + }; + let mut fetch = |block: &str, off: u64, len: u64| -> std::io::Result> { + let store3 = store2.clone(); + let block = block.to_string(); + futures::executor::block_on(async move { + super::read_range(&store3, &block, off, len).await + }) + .map_err(|e| std::io::Error::other(e.to_string())) + }; + rebuild_file(&entry, &rec2, &mut fetch, &mut sink)?; + sink.digest = Some(hex::encode(sink.hasher.clone().finalize())); + Ok::<_, twigpine_core::model::reconstruction::ModelError>(( + sink, path, declared, + )) + }) + .await; + let (sink, path, declared) = match built { + Ok(Ok(v)) => v, + Ok(Err(e)) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + Err(e) => return Err(AppError::Internal(e.into())), + }; + if sink.digest.as_deref() != Some(file.sha256.as_str()) { + return reject_release( + state, + release_id, + &format!( + "{}: rebuilt bytes hash to {}", + path, + sink.digest.unwrap_or_default() + ), + ) + .await; + } + let detected = detect_format(&sink.head, &path); + if detected != declared { + return reject_release( + state, + release_id, + &format!( + "{path}: declared format {declared:?} but bytes detect as {detected:?}" + ), + ) + .await; + } + } + StorageKind::Git => { + match super::claim::git_show( + &state.git_bin, + &disk_path, + &release.commit_sha, + &file.path, + ) + .await + { + Ok(Some(bytes)) => { + let got = hex::encode(sha2::Sha256::digest(&bytes)); + if got != file.sha256 || bytes.len() as u64 != file.size { + return reject_release( + state, + release_id, + &format!("{}: git blob does not match the manifest", file.path), + ) + .await; + } + let detected = detect_format(&bytes[..bytes.len().min(64)], &file.path); + if detected != file.format { + return reject_release( + state, + release_id, + &format!( + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected + ), + ) + .await; + } + } + Ok(None) => { + return reject_release( + state, + release_id, + &format!("{}: not present in the claimed commit", file.path), + ) + .await; + } + Err(e) => return Err(e), + } + } + } + } + + // Publish: hidden ref first, then the state flip, so a crash leaves a + // verifying row the worker retries rather than a dangling ref. + write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; + state.db.model_mark_published(release_id).await?; + Ok(()) +} + +/// `refs/gitlawb/releases/` -> the release commit itself: reachable, +/// so `gc` never prunes it, and hidden under the gitlawb ref namespace. +pub async fn write_release_ref( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, +) -> Result<(), AppError> { + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &[ + "update-ref", + &format!("refs/gitlawb/releases/{commit}"), + commit, + ], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await + .map_err(AppError::Internal)?; + if !out.status.success() { + return Err(AppError::Internal(anyhow::anyhow!( + "git update-ref failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))); + } + Ok(()) +} + +/// Reject a release: drop its block refs, release the quota it reserved for +/// blocks no other live release still references, and record the reason. +pub async fn reject_release( + state: &AppState, + release_id: i64, + reason: &str, +) -> Result<(), AppError> { + state.db.model_reject_release(release_id, reason).await?; + tracing::info!(release_id, %reason, "model release rejected"); + Ok(()) +} + +/// Poll for `verifying` releases and verify them in order. Spawned once per +/// node when model hosting is enabled. +pub async fn run_verify_worker(state: AppState) { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); + loop { + interval.tick().await; + let ids = match state.db.model_verifying_ids(4).await { + Ok(v) => v, + Err(e) => { + tracing::warn!("model verify worker query failed: {e}"); + continue; + } + }; + for id in ids { + if let Err(e) = verify_release(&state, id).await { + tracing::warn!("model release {id} verification errored: {e}"); + } + } + } +} diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 64c6f56a..e8f66d33 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -14,8 +14,9 @@ use tower_http::trace::{DefaultOnFailure, DefaultOnResponse, TraceLayer}; use tracing::Level; use crate::api::{ - agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, peers, profiles, - protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, webhooks, + agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, models, peers, + profiles, protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, + webhooks, }; use crate::auth; use crate::rate_limit; @@ -762,6 +763,72 @@ pub fn build_router(state: AppState) -> Router { auth::optional_signature, )); + // ── Model hosting routes ───────────────────────────────────────────── + // Mounted only when the operator enabled the feature (`block_store` is + // the flag's live form). Three surfaces with three different auth + // shapes: + // - session open + session status: signed, owner-only. + // - claims: signed, persists the request material and owns its replay + // defense exactly like status claims. + // - block PUT: unsigned by design — the session id is the bearer + // credential and a signed 128 MiB body would have to be buffered + // whole to verify. Default body limit off, explicit block cap, same + // per-IP write brake as the other write surfaces. + let model_routes = if state.block_store.is_some() { + let signed = add_auth_layers( + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions", + post(models::open_model_session), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + get(models::get_model_session), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .write_braked(&write_ip_limiter); + let claims = add_auth_layers( + Router::new().route( + "/api/v1/repos/{owner}/{repo}/models/claims", + post(models::claim_model_release), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .layer(RequestBodyLimitLayer::new(status::MAX_REQUEST_BODY_BYTES)) + .layer(axum::Extension(auth::PersistsSignedBody)) + .layer(axum::Extension(auth::OwnsReplayDefense)) + .write_braked(&write_ip_limiter); + let blocks = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}", + axum::routing::put(models::put_model_block), + ) + .layer(DefaultBodyLimit::disable()) + .layer(RequestBodyLimitLayer::new( + crate::models::MAX_BLOCK_BYTES as usize, + )) + .write_braked(&write_ip_limiter); + let reads = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + get(models::get_model_release), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}/reconstruction", + get(models::get_model_reconstruction), + ) + .layer(middleware::from_fn_with_state( + auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), + auth::optional_signature, + )); + signed.merge(claims).merge(blocks).merge(reads) + } else { + Router::new() + }; + // ── Meta ────────────────────────────────────────────────────────────── let meta_routes = Router::new() .route("/", get(node_info)) @@ -791,6 +858,7 @@ pub fn build_router(state: AppState) -> Router { .merge(sync_trigger_routes) .merge(ipfs_routes) .merge(arweave_routes) + .merge(model_routes) .merge(meta_routes) .layer( TraceLayer::new_for_http() diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 21ec3d8d..9032eca0 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -176,6 +176,15 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS task_tx.clone(), task_cursor_key.clone(), )); + // Model hosting is ON for the harness node: a filesystem block store in a + // temp dir mounts the model routes so the deny sweep can drive their + // gates for real. Writes land inside the node's per-test repos dir and + // are removed with it. + let block_dir = repos_dir.join("model-blocks"); + std::fs::create_dir_all(&block_dir).expect("create temp block dir"); + let block_store: Option> = Some(Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir).expect("fs block store"), + )); AppState { config: Arc::new(Config::parse_from(["twigpine-node"])), db, @@ -228,7 +237,7 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS 16, ), git_bin: "git".to_string(), - block_store: None, + block_store, } } @@ -371,9 +380,50 @@ impl TestNode { record.id } + /// Seed a published model release row directly, bypassing the claim + /// pipeline: deny fixtures need a real row behind the read gate, not the + /// full upload-and-verify path. + pub async fn seed_model_release(&self, repo_id: &str, commit_sha: &str, publisher_did: &str) { + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ($1,$2,'main',$3,'published',$4,'sig','input','signing',\ + decode('00','hex'),$5)", + ) + .bind(repo_id) + .bind(commit_sha) + .bind(publisher_did) + .bind(format!("{commit_sha:0>64}")) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model release"); + } + + /// Seed an open model upload session row directly (see + /// [`Self::seed_model_release`]): the session-status read row's owner + /// twin needs a real session behind the gate. + pub async fn seed_model_session(&self, repo_id: &str, session_id: &str, owner_did: &str) { + sqlx::query( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1,$2,$3,$4,$5,0,'open')", + ) + .bind(session_id) + .bind(owner_did) + .bind(repo_id) + .bind(chrono::Utc::now().to_rfc3339()) + .bind((chrono::Utc::now() + chrono::Duration::hours(12)).to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model session"); + } + /// Mark `branch` as protected on `repo_id`, so a non-owner push to it is /// rejected by the branch-protection gate (used by the deny-prober's - /// protected-push probe — #195, F3). + /// protected-push probe, #195 F3). pub async fn seed_protected_branch(&self, repo_id: &str, branch: &str, created_by: &str) { self.db .protect_branch(repo_id, branch, created_by) diff --git a/crates/twigpine-node/tests/deny_harness.rs b/crates/twigpine-node/tests/deny_harness.rs index 26b0c0d7..76acf4cb 100644 --- a/crates/twigpine-node/tests/deny_harness.rs +++ b/crates/twigpine-node/tests/deny_harness.rs @@ -1429,6 +1429,24 @@ mod completeness { ("git_upload_pack", NotDrivenReason::GitSmartHttpRead), // Global list-FILTER: 200 with unreadable rows removed, never a 404. ("list_all_bounties", NotDrivenReason::GlobalListFilter), + // Model hosting writes: the session open, claim, and unsigned block + // PUT all read-gate the repo before their own credential checks. None + // is a 404-deny GET; the owner-gate rows drive the signed writes, and + // the bearer-session PUT's denies are covered by the models unit + // tests (a session row cannot be seeded through the public API for + // the stranger leg). + ("open_model_session", NotDrivenReason::ReadGatingMutation), + ("claim_model_release", NotDrivenReason::ReadGatingMutation), + ("put_model_block", NotDrivenReason::ReadGatingMutation), + // get_model_reconstruction's owner-2xx twin needs a completed claim: + // a signed manifest commit in git plus a real reconstruction object + // in the block store, substrate the fixture cannot seed through the + // public API. Its hostile 404 is still what a caller sees; only the + // twin lacks a drivable 2xx. + ( + "get_model_reconstruction", + NotDrivenReason::ExternalDependencyUnavailable, + ), ]; /// Every `.route("", ()…)` mount in `src`, as diff --git a/crates/twigpine-node/tests/support/probe.rs b/crates/twigpine-node/tests/support/probe.rs index 9e27520d..a7fdbbca 100644 --- a/crates/twigpine-node/tests/support/probe.rs +++ b/crates/twigpine-node/tests/support/probe.rs @@ -256,6 +256,21 @@ impl Fixture { let priv_bounty_id = seed_private_bounty(node, &owner, &owner_did, priv_repo, &bounty_marker).await; + // Model hosting is mounted on the harness node (an fs block store in + // the per-test repos dir). The model-release read row fills `{sha}` + // with 40 a's, so seed that commit as a published release on the + // private repo: anon/stranger get the existence-hiding 404, the owner + // twin gets a 200 proving the gate. + node.seed_model_release( + &private_repo_id, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + &owner_did, + ) + .await; + // The session-status read row fills `{id}` with the fixed "1". + node.seed_model_session(&private_repo_id, "1", &owner_did) + .await; + let priv_markers = vec![issue_marker, pr_marker, pr_diff_marker, bounty_marker]; // #195 (F3): seed the caller-self task entities through the real task write diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 61ddf428..07f8c411 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -1030,6 +1030,84 @@ pub fn deny_bearing_routes() -> &'static [Row] { id_source: IdSource::FailableTaskId, anon_read: AnonRead::Deny404, }, + // ── Model hosting (U5/U6). Session open and release claim are signed + // owner-gated writes behind the shared read gate; the session-status + // GET is doubly gated like list_webhooks (OwnerGate + ReadGate rows). + // The unsigned block PUT's bearer session is its credential, and the + // release/reconstruction reads are plain read-gated 404-deny GETs. + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/sessions", + gate: GateClass::OwnerGate, + handler: "models::open_model_session", + // Option> accepts an empty object; the owner + // twin then creates a session (201, Not403). + body: Some(r#"{}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/claims", + gate: GateClass::OwnerGate, + handler: "models::claim_model_release", + // A well-formed claim body; the owner twin passes the owner gate and + // fails the commit lookup (400), which is still a Not403 twin. + body: Some(r#"{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","branch":"main"}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Session status: a signed stranger on the PUBLIC repo passes the read + // gate and hits require_repo_owner (403); the owner gets a 404 on the + // absent session (Not403). The read layer is the ReadGate row below. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::OwnerGate, + handler: "models::get_model_session", + body: None, + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Same path, READ layer: anon gets 401 (the route requires a signature), + // a signed non-reader of the private repo gets the existence-hiding 404, + // and the owner reads the session the fixture seeded as id "1". + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::ReadGate, + handler: "models::get_model_session", + body: None, + needs: &["model_session"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny401, + }, + // Release status: optional-signature read. The fixture seeds a published + // release on the private repo under commit 40 a's (the {sha} fill), so + // anon/stranger get the existence-hiding 404 and the owner gets a 200. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + gate: GateClass::ReadGate, + handler: "models::get_model_release", + body: None, + needs: &["model_release"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, // The read-gate handlers NOT driven here (deferred GET reads, read-gating // mutations, git smart-HTTP reads, the content-addressed read, and the // global list-filters) are no longer tracked by free-text prose: they are From 440a7cffce5d6d3efa08bfa4ac9cb04711df4544 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:33:26 -0600 Subject: [PATCH 02/20] fix(node): cap the first claim's quota reservation too 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. --- crates/twigpine-node/src/db/model_queries.rs | 47 +++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 9a5a1eb6..c49311c2 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -423,7 +423,9 @@ impl Db { } /// Atomic per-identity reservation; `None` when the cap would be - /// exceeded. + /// exceeded. The cap applies on BOTH branches: a `WHERE` inside `DO + /// UPDATE` alone would let a first-time DID insert any `delta`, since + /// that clause never guards the insert attempt. pub async fn model_tx_reserve_quota( &self, tx: &mut Transaction<'_, Postgres>, @@ -432,7 +434,8 @@ impl Db { cap: i64, ) -> Result> { Ok(sqlx::query_scalar::<_, i64>( - "INSERT INTO model_quota_usage (did, bytes_used) VALUES ($1, $2) + "INSERT INTO model_quota_usage (did, bytes_used) + SELECT $1, $2 WHERE $2 <= $3 ON CONFLICT (did) DO UPDATE SET bytes_used = model_quota_usage.bytes_used + $2 WHERE model_quota_usage.bytes_used + $2 <= $3 @@ -848,6 +851,46 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn reserve_quota_caps_first_and_later_claims(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // First claim over cap: refused, and no row may be left behind. + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 2000, 1000) + .await + .unwrap() + .is_none()); + tx.commit().await.unwrap(); + let row: Option = sqlx::query_scalar( + "SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'", + ) + .fetch_optional(&pool) + .await + .unwrap(); + assert!(row.is_none()); + // Within cap inserts, over-cap update refuses, within-cap update adds. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 600, 1000) + .await + .unwrap(), + Some(600) + ); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 500, 1000) + .await + .unwrap() + .is_none()); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 400, 1000) + .await + .unwrap(), + Some(1000) + ); + tx.commit().await.unwrap(); + } + #[sqlx::test] async fn release_blocks_keep_a_block_alive(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; From 20fb3c3cb09e797ce6bfbe73264126d84763e8aa Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:34:12 -0600 Subject: [PATCH 03/20] fix(node): hide release refs from clone advertisement Published model releases pin their commits under refs/gitlawb/releases/; advertise them like the requests namespace and every clone fetches internal bookkeeping. --- crates/twigpine-node/src/git/store.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index e330c0c1..52da7912 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -91,10 +91,14 @@ pub fn init_bare(path: &Path) -> Result<()> { // Hide the internal marker namespace from clone/fetch // advertisement. `refs/gitlawb/requests/*` carries request UUIDs // and would otherwise leak per-push metadata to every client and - // grow advertisement cost with push count. + // grow advertisement cost with push count. `refs/gitlawb/releases/*` + // pins published model releases so gc never prunes them; it is + // likewise not for clients. for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { // allow-unbounded-git: same init-time local `git config` as above. let out = Command::new("git") @@ -129,6 +133,8 @@ pub fn ensure_marker_hidden_checked(repo_path: &Path) -> Result<()> { for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { // allow-unbounded-git: reached only through the #[allow(dead_code)] // ensure_marker_hidden wrapper; the push path runs this config through @@ -215,6 +221,8 @@ pub async fn verify_recovery_prereqs_bounded( for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { let current = run_git(git_bin, repo_path, &["config", "--get-all", key], timeout).await?; let already = String::from_utf8_lossy(¤t.stdout) From b26307583d9e864472dcb55909bb27c3edda7136 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:34:48 -0600 Subject: [PATCH 04/20] fix(node): stop block ingest when a repo leaves full publicity 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. --- crates/twigpine-node/src/api/models.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index e916da1b..c2802ab0 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -136,12 +136,16 @@ pub async fn put_model_block( }; // authorize_repo_read 404s a repo the session owner can no longer read; // the session-to-repo binding check below keeps foreign-session PUTs - // indistinguishable from a missing session. - let (record, _rules) = + // indistinguishable from a missing session. The owner always reads their + // own repo, so the fully-public check is what stops bytes landing on a + // repo that turned private or gained visibility rules mid-upload. + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; if session.repo_id != record.id || session.state != "open" || session.expires_at <= models::ts_now() + || !record.is_public + || !rules.is_empty() { return Err(AppError::NotFound("model upload session not found".into())); } From 4ed781e501aa9a66c5cdbc5a903cd1f3d63e105c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:36:04 -0600 Subject: [PATCH 05/20] style(node): apply rustfmt to the quota test --- crates/twigpine-node/src/db/model_queries.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c49311c2..fe77992e 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -862,12 +862,11 @@ mod tests { .unwrap() .is_none()); tx.commit().await.unwrap(); - let row: Option = sqlx::query_scalar( - "SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'", - ) - .fetch_optional(&pool) - .await - .unwrap(); + let row: Option = + sqlx::query_scalar("SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'") + .fetch_optional(&pool) + .await + .unwrap(); assert!(row.is_none()); // Within cap inserts, over-cap update refuses, within-cap update adds. let mut tx = db.model_begin().await.unwrap(); From e2607f9b57765b1a943b7654ac6bafd91a9ae0b8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:41:19 -0600 Subject: [PATCH 06/20] fix(node): rebuild releases with async range reads 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. --- crates/twigpine-node/src/models/verify.rs | 88 +++++++++++------------ 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 118ecc5a..b26272b8 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -6,7 +6,7 @@ use sha2::Digest; use std::io::Write; use twigpine_core::model::manifest::{detect_format, StorageKind}; -use twigpine_core::model::reconstruction::{rebuild_file, Reconstruction}; +use twigpine_core::model::reconstruction::Reconstruction; use crate::error::AppError; use crate::state::AppState; @@ -15,7 +15,6 @@ use crate::state::AppState; struct VerifySink { hasher: sha2::Sha256, head: Vec, - digest: Option, } impl Write for VerifySink { @@ -122,38 +121,15 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App ) .await; } - // The rebuild runs on the blocking pool: `rebuild_file` is a - // sync walker over a range-fetch callback, and the store is - // async. block_on inside spawn_blocking is honest — the - // fetch itself is chunk-sized and bounded. - let store2 = store.clone(); - let rec2 = rec.clone(); - let path = file.path.clone(); - let declared = file.format; - let built = tokio::task::spawn_blocking(move || { - let mut sink = VerifySink { - hasher: sha2::Sha256::new(), - head: Vec::new(), - digest: None, - }; - let mut fetch = |block: &str, off: u64, len: u64| -> std::io::Result> { - let store3 = store2.clone(); - let block = block.to_string(); - futures::executor::block_on(async move { - super::read_range(&store3, &block, off, len).await - }) - .map_err(|e| std::io::Error::other(e.to_string())) - }; - rebuild_file(&entry, &rec2, &mut fetch, &mut sink)?; - sink.digest = Some(hex::encode(sink.hasher.clone().finalize())); - Ok::<_, twigpine_core::model::reconstruction::ModelError>(( - sink, path, declared, - )) - }) - .await; - let (sink, path, declared) = match built { - Ok(Ok(v)) => v, - Ok(Err(e)) => { + // Rebuild by ordered range reads, fully async: a sync walker + // would force block_on, which has no reactor under the S3 + // backend. Blocks were hash-verified at write, so the + // whole-file digest is the check that matters here. + let slices = match twigpine_core::model::reconstruction::map_file_range( + &entry, &rec, 0, file.size, + ) { + Ok(s) => s, + Err(e) => { return reject_release( state, release_id, @@ -161,27 +137,51 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App ) .await; } - Err(e) => return Err(AppError::Internal(e.into())), }; - if sink.digest.as_deref() != Some(file.sha256.as_str()) { + let mut sink = VerifySink { + hasher: sha2::Sha256::new(), + head: Vec::new(), + }; + for slice in &slices { + let bytes = match super::read_range( + &store, + &slice.block, + slice.offset, + slice.len, + ) + .await + { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + }; + if sink.write_all(&bytes).is_err() { + return Err(AppError::Internal(anyhow::anyhow!("verify sink write"))); + } + } + let digest = hex::encode(sink.hasher.finalize()); + if digest != file.sha256 { return reject_release( state, release_id, - &format!( - "{}: rebuilt bytes hash to {}", - path, - sink.digest.unwrap_or_default() - ), + &format!("{}: rebuilt bytes hash to {digest}", file.path), ) .await; } - let detected = detect_format(&sink.head, &path); - if detected != declared { + let detected = detect_format(&sink.head, &file.path); + if detected != file.format { return reject_release( state, release_id, &format!( - "{path}: declared format {declared:?} but bytes detect as {detected:?}" + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected ), ) .await; From bb394dc919aeb4660cd7a01ebde60035eb6ee380 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:44:55 -0600 Subject: [PATCH 07/20] refactor(node): exit model workers on node shutdown Match the other spawned workers: select each tick against the shutdown watch channel instead of looping until the runtime dies. --- crates/twigpine-node/src/models/sweep.rs | 9 +++++++-- crates/twigpine-node/src/models/verify.rs | 8 ++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index edf12187..c11f6ea9 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -68,11 +68,16 @@ pub async fn sweep_once(state: &AppState) -> Result { Ok(stats) } -/// Periodic sweep; spawned once when model hosting is enabled. +/// Periodic sweep; spawned once when model hosting is enabled and exits on +/// node shutdown. pub async fn run_sweep_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); loop { - interval.tick().await; + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } if let Err(e) = sweep_once(&state).await { tracing::warn!("model sweep failed: {e}"); } diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index b26272b8..5a823e36 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -286,11 +286,15 @@ pub async fn reject_release( } /// Poll for `verifying` releases and verify them in order. Spawned once per -/// node when model hosting is enabled. +/// node when model hosting is enabled; exits on node shutdown. pub async fn run_verify_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); loop { - interval.tick().await; + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } let ids = match state.db.model_verifying_ids(4).await { Ok(v) => v, Err(e) => { From 2d29e9308ac8c39c690073f9950dbd3b26f7b53c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:45:09 -0600 Subject: [PATCH 08/20] fix(node): refund the admission on post-store failures A size-lookup or record_block error after put_verified leaked the session charge until expiry. --- crates/twigpine-node/src/api/models.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index c2802ab0..d20007e2 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -220,12 +220,25 @@ pub async fn put_model_block( }; let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. - let size = store - .size(&block_id) - .await - .map_err(|e| AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")))? - .unwrap_or(declared); - let duplicate = models::record_block(pool, &session.id, &sha, size, declared as i64).await?; + // Past this point the object exists; a bookkeeping failure must refund + // the admission or the session's charge leaks until it expires. + let size = match store.size(&block_id).await { + Ok(s) => s.unwrap_or(declared), + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(AppError::Internal(anyhow::anyhow!( + "block size lookup failed: {e}" + ))); + } + }; + let duplicate = match models::record_block(pool, &session.id, &sha, size, declared as i64).await + { + Ok(d) => d, + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(e); + } + }; let fresh = models::load_session(pool, &session.id).await?; Ok(Json(json!({ "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), From 690b0624e1d3a958b4d04aeaeea06c56685d7097 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:57:04 -0600 Subject: [PATCH 09/20] feat(cli): add twigpine model publish 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. --- crates/twigpine-cli/src/http.rs | 19 + crates/twigpine-cli/src/main.rs | 8 + crates/twigpine-cli/src/model.rs | 1077 ++++++++++++++++++++++++++++++ 3 files changed, 1104 insertions(+) create mode 100644 crates/twigpine-cli/src/model.rs diff --git a/crates/twigpine-cli/src/http.rs b/crates/twigpine-cli/src/http.rs index 309b0d10..a2dda070 100644 --- a/crates/twigpine-cli/src/http.rs +++ b/crates/twigpine-cli/src/http.rs @@ -314,6 +314,25 @@ impl NodeClient { self.send_signed("PUT", path, body).await } + /// PUT raw bytes with no signature and caller-supplied extra headers. + /// Used only for the model block upload, where the session id IS the + /// bearer credential and the body is too large to buffer for signing. + /// Content-Length is set by reqwest from the body, which the route + /// requires. Every other write goes through `put`/`post`/`delete`. + pub async fn put_unsigned( + &self, + path: &str, + body: Vec, + headers: &[(&str, &str)], + ) -> Result { + let url = format!("{}{}", self.node_url, path); + let mut req = self.inner.put(&url).body(body); + for (name, value) in headers { + req = req.header(*name, *value); + } + req.send().await.with_context(|| format!("PUT {url}")) + } + /// DELETE with RFC 9421 signing + transparent iCaptcha solve/retry. pub async fn delete(&self, path: &str, body: &[u8]) -> Result { self.send_signed("DELETE", path, body).await diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index 13696231..9f1dc2e0 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -16,6 +16,7 @@ mod ipfs_cmd; mod issue; mod mcp; mod mirror; +mod model; mod name; mod node; mod node_stake; @@ -140,6 +141,12 @@ enum Commands { /// Print your current identity (DID) and optional node info Whoami(whoami::WhoamiArgs), + + /// Publish open-weight model releases + Model { + #[command(subcommand)] + cmd: model::ModelCmd, + }, } /// The command was `gl` before the rename and still answers to it. Say so @@ -236,6 +243,7 @@ async fn run() -> Result<()> { Commands::Bounty(args) => bounty::run(args).await, Commands::Ucan(args) => ucan_cmd::run(args).await, Commands::Whoami(args) => whoami::run(args).await, + Commands::Model { cmd } => model::run(cmd).await, } } diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs new file mode 100644 index 00000000..ae24c0c1 --- /dev/null +++ b/crates/twigpine-cli/src/model.rs @@ -0,0 +1,1077 @@ +//! `twigpine model` — open-weight model publishing (KTD14). +//! +//! `twigpine model publish` runs inside a local clone of a fully public +//! Twigpine repo: it classifies files by the chunking threshold, packs the +//! large ones into content blocks with cross-release dedup, uploads the new +//! blocks under an upload session (resuming from a `.git` state file after an +//! interruption), commits the signed manifest, pushes, claims the release, +//! and polls until the node's verification publishes it. + +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::STANDARD as B64, Engine}; +use clap::{Args, Subcommand}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Output; +use std::time::{Duration, Instant}; + +use twigpine_core::cid::sha256_hex; +use twigpine_core::model::manifest::{ + self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, + MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{pack_file, BlockEntry, DedupIndex, Reconstruction}; + +use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; +use crate::identity::load_keypair_from_dir; + +const DEFAULT_CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024; +const SESSION_HEADER: &str = "x-twigpine-model-session"; +const STATE_FILE_NAME: &str = "twigpine-model-publish.json"; +const GITIGNORE_BEGIN: &str = "# >>> twigpine-model-publish >>>"; +const GITIGNORE_END: &str = "# <<< twigpine-model-publish <<<"; +/// huggingface_hub 2.x refuses plain downloads of a single file past this. +const SINGLE_FILE_WARN_BYTES: u64 = 50 << 30; +/// Bound on a fetched prior reconstruction object: big models name thousands +/// of blocks but the object is small JSON; a runaway body is not one. +const RECONSTRUCTION_FETCH_CAP: usize = 64 * 1024 * 1024; +const POLL_INTERVAL: Duration = Duration::from_secs(3); +const POLL_BUDGET: Duration = Duration::from_secs(300); + +#[derive(Subcommand)] +pub enum ModelCmd { + /// Publish the working tree as a signed model release + Publish(PublishArgs), +} + +#[derive(Args)] +pub struct PublishArgs { + /// Node base URL (or set TWIGPINE_NODE) + #[arg( + long, + default_value = "https://node.twigpine.com", + env = "TWIGPINE_NODE" + )] + pub node: String, + /// Skip the permanence confirmation (for scripts) + #[arg(long)] + pub yes: bool, + /// Declare a parent release: /@ + #[arg(long)] + pub parent: Option, + /// License identifier recorded in the manifest + #[arg(long, default_value = "")] + pub license: String, + /// Branch to push the release commit to (default: current branch) + #[arg(long)] + pub branch: Option, + /// Chunking threshold in bytes; files at or above it are stored as + /// content blocks instead of git blobs + #[arg(long, hide = true, default_value_t = DEFAULT_CHUNK_THRESHOLD)] + pub chunk_threshold_bytes: u64, + /// Identity directory override + #[arg(long)] + pub dir: Option, +} + +pub async fn run(cmd: ModelCmd) -> Result<()> { + match cmd { + ModelCmd::Publish(a) => cmd_publish(a).await, + } +} + +// ── git helpers ───────────────────────────────────────────────────────────── + +fn git(root: &Path, args: &[&str]) -> Result { + let out = std::process::Command::new("git") + .args(args) + .current_dir(root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(out) +} + +fn git_lines(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect()) +} + +fn git_nul(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .split('\0') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect()) +} + +/// `git log` for the release-marker path, newest first; an unborn HEAD just +/// has none. Capped: each commit costs one reconstruction fetch for dedup. +fn release_commits(root: &Path) -> Vec { + git_lines( + root, + &[ + "log", + "--format=%H", + "-n", + "8", + "--", + ".twigpine/model-release.json", + ], + ) + .unwrap_or_default() +} + +fn repo_root() -> Result { + let out = std::process::Command::new("git") + .args(["rev-parse", "--show-toplevel"]) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("not inside a git repository"); + } + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(PathBuf::from(text.trim())) +} + +fn git_dir(root: &Path) -> Result { + let lines = git_lines(root, &["rev-parse", "--git-dir"])?; + let dir = PathBuf::from(lines.first().context("no git dir")?); + Ok(if dir.is_absolute() { + dir + } else { + root.join(dir) + }) +} + +/// Parse a `twigpine:///` (or `gitlawb://`) remote URL. +fn parse_remote_url(url: &str) -> Option<(String, String)> { + let rest = twigpine_core::url_scheme::strip_scheme(url.trim())?; + let slash = rest.rfind('/')?; + let did = rest[..slash].to_string(); + let repo = twigpine_core::ucan::push::canonical_repo_name(&rest[slash + 1..]).to_string(); + if did.is_empty() || repo.is_empty() { + return None; + } + Some((did, repo)) +} + +/// The remote name plus (owner did, repo) of the first remote carrying a +/// twigpine URL: origin first, then twigpine/gitlawb, then any other. +fn detect_remote(root: &Path) -> Result<(String, String, String)> { + let names = git_lines(root, &["remote"])?; + let preferred = ["origin", "twigpine", "gitlawb"]; + let ordered = preferred + .iter() + .filter(|p| names.iter().any(|n| n == *p)) + .map(|p| p.to_string()) + .chain( + names + .iter() + .filter(|n| !preferred.contains(&n.as_str())) + .cloned(), + ); + for name in ordered { + for extra in [&["--all"][..], &["--push", "--all"][..]] { + let mut args = vec!["remote", "get-url"]; + args.extend_from_slice(extra); + args.push(&name); + let Ok(urls) = git_lines(root, &args) else { + continue; + }; + if let Some((did, repo)) = urls.iter().find_map(|u| parse_remote_url(u)) { + return Ok((name, did, repo)); + } + } + } + bail!("no twigpine:// (or gitlawb://) remote found; run inside a clone of the repo") +} + +// ── file classification ───────────────────────────────────────────────────── + +#[derive(Debug, PartialEq, Eq)] +enum Class { + /// Listed in the manifest with `storage: "git"` and committed. + Git, + /// Listed with `storage: "chunked"`, packed into blocks, gitignored. + Chunked, + /// At or over the threshold but git-tracked: refused (weights live + /// outside git). + LargeTracked, + /// Untracked and ignored, so not part of the publishable set. + Ignored, +} + +/// The publishable set is git's own view of the tree: tracked files plus +/// untracked files that are not ignored. An ignored file only comes back in +/// at threshold size and only while it sits inside the managed .gitignore +/// block, which is how previously published chunked paths stay findable on +/// re-publish without sweeping ignored junk (a `target/` dir) into a release. +fn classify(size: u64, tracked: bool, ignored: bool, managed: bool, threshold: u64) -> Class { + if size >= threshold { + if tracked { + Class::LargeTracked + } else if ignored && !managed { + Class::Ignored + } else { + Class::Chunked + } + } else if ignored { + Class::Ignored + } else { + Class::Git + } +} + +struct Scan { + /// Repo-relative paths committed as git blobs. + git_files: Vec, + /// Repo-relative paths packed as content blocks. + chunked_files: Vec, + /// Tracked files at or over the threshold: the refusal list. + refused: Vec, + /// Ignored files at or over the threshold that are not managed: warned + /// and skipped (see [`classify`]). + skipped_ignored: Vec, +} + +/// Tracked paths from `git ls-files -s`, minus submodule gitlinks (mode +/// 160000): a gitlink has no blob to hash and is not a manifest file. +fn tracked_paths(root: &Path) -> Result> { + let entries = git_nul(root, &["ls-files", "-s", "-z"])?; + let mut out = HashSet::new(); + for e in entries { + let Some((meta, name)) = e.split_once('\t') else { + continue; + }; + if meta.starts_with("160000 ") { + continue; + } + out.insert(name.to_string()); + } + Ok(out) +} + +/// Paths listed inside the managed .gitignore block (empty when there is no +/// block): previously published chunked files. +fn managed_block_paths(gitignore: &str) -> Vec { + let mut inside = false; + let mut out = Vec::new(); + for line in gitignore.lines() { + let t = line.trim_end(); + if t == GITIGNORE_BEGIN { + inside = true; + continue; + } + if t == GITIGNORE_END { + break; + } + if inside && !t.is_empty() { + out.push(t.to_string()); + } + } + out +} + +fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { + let tracked = tracked_paths(root)?; + let others = git_nul(root, &["ls-files", "--others", "-z"])?; + let unignored: HashSet = + git_nul(root, &["ls-files", "--others", "--exclude-standard", "-z"])? + .into_iter() + .collect(); + let managed: HashSet = managed_block_paths(gitignore).into_iter().collect(); + + let mut scan = Scan { + git_files: Vec::new(), + chunked_files: Vec::new(), + refused: Vec::new(), + skipped_ignored: Vec::new(), + }; + let mut consider = |path: &str, is_tracked: bool| { + if path.starts_with(".twigpine/") { + return; // release metadata is never a manifest file + } + // A path that vanished between listing and stat (or a tracked file + // deleted in the worktree, whose staged deletion `git add -A` picks + // up) is simply not in the publishable set. + let Ok(meta) = std::fs::symlink_metadata(root.join(path)) else { + return; + }; + if !meta.is_file() && !meta.file_type().is_symlink() { + return; + } + let ignored = !is_tracked && !unignored.contains(path); + match classify( + meta.len(), + is_tracked, + ignored, + managed.contains(path), + threshold, + ) { + Class::Git => scan.git_files.push(path.to_string()), + Class::Chunked => scan.chunked_files.push(path.to_string()), + Class::LargeTracked => scan.refused.push(path.to_string()), + Class::Ignored => { + if meta.len() >= threshold { + scan.skipped_ignored.push(path.to_string()); + } + } + } + }; + + for p in &tracked { + consider(p, true); + } + for p in &others { + if tracked.contains(p) { + continue; + } + consider(p, false); + } + scan.git_files.sort(); + scan.chunked_files.sort(); + scan.refused.sort(); + scan.skipped_ignored.sort(); + Ok(scan) +} + +// ── .gitignore managed block ──────────────────────────────────────────────── + +/// Insert or replace the managed block so it lists exactly `paths`; an empty +/// list removes the block. Idempotent: rewriting the same list yields the +/// same file content. +fn upsert_managed_block(existing: &str, paths: &[String]) -> String { + let mut out: Vec = existing.lines().map(str::to_string).collect(); + if let Some(b) = out.iter().position(|l| l.trim_end() == GITIGNORE_BEGIN) { + let end = out[b + 1..] + .iter() + .position(|l| l.trim_end() == GITIGNORE_END) + .map(|e| b + 1 + e) + .unwrap_or(out.len() - 1); + out.drain(b..=end); + // The blank line we insert before the block goes with it. + if b > 0 && out.get(b - 1).is_some_and(|l| l.is_empty()) { + out.remove(b - 1); + } + } + if !paths.is_empty() { + if !out.is_empty() && !out.last().is_some_and(|l| l.is_empty()) { + out.push(String::new()); + } + out.push(GITIGNORE_BEGIN.to_string()); + out.extend(paths.iter().cloned()); + out.push(GITIGNORE_END.to_string()); + } + let mut s = out.join("\n"); + if !s.is_empty() { + s.push('\n'); + } + s +} + +// ── resume state ──────────────────────────────────────────────────────────── + +#[derive(Debug, Default, Serialize, Deserialize, PartialEq)] +struct PublishState { + session_id: String, + uploaded: Vec, +} + +fn load_state(path: &Path) -> PublishState { + let Ok(text) = std::fs::read_to_string(path) else { + return PublishState::default(); + }; + serde_json::from_str(&text).unwrap_or_default() +} + +/// Rewrite the state file after each uploaded block: the file carries the +/// resume set, so it is written and fsync'd rather than left in page cache. +fn save_state(path: &Path, state: &PublishState) -> Result<()> { + let bytes = serde_json::to_vec(state)?; + let mut f = std::fs::File::create(path).with_context(|| format!("write {}", path.display()))?; + f.write_all(&bytes)?; + f.sync_all()?; + Ok(()) +} + +// ── misc ──────────────────────────────────────────────────────────────────── + +/// `/@<40-hex commit>` -> ((owner, name), commit). +fn parse_parent(spec: &str) -> Result<((String, String), String)> { + let (repo, commit) = spec + .rsplit_once('@') + .context("parent must be /@")?; + let (owner, name) = repo + .split_once('/') + .context("parent must be /@")?; + if owner.is_empty() || name.is_empty() || name.contains('/') { + bail!("parent must be /@"); + } + if commit.len() != 40 || !commit.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("parent commit must be a 40-hex sha"); + } + Ok(((owner.to_string(), name.to_string()), commit.to_string())) +} + +/// The detached signature file contents: base64-std over the domain-tagged +/// manifest bytes, same as `manifest::sign` but through the CLI Keypair +/// (which signs but does not expose its SigningKey). +fn sign_manifest_bytes(kp: &twigpine_core::identity::Keypair, manifest_bytes: &[u8]) -> String { + let sig = kp.sign(&manifest::signing_input(manifest_bytes)); + B64.encode(sig.to_bytes()) +} + +fn read_head(path: &Path, n: u64) -> Result> { + let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; + let mut buf = Vec::new(); + f.take(n).read_to_end(&mut buf)?; + Ok(buf) +} + +/// Bytes of the staged index blob for `path`: exactly what the release +/// commit will store, filters and symlink handling included. +fn staged_blob(root: &Path, path: &str) -> Result> { + Ok(git(root, &["show", &format!(":{path}")])?.stdout) +} + +/// Fetch a prior release's reconstruction object for dedup. A 404 means the +/// commit never became a published release (or its repo stopped serving); +/// any other non-2xx surfaces the node's own body. +async fn fetch_reconstruction( + client: &NodeClient, + owner: &str, + name: &str, + commit: &str, +) -> Result> { + let path = format!("/api/v1/repos/{owner}/{name}/models/releases/{commit}/reconstruction"); + let resp = client + .get_signed(&path) + .await + .context("reconstruction fetch failed")?; + let status = resp.status(); + if status == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !status.is_success() { + let capped = read_body_capped_bytes(resp, 8 * 1024).await; + bail!( + "reconstruction fetch for {commit} failed ({status}): {}", + crate::http::sanitize_node_msg(&String::from_utf8_lossy(&capped.bytes)) + ); + } + let capped = read_body_capped_bytes(resp, RECONSTRUCTION_FETCH_CAP).await; + if capped.truncated || capped.read_failed { + bail!("reconstruction object for {commit} was oversized or truncated"); + } + let rec = Reconstruction::parse(&capped.bytes) + .map_err(|e| anyhow::anyhow!("reconstruction object for {commit} is invalid: {e}"))?; + Ok(Some(rec)) +} + +/// Send one content block to the session. Unsigned by protocol: the session +/// id is the bearer credential. A non-2xx body is surfaced through +/// `read_json`'s denial path. +async fn upload_block( + client: &NodeClient, + base: &str, + session_id: &str, + sha: &str, + data: Vec, +) -> Result<()> { + let resp = client + .put_unsigned( + &format!("{base}/models/blocks/{sha}"), + data, + &[(SESSION_HEADER, session_id)], + ) + .await?; + let _: Value = read_json(resp, "block upload").await?; + Ok(()) +} + +/// Without `--yes`, publishing requires an explicit "yes" on stdin. Any +/// other answer, including EOF on a pipe, declines. +fn confirm_publish() -> Result { + eprint!("type 'yes' to publish: "); + let _ = std::io::stderr().flush(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line)?; + Ok(line.trim().eq_ignore_ascii_case("yes")) +} + +// ── publish ───────────────────────────────────────────────────────────────── + +async fn cmd_publish(args: PublishArgs) -> Result<()> { + let kp = load_keypair_from_dir(args.dir.as_deref())?; + let root = repo_root()?; + let git_dir = git_dir(&root)?; + let (remote_name, owner, name) = detect_remote(&root)?; + let branch = match &args.branch { + Some(b) => b.clone(), + None => { + let out = std::process::Command::new("git") + .args(["symbolic-ref", "--short", "-q", "HEAD"]) + .current_dir(&root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("detached HEAD: pass --branch to name the release branch"); + } + String::from_utf8(out.stdout) + .context("branch name was not utf-8")? + .trim() + .to_string() + } + }; + + // 1. Scan and refuse tracked large files before anything else happens. + let gitignore_path = root.join(".gitignore"); + let existing_gitignore = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); + let scan = scan_files(&root, &existing_gitignore, args.chunk_threshold_bytes)?; + if !scan.refused.is_empty() { + bail!( + "these files are {} bytes or larger but tracked in git; weights must live \ + outside git. Remove them from the index first (git rm --cached):\n {}", + args.chunk_threshold_bytes, + scan.refused.join("\n ") + ); + } + for p in &scan.skipped_ignored { + eprintln!( + "warning: {p} is at or over the chunk threshold but gitignored; \ + unignore it to publish" + ); + } + + // 2. Warn + confirm: publishing is permanent. + println!("Publishing {owner}/{name} as a model release on branch {branch}:"); + println!( + " {} git files, {} chunked files", + scan.git_files.len(), + scan.chunked_files.len() + ); + for p in &scan.chunked_files { + let size = std::fs::symlink_metadata(root.join(p)) + .map(|m| m.len()) + .unwrap_or(0); + if size > SINGLE_FILE_WARN_BYTES { + eprintln!( + "warning: {p} is over 50 GiB; huggingface_hub refuses plain downloads that large" + ); + } + } + eprintln!( + "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" + ); + if !args.yes && !confirm_publish()? { + println!("aborted"); + return Ok(()); + } + + let client = NodeClient::new(&args.node, Some(kp.clone())); + let base = format!("/api/v1/repos/{owner}/{name}"); + + // 3. Dedup: reconstructions of prior releases in this clone, plus the + // declared parent's when given. + let mut priors: Vec = Vec::new(); + let mut parent_ref: Option = None; + for commit in release_commits(&root) { + if let Some(rec) = fetch_reconstruction(&client, &owner, &name, &commit).await? { + priors.push(rec); + } + } + if let Some(spec) = &args.parent { + let ((powner, pname), pcommit) = parse_parent(spec)?; + let rec = fetch_reconstruction(&client, &powner, &pname, &pcommit) + .await? + .context("declared parent has no published reconstruction on this node")?; + // There is no manifest-serving route, so the parent manifest sha256 + // is the sha of the manifest bytes in the local clone when the parent + // commit is here, and the sha of the parent's reconstruction object + // (the only parent artifact the node serves) otherwise. The node + // records the field without checking it (R9: a signed claim, not a + // verified link). + let manifest_sha = git( + &root, + &["show", &format!("{pcommit}:.twigpine/model-release.json")], + ) + .map(|out| sha256_hex(&out.stdout)) + .unwrap_or_else(|_| sha256_hex(&rec.to_bytes().unwrap_or_default())); + parent_ref = Some(ParentRef { + repo: format!("{powner}/{pname}"), + commit: pcommit, + manifest_sha256: manifest_sha, + }); + priors.push(rec); + } + let prior_refs: Vec<&Reconstruction> = priors.iter().collect(); + let mut dedup = DedupIndex::from_reconstructions(&prior_refs); + let mut all_entries: HashMap = HashMap::new(); + for rec in &priors { + for b in &rec.blocks { + all_entries.insert(b.sha256.clone(), b.clone()); + } + } + + // 4. Pack every chunked file; shared chunks become terms into prior + // blocks, the rest seal into new blocks to upload. + let mut rec = Reconstruction::new(); + let mut new_blocks = Vec::new(); + let mut new_block_shas: HashSet = HashSet::new(); + let mut files: Vec = Vec::new(); + for path in &scan.chunked_files { + let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; + let packed = pack_file(path, file, &dedup)?; + let head = read_head(&root.join(path), 64)?; + files.push(ManifestFile { + path: path.clone(), + size: packed.file.size, + sha256: packed.file.sha256.clone(), + format: detect_format(&head, path), + storage: StorageKind::Chunked, + }); + rec.files.push(packed.file); + for e in packed.block_entries { + all_entries.insert(e.sha256.clone(), e.clone()); + rec.blocks.push(e); + } + for b in packed.new_blocks { + if new_block_shas.insert(b.sha256.clone()) { + new_blocks.push(b); + } + } + // Make this file's fresh chunks visible to the next file's dedup. + dedup.add(&rec); + } + // Terms into earlier blocks need those entries in this object: a reader + // resolves term.block against rec.blocks only. + let needed: HashSet = rec + .files + .iter() + .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) + .collect(); + for sha in needed { + if rec.blocks.iter().any(|b| b.sha256 == sha) { + continue; + } + let entry = all_entries + .get(&sha) + .with_context(|| format!("term references unknown block {sha}"))?; + rec.blocks.push(entry.clone()); + } + // A release with no chunked files has no chunked bytes to reconstruct: + // no reconstruction object, no reconstruction block. + let rec_bytes = if scan.chunked_files.is_empty() { + Vec::new() + } else { + rec.validate() + .map_err(|e| anyhow::anyhow!("reconstruction object invalid: {e}"))?; + rec.to_bytes() + .map_err(|e| anyhow::anyhow!("reconstruction serialize failed: {e}"))? + }; + let rec_sha = sha256_hex(&rec_bytes); + + // 5. Open (or resume) the upload session and send the new blocks, then + // the reconstruction object as one more block. + let state_path = git_dir.join(STATE_FILE_NAME); + let mut state = load_state(&state_path); + if !state.session_id.is_empty() { + let resp = client + .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) + .await + .context("session status request failed")?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + state = PublishState::default(); + } else { + let v: Value = read_json(resp, "session status").await?; + if v["state"].as_str() != Some("open") { + state = PublishState::default(); + } + } + } + if state.session_id.is_empty() { + let body = serde_json::to_vec(&json!({ + "parent_release": parent_ref.as_ref().map(|p| p.commit.clone()), + }))?; + let resp = client + .post(&format!("{base}/models/sessions"), &body) + .await?; + let v: Value = json_or_denial("open model session", resp).await?; + state.session_id = v["session_id"] + .as_str() + .context("session response had no session_id")? + .to_string(); + state.uploaded.clear(); + save_state(&state_path, &state)?; + } + let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); + let session_id = state.session_id.clone(); + + let total = new_blocks.len() + usize::from(!rec_bytes.is_empty()); + for (i, block) in new_blocks.into_iter().enumerate() { + let sha = block.sha256; + if uploaded.contains(&sha) { + continue; + } + upload_block(&client, &base, &session_id, &sha, block.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha); + save_state(&state_path, &state)?; + println!("uploaded block {}/{total}", i + 1); + } + if !rec_bytes.is_empty() && !uploaded.contains(&rec_sha) { + upload_block(&client, &base, &session_id, &rec_sha, rec_bytes.clone()).await?; + state.uploaded.push(rec_sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded reconstruction object ({total}/{total})"); + } + + // 6. Managed .gitignore block, then stage the publishable set. + let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); + if new_gitignore != existing_gitignore { + std::fs::write(&gitignore_path, &new_gitignore)?; + } + git(&root, &["add", "-A"])?; + + // 7. Hash the git-stored files from the index (the exact bytes the + // commit stores), then write and stage the manifest. + for path in &scan.git_files { + let bytes = staged_blob(&root, path)?; + files.push(ManifestFile { + path: path.clone(), + size: bytes.len() as u64, + sha256: sha256_hex(&bytes), + format: detect_format(&bytes[..bytes.len().min(64)], path), + storage: StorageKind::Git, + }); + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner}/{name}"), + publisher_did: kp.did().to_string(), + license: args.license.clone(), + parent: parent_ref, + files, + reconstruction: if rec_bytes.is_empty() { + None + } else { + Some(ReconstructionRef { + sha256: rec_sha, + size: rec_bytes.len() as u64, + }) + }, + }; + let manifest_bytes = manifest + .to_bytes() + .map_err(|e| anyhow::anyhow!("manifest serialize failed: {e}"))?; + let twigpine_dir = root.join(".twigpine"); + std::fs::create_dir_all(&twigpine_dir)?; + std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; + std::fs::write( + twigpine_dir.join("model-release.sig"), + format!("{}\n", sign_manifest_bytes(&kp, &manifest_bytes)), + )?; + git(&root, &["add", "-A"])?; + + // 8. Commit when the index differs, push, and claim HEAD. + let has_changes = git(&root, &["diff", "--cached", "--quiet"]).is_err(); + if has_changes { + let n = release_commits(&root).len() + 1; + git(&root, &["commit", "-m", &format!("model release {n}")])?; + } else { + // Nothing staged: a re-publish of identical content lands here, and + // HEAD must already be a release commit to claim. + if git( + &root, + &["cat-file", "-e", "HEAD:.twigpine/model-release.json"], + ) + .is_err() + { + bail!("nothing to publish and HEAD carries no release manifest"); + } + println!("no changes to commit; claiming the existing release commit"); + } + let commit = git_lines(&root, &["rev-parse", "HEAD"])? + .into_iter() + .next() + .context("no HEAD commit")?; + + let push = std::process::Command::new("git") + .args(["push", &remote_name, &format!("HEAD:{branch}")]) + .current_dir(&root) + .env("TWIGPINE_NODE", &args.node) + // The helper on PATH may be a build from before the rename. + .env("GITLAWB_NODE", &args.node) + .output() + .context("failed to run git push")?; + if !push.status.success() { + bail!( + "git push failed:\n{}", + String::from_utf8_lossy(&push.stderr).trim() + ); + } + println!("pushed {commit} to {remote_name}/{branch}"); + + let claim_body = serde_json::to_vec(&json!({ + "commit": commit, + "branch": branch, + }))?; + let resp = client + .post(&format!("{base}/models/claims"), &claim_body) + .await?; + let claim: Value = json_or_denial("claim release", resp).await?; + let release_id = claim["release_id"].as_i64().unwrap_or_default(); + println!("release {release_id} claimed; verifying"); + + // 9. Poll until the verification worker settles the release. + let release_path = format!("{base}/models/releases/{commit}"); + let deadline = Instant::now() + POLL_BUDGET; + loop { + let resp = client.get_signed(&release_path).await?; + let v: Value = read_json(resp, "release status").await?; + match v["state"].as_str() { + Some("published") => { + println!("published release {release_id}"); + println!(" commit: {}", v["commit"].as_str().unwrap_or(&commit)); + println!( + " manifest: {}", + v["manifest_sha256"].as_str().unwrap_or("?") + ); + let _ = std::fs::remove_file(&state_path); + return Ok(()); + } + Some("rejected") => { + bail!( + "release {release_id} rejected: {}", + v["failure_reason"].as_str().unwrap_or("unknown reason") + ); + } + _ => { + if Instant::now() >= deadline { + println!( + "release {release_id} is still verifying after {}s; its status is at\n \ + GET {release_path}", + POLL_BUDGET.as_secs() + ); + return Ok(()); + } + tokio::time::sleep(POLL_INTERVAL).await; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: u64 = 1024; // test threshold + + #[test] + fn classify_by_threshold_tracking_and_ignore() { + // Below threshold: tracked or unignored-untracked are git files. + assert_eq!(classify(T - 1, true, false, false, T), Class::Git); + assert_eq!(classify(T - 1, false, false, false, T), Class::Git); + assert_eq!(classify(T - 1, false, true, false, T), Class::Ignored); + assert_eq!(classify(T - 1, false, true, true, T), Class::Ignored); + // At/above threshold: tracked refuses; untracked chunks unless + // ignored outside the managed block. + assert_eq!(classify(T, true, false, false, T), Class::LargeTracked); + assert_eq!(classify(T + 1, true, true, false, T), Class::LargeTracked); + assert_eq!(classify(T, false, false, false, T), Class::Chunked); + assert_eq!(classify(T, false, true, true, T), Class::Chunked); + assert_eq!(classify(T, false, true, false, T), Class::Ignored); + } + + #[test] + fn managed_block_upsert_insert_replace_idempotent_remove() { + let base = "*.tmp\n".to_string(); + let paths = vec!["weights/a.bin".to_string(), "b.bin".to_string()]; + let once = upsert_managed_block(&base, &paths); + assert!(once.contains("*.tmp\n")); + assert!(once.contains(GITIGNORE_BEGIN)); + assert!(once.contains("weights/a.bin\nb.bin\n")); + assert!(once.contains(GITIGNORE_END)); + assert_eq!(once, upsert_managed_block(&once, &paths), "idempotent"); + + let replaced = upsert_managed_block(&once, &["c.bin".to_string()]); + assert!(replaced.contains("c.bin")); + assert!(!replaced.contains("a.bin")); + + let removed = upsert_managed_block(&replaced, &[]); + assert!(!removed.contains(GITIGNORE_BEGIN)); + assert_eq!(removed, "*.tmp\n"); + + let empty = upsert_managed_block("", &paths); + assert_eq!(managed_block_paths(&empty), paths); + } + + #[test] + fn managed_block_paths_reads_only_the_block() { + let text = format!("a\n{GITIGNORE_BEGIN}\nx.bin\ny.bin\n{GITIGNORE_END}\nz\n"); + assert_eq!(managed_block_paths(&text), vec!["x.bin", "y.bin"]); + assert!(managed_block_paths("nothing here\n").is_empty()); + } + + #[test] + fn publish_state_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "abc".to_string(), + uploaded: vec!["aa".into(), "bb".into()], + }; + save_state(&path, &state).unwrap(); + assert_eq!(load_state(&path), state); + assert_eq!( + load_state(&dir.path().join("missing.json")), + PublishState::default() + ); + std::fs::write(&path, "not json").unwrap(); + assert_eq!(load_state(&path), PublishState::default()); + } + + #[test] + fn parse_parent_shapes() { + let commit = "a".repeat(40); + let ((owner, name), c) = parse_parent(&format!("alice/weights@{commit}")).unwrap(); + assert_eq!( + (owner.as_str(), name.as_str(), c.as_str()), + ("alice", "weights", commit.as_str()) + ); + // A did:key owner carries colons; the split is on the LAST '@'. + let did_owner = "did:key:z6MkAbc"; + let ((owner, name), _) = parse_parent(&format!("{did_owner}/weights@{commit}")).unwrap(); + assert_eq!((owner.as_str(), name.as_str()), (did_owner, "weights")); + for bad in [ + "noslash", + "a/b@", + "a/b@cafe", + &format!("a/b/c@{commit}"), + &format!("a/b@{commit}x"), + &format!("a/b@{}", "g".repeat(40)), + ] { + assert!(parse_parent(bad).is_err(), "{bad}"); + } + } + + #[test] + fn manifest_assembly_round_trips_storage_kinds() { + // The manifest the command writes: schema v1, repo as owner/name, + // git and chunked entries sorted by path, reconstruction ref present. + let kp = twigpine_core::identity::Keypair::from_seed(&[3u8; 32]).unwrap(); + let mut files = vec![ + ManifestFile { + path: "weights.bin".to_string(), + size: 11, + sha256: "b".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Other, + storage: StorageKind::Chunked, + }, + ManifestFile { + path: "README.md".to_string(), + size: 5, + sha256: "a".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Text, + storage: StorageKind::Git, + }, + ]; + files.sort_by(|a, b| a.path.cmp(&b.path)); + let m = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "did:key:z6MkA/w".to_string(), + publisher_did: kp.did().to_string(), + license: "apache-2.0".to_string(), + parent: None, + files, + reconstruction: Some(ReconstructionRef { + sha256: "c".repeat(64), + size: 42, + }), + }; + let bytes = m.to_bytes().unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["schema"].as_str(), Some(MANIFEST_SCHEMA_V1)); + assert_eq!(v["repo"].as_str(), Some("did:key:z6MkA/w")); + assert_eq!(v["license"].as_str(), Some("apache-2.0")); + let paths: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["path"].as_str()) + .collect(); + assert_eq!(paths, ["README.md", "weights.bin"]); + let storages: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["storage"].as_str()) + .collect(); + assert_eq!(storages, ["git", "chunked"]); + let rec_sha = "c".repeat(64); + assert_eq!( + v["reconstruction"]["sha256"].as_str(), + Some(rec_sha.as_str()) + ); + } + + #[test] + fn cli_signature_matches_manifest_sign() { + // The two paths sign the same domain-tagged bytes with the same key: + // manifest::sign takes a raw SigningKey, the CLI signs through Keypair. + let seed = [9u8; 32]; + let signing = ed25519_dalek::SigningKey::from_bytes(&seed); + let kp = twigpine_core::identity::Keypair::from_seed(&seed).unwrap(); + let m = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "alice/m".to_string(), + publisher_did: kp.did().to_string(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: Some(ReconstructionRef { + sha256: "a".repeat(64), + size: 1, + }), + }; + let bytes = m.to_bytes().unwrap(); + let sig = sign_manifest_bytes(&kp, &bytes); + assert_eq!(sig, manifest::sign(&signing, &bytes)); + let parsed = manifest::verify(&bytes, &sig, &kp.did()).unwrap(); + assert_eq!(parsed.repo, "alice/m"); + } + + #[test] + fn remote_url_parses_both_schemes() { + assert_eq!( + parse_remote_url("twigpine://did:key:z6MkA/repo.git"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!( + parse_remote_url("gitlawb://did:key:z6MkA/repo"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!(parse_remote_url("https://x/y"), None); + } +} From ee8f61a6793840feb031250d6661a4d0c20ff1f9 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:57:09 -0600 Subject: [PATCH 10/20] test(node): add HTTP coverage for model routes 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. --- crates/twigpine-node/Cargo.toml | 5 + crates/twigpine-node/src/db/model_queries.rs | 13 +- crates/twigpine-node/tests/models_api.rs | 730 +++++++++++++++++++ 3 files changed, 743 insertions(+), 5 deletions(-) create mode 100644 crates/twigpine-node/tests/models_api.rs diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index f1a5f827..acf6097c 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -28,6 +28,11 @@ name = "deny_harness" path = "tests/deny_harness.rs" required-features = ["test-harness"] +[[test]] +name = "models_api" +path = "tests/models_api.rs" +required-features = ["test-harness"] + [dependencies] twigpine-core = { path = "../twigpine-core" } async-trait = "0.1" diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index fe77992e..2244b6ce 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -407,8 +407,9 @@ impl Db { if shas.is_empty() { return Ok(0); } + // SUM over bigint returns numeric; cast back so the i64 decode holds. Ok(sqlx::query_scalar::<_, Option>( - "SELECT SUM(b.size) FROM model_blocks b + "SELECT SUM(b.size)::bigint FROM model_blocks b WHERE b.sha256 = ANY($1) AND NOT EXISTS ( SELECT 1 FROM model_release_blocks rb @@ -450,10 +451,11 @@ impl Db { /// Node-wide used bytes: claimed quota plus every open session's bytes. pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { + // SUM over bigint returns numeric; cast back so the i64 decode holds. Ok(sqlx::query_scalar::<_, Option>( - "SELECT COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + "SELECT (COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions - WHERE state = 'open'), 0)", + WHERE state = 'open'), 0))::bigint", ) .fetch_one(&mut **tx) .await? @@ -579,8 +581,9 @@ impl Db { tx.commit().await?; return Ok(()); }; + // SUM over bigint returns numeric; cast back so the i64 decode holds. let freed: i64 = sqlx::query_scalar::<_, Option>( - "SELECT COALESCE(SUM(b.size), 0) FROM model_blocks b + "SELECT COALESCE(SUM(b.size), 0)::bigint FROM model_blocks b JOIN model_release_blocks rb ON rb.block_sha256 = b.sha256 WHERE rb.release_id = $1 AND NOT EXISTS ( @@ -769,7 +772,7 @@ mod tests { .unwrap() .expect("first admission"); assert_eq!(first.bytes_received, 100); - assert!(first.expires_at > s.expires_at || first.expires_at == s.expires_at); + assert!(first.expires_at >= s.expires_at); // Over the per-identity session cap: refused. assert!(db .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs new file mode 100644 index 00000000..236641f4 --- /dev/null +++ b/crates/twigpine-node/tests/models_api.rs @@ -0,0 +1,730 @@ +//! HTTP-level coverage for the U5/U6/U7 model-hosting routes: the signed +//! session open and session status, the unsigned bearer block PUT, the signed +//! release claim (including its request-digest replay), and the read-gated +//! release status. The deny sweep already proves the hostile statuses; these +//! tests drive the happy paths and the handler-specific 4xxes the sweep rows +//! cannot express. Requires `--features test-harness`. + +#[allow(dead_code)] +mod support; + +use serde_json::{json, Value}; +use sha2::Digest; +use support::signing::signed_request; + +use twigpine_core::http_sig::sign_request; +use twigpine_core::identity::Keypair; +use twigpine_node::test_harness::{spawn_node, TestNode}; + +fn bounded_client() -> reqwest::Client { + reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(30)) + .build() + .expect("client builds") +} + +fn sessions_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/sessions") +} + +fn claims_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/claims") +} + +fn release_path(owner: &str, repo: &str, commit: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/releases/{commit}") +} + +fn blocks_path(owner: &str, repo: &str, sha: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/blocks/{sha}") +} + +fn put_block( + client: &reqwest::Client, + base_url: &str, + path: &str, + session: Option<&str>, + body: Vec, +) -> reqwest::RequestBuilder { + let mut req = client.put(format!("{base_url}{path}")).body(body); + if let Some(s) = session { + req = req.header("x-twigpine-model-session", s); + } + req +} + +/// An owner keypair plus the raw SigningKey the manifest format signs with; +/// both derive from one seed so the keypair's DID anchors the manifest. +fn owner_with_signing(seed: u8) -> (Keypair, ed25519_dalek::SigningKey) { + let seed_bytes = [seed; 32]; + ( + Keypair::from_seed(&seed_bytes).expect("keypair"), + ed25519_dalek::SigningKey::from_bytes(&seed_bytes), + ) +} + +/// Build a git repo on disk containing one commit with a valid signed release +/// manifest, returning the commit sha. The claim route's `git cat-file` / +/// `git show` calls run against `repos.disk_path`, so the row must point here. +fn make_release_repo(dir: &std::path::Path, manifest: &[u8], sig: &str) -> String { + let run = |args: &[&str]| { + let out = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + run(&["init", "-q", "-b", "main"]); + std::fs::create_dir_all(dir.join(".twigpine")).expect("mkdir .twigpine"); + std::fs::write(dir.join(".twigpine/model-release.json"), manifest).expect("write manifest"); + std::fs::write(dir.join(".twigpine/model-release.sig"), sig).expect("write sig"); + run(&["add", "-A"]); + run(&[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "model release 1", + ]); + run(&["rev-parse", "HEAD"]) +} + +/// Point the seeded repo row at an on-disk git directory (seed_repo writes a +/// placeholder disk_path the claim route cannot read). +async fn set_disk_path(pool: &sqlx::PgPool, repo_id: &str, dir: &std::path::Path) { + sqlx::query("UPDATE repos SET disk_path = $1 WHERE id = $2") + .bind(dir.to_str().expect("utf-8 temp path")) + .bind(repo_id) + .execute(pool) + .await + .expect("update disk_path"); +} + +async fn seed_open_session(node: &TestNode, repo_id: &str, owner_did: &str) -> String { + let session_id = "s".repeat(64); + node.seed_model_session(repo_id, &session_id, owner_did) + .await; + session_id +} + +// ── POST /models/sessions ──────────────────────────────────────────────────── + +/// The owner opening a session on a fully public repo gets 201 and a +/// 64-hex session id plus an expiry. +#[sqlx::test] +async fn open_session_owner_created(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 201); + let v: Value = resp.json().await.expect("session body"); + assert_eq!( + v["session_id"].as_str().map(str::len), + Some(64), + "session id is a 256-bit hex bearer" + ); + assert!(v["expires_at"].as_str().is_some()); + + node.shutdown().await; +} + +/// A signed caller who is not the repo owner gets the owner gate's 403. +#[sqlx::test] +async fn open_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +/// An unsigned request is stopped by the signature layer before any repo +/// lookup: 401. +#[sqlx::test] +async fn open_session_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = client + .post(format!( + "{}{}", + node.base_url, + sessions_path(&owner_did, "model") + )) + .body(b"{}".to_vec()) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A private repo answers the read gate's existence-hiding 404 to a signed +/// non-reader, before the owner gate can fire. +#[sqlx::test] +async fn open_session_private_repo_hidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A public repo carrying a path-scoped visibility rule is not "fully +/// public", so the session open refuses it with a named 400 rather than +/// partially publishing. +#[sqlx::test] +async fn open_session_repo_with_visibility_rule_rejected(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + node.withhold_path(&repo_id, "sub/**", &[], &owner_did) + .await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let body = resp.text().await.unwrap_or_default(); + assert!( + body.contains("fully public"), + "denial should name the fully-public requirement, got: {body}" + ); + + node.shutdown().await; +} + +// ── GET /models/sessions/{id} ──────────────────────────────────────────────── + +/// The owner reads back an open session's state and byte counter. +#[sqlx::test] +async fn get_session_owner_reads_open(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("session body"); + assert_eq!(v["session_id"].as_str(), Some(session_id.as_str())); + assert_eq!(v["state"].as_str(), Some("open")); + + node.shutdown().await; +} + +/// A signed stranger reaches the owner gate on the session read: 403. +#[sqlx::test] +async fn get_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +// ── PUT /models/blocks/{sha256} ────────────────────────────────────────────── + +/// The unsigned PUT without the session header gets 401: the bearer +/// credential is absent, not invalid. +#[sqlx::test] +async fn put_block_without_session_header_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let sha = hex::encode(sha2::Sha256::digest(b"block")); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + None, + b"block".to_vec(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A session id that was never issued answers the same 404 as an expired or +/// foreign one: a bearer guess learns nothing about which part failed. +#[sqlx::test] +async fn put_block_bogus_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&"f".repeat(64)), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A session bound to repo A does not upload into repo B: the +/// session-to-repo binding check answers 404. +#[sqlx::test] +async fn put_block_session_for_other_repo_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_a = node.seed_repo(&owner_did, "model-a", true).await; + node.seed_repo(&owner_did, "model-b", true).await; + let session_id = seed_open_session(&node, &repo_a, &owner_did).await; + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model-b", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// An open session whose expiry already passed answers 404; the PUT never +/// reaches the block store. +#[sqlx::test] +async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "e".repeat(64); + sqlx::query( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1,$2,$3,$4,$5,0,'open')", + ) + .bind(&session_id) + .bind(&owner_did) + .bind(&repo_id) + .bind(chrono::Utc::now().to_rfc3339()) + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .execute(&pool) + .await + .expect("seed expired session"); + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// Happy path: a block whose body hashes to the id in the path is stored, +/// reported with the session's running byte count and `duplicate:false`; +/// resending it reports `duplicate:true`; a body that does not match the +/// named id is refused with 400. +#[sqlx::test] +async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = b"the quick brown fox".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("block response"); + assert_eq!(v["duplicate"].as_bool(), Some(false)); + assert!( + v["received"].as_i64().unwrap_or(0) >= body.len() as i64, + "bytes_received should include this block: {v}" + ); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("dup response"); + assert_eq!(v["duplicate"].as_bool(), Some(true)); + + let wrong_sha = "0".repeat(64); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &wrong_sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400, "digest mismatch is a 400"); + + node.shutdown().await; +} + +// ── POST /models/claims ────────────────────────────────────────────────────── + +/// A claim against a pushed commit carrying a signed manifest inserts the +/// release row; re-sending the identical signed request resolves to the same +/// release_id through the persisted request digest. +#[sqlx::test] +async fn claim_accepts_signed_manifest_and_replays_idempotently(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(7); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + + let dir = tempfile::tempdir().expect("tempdir"); + let commit = make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let path = claims_path(&owner_did, "model"); + let body = + serde_json::to_vec(&json!({"commit": commit, "branch": "main"})).expect("claim body"); + // Sign once, then send the identical request twice: the digest replay + // resolves the second to the original row. + let signed = sign_request(&owner, "POST", &path, &body); + let send = |client: &reqwest::Client| { + client + .post(format!("{}{}", node.base_url, path)) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body.clone()) + }; + + let resp = send(&client).send().await.expect("request sends"); + let status = resp.status().as_u16(); + let text = resp.text().await.unwrap_or_default(); + assert_eq!(status, 200, "claim body: {text}"); + let v: Value = serde_json::from_str(&text).expect("claim response"); + let release_id = v["release_id"].as_i64().expect("release_id"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("verifying")); + + let resp = send(&client).send().await.expect("replay sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("replay response"); + assert_eq!( + v["release_id"].as_i64(), + Some(release_id), + "a replayed claim must resolve to the original release row" + ); + + node.shutdown().await; +} + +/// A claim naming a commit the repo does not hold is a 400, not a 404: the +/// repo exists and is readable; the commit is the bad input. +#[sqlx::test] +async fn claim_missing_commit_is_bad_request(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(8); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + // A real on-disk repo is needed for `git cat-file` to answer "missing" + // rather than the spawn failing on a nonexistent path. + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + let dir = tempfile::tempdir().expect("tempdir"); + make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let body = serde_json::to_vec(&json!({ + "commit": "b".repeat(40), + "branch": "main", + })) + .expect("claim body"); + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body, + &owner, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let text = resp.text().await.unwrap_or_default(); + assert!(text.contains("commit not found"), "got: {text}"); + + node.shutdown().await; +} + +/// The owner gate on claims: a signed stranger is 403, an unsigned request is +/// 401 before the handler runs. +#[sqlx::test] +async fn claim_non_owner_forbidden_and_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = serde_json::to_vec(&json!({ + "commit": "a".repeat(40), + "branch": "main", + })) + .expect("claim body"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body.clone(), + &stranger, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +// ── GET /models/releases/{sha} ─────────────────────────────────────────────── + +/// A seeded published release reads back its fields; an unknown commit is a +/// plain 404; a private repo's release is existence-hiding to a non-reader. +#[sqlx::test] +async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let commit = "c".repeat(40); + node.seed_model_release(&repo_id, &commit, &owner_did).await; + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &commit) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("release body"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("published")); + assert_eq!(v["branch"].as_str(), Some("main")); + assert!(v["release_id"].as_i64().is_some()); + assert!(v["manifest_sha256"].as_str().is_some()); + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &"d".repeat(40)) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "unknown commit is a 404"); + + // Private repo: a signed stranger gets the existence-hiding 404. + let priv_repo = node.seed_repo(&owner_did, "model-priv", false).await; + node.seed_model_release(&priv_repo, &commit, &owner_did) + .await; + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &release_path(&owner_did, "model-priv", &commit), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} From 97c4d9b8a1e895fa9bd414885cca064cb8f42d5d Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:16:54 -0600 Subject: [PATCH 11/20] refactor(node): tighten model publishing after the simplify pass 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. --- crates/twigpine-cli/Cargo.toml | 3 +- crates/twigpine-cli/src/model.rs | 210 ++++++++---------- .../twigpine-core/src/model/reconstruction.rs | 8 +- crates/twigpine-node/src/api/models.rs | 132 ++++++----- crates/twigpine-node/src/db/mod.rs | 4 +- crates/twigpine-node/src/db/model_queries.rs | 75 ++++--- crates/twigpine-node/src/git/store.rs | 41 ++-- crates/twigpine-node/src/models/claim.rs | 41 ++-- crates/twigpine-node/src/models/mod.rs | 100 +-------- crates/twigpine-node/src/models/sweep.rs | 4 +- crates/twigpine-node/src/models/verify.rs | 38 ++-- crates/twigpine-node/tests/models_api.rs | 114 +++++++--- crates/twigpine-node/tests/support/routes.rs | 4 +- 13 files changed, 374 insertions(+), 400 deletions(-) diff --git a/crates/twigpine-cli/Cargo.toml b/crates/twigpine-cli/Cargo.toml index d39d025e..b844b079 100644 --- a/crates/twigpine-cli/Cargo.toml +++ b/crates/twigpine-cli/Cargo.toml @@ -41,8 +41,9 @@ alloy = { version = "1", default-features = false, features = [ "rpc-types-eth", ] } +ed25519-dalek = { workspace = true } + [dev-dependencies] mockito = "1" tempfile = "3" tokio = { workspace = true } -ed25519-dalek = { workspace = true } diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index ae24c0c1..ea2edbd7 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -8,7 +8,6 @@ //! and polls until the node's verification publishes it. use anyhow::{bail, Context, Result}; -use base64::{engine::general_purpose::STANDARD as B64, Engine}; use clap::{Args, Subcommand}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -431,14 +430,6 @@ fn parse_parent(spec: &str) -> Result<((String, String), String)> { Ok(((owner.to_string(), name.to_string()), commit.to_string())) } -/// The detached signature file contents: base64-std over the domain-tagged -/// manifest bytes, same as `manifest::sign` but through the CLI Keypair -/// (which signs but does not expose its SigningKey). -fn sign_manifest_bytes(kp: &twigpine_core::identity::Keypair, manifest_bytes: &[u8]) -> String { - let sig = kp.sign(&manifest::signing_input(manifest_bytes)); - B64.encode(sig.to_bytes()) -} - fn read_head(path: &Path, n: u64) -> Result> { let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; let mut buf = Vec::new(); @@ -594,8 +585,9 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { // declared parent's when given. let mut priors: Vec = Vec::new(); let mut parent_ref: Option = None; - for commit in release_commits(&root) { - if let Some(rec) = fetch_reconstruction(&client, &owner, &name, &commit).await? { + let prior_commits = release_commits(&root); + for commit in &prior_commits { + if let Some(rec) = fetch_reconstruction(&client, &owner, &name, commit).await? { priors.push(rec); } } @@ -632,15 +624,50 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } - // 4. Pack every chunked file; shared chunks become terms into prior - // blocks, the rest seal into new blocks to upload. + // 4. Open (or resume) the upload session before packing, so each new + // block streams out as it seals instead of buffering the whole + // model in memory. + let state_path = git_dir.join(STATE_FILE_NAME); + let mut state = load_state(&state_path); + if !state.session_id.is_empty() { + let resp = client + .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) + .await + .context("session status request failed")?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + state = PublishState::default(); + } else { + let v: Value = read_json(resp, "session status").await?; + if v["state"].as_str() != Some("open") { + state = PublishState::default(); + } + } + } + if state.session_id.is_empty() { + let body = serde_json::to_vec(&json!({}))?; + let resp = client + .post(&format!("{base}/models/sessions"), &body) + .await?; + let v: Value = json_or_denial("open model session", resp).await?; + state.session_id = v["session_id"] + .as_str() + .context("session response had no session_id")? + .to_string(); + state.uploaded.clear(); + save_state(&state_path, &state)?; + } + let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); + let session_id = state.session_id.clone(); + + // 5. Pack every chunked file; shared chunks become terms into prior + // blocks, the rest seal into new blocks uploaded as they seal. let mut rec = Reconstruction::new(); - let mut new_blocks = Vec::new(); - let mut new_block_shas: HashSet = HashSet::new(); let mut files: Vec = Vec::new(); for path in &scan.chunked_files { let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; let packed = pack_file(path, file, &dedup)?; + // Make this file's fresh chunks visible to the next file's dedup. + dedup.add_block_entries(&packed.block_entries); let head = read_head(&root.join(path), 64)?; files.push(ManifestFile { path: path.clone(), @@ -655,12 +682,16 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { rec.blocks.push(e); } for b in packed.new_blocks { - if new_block_shas.insert(b.sha256.clone()) { - new_blocks.push(b); + let sha = b.sha256; + if uploaded.contains(&sha) { + continue; } + upload_block(&client, &base, &session_id, &sha, b.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded block {}", &sha[..16]); } - // Make this file's fresh chunks visible to the next file's dedup. - dedup.add(&rec); } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. @@ -669,13 +700,15 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { .iter() .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) .collect(); + let mut present: HashSet = rec.blocks.iter().map(|b| b.sha256.clone()).collect(); for sha in needed { - if rec.blocks.iter().any(|b| b.sha256 == sha) { + if present.contains(&sha) { continue; } let entry = all_entries .get(&sha) .with_context(|| format!("term references unknown block {sha}"))?; + present.insert(entry.sha256.clone()); rec.blocks.push(entry.clone()); } // A release with no chunked files has no chunked bytes to reconstruct: @@ -690,69 +723,24 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { }; let rec_sha = sha256_hex(&rec_bytes); - // 5. Open (or resume) the upload session and send the new blocks, then - // the reconstruction object as one more block. - let state_path = git_dir.join(STATE_FILE_NAME); - let mut state = load_state(&state_path); - if !state.session_id.is_empty() { - let resp = client - .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) - .await - .context("session status request failed")?; - if resp.status() == reqwest::StatusCode::NOT_FOUND { - state = PublishState::default(); - } else { - let v: Value = read_json(resp, "session status").await?; - if v["state"].as_str() != Some("open") { - state = PublishState::default(); - } - } - } - if state.session_id.is_empty() { - let body = serde_json::to_vec(&json!({ - "parent_release": parent_ref.as_ref().map(|p| p.commit.clone()), - }))?; - let resp = client - .post(&format!("{base}/models/sessions"), &body) - .await?; - let v: Value = json_or_denial("open model session", resp).await?; - state.session_id = v["session_id"] - .as_str() - .context("session response had no session_id")? - .to_string(); - state.uploaded.clear(); - save_state(&state_path, &state)?; - } - let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); - let session_id = state.session_id.clone(); - - let total = new_blocks.len() + usize::from(!rec_bytes.is_empty()); - for (i, block) in new_blocks.into_iter().enumerate() { - let sha = block.sha256; - if uploaded.contains(&sha) { - continue; - } - upload_block(&client, &base, &session_id, &sha, block.data).await?; - state.uploaded.push(sha.clone()); - uploaded.insert(sha); - save_state(&state_path, &state)?; - println!("uploaded block {}/{total}", i + 1); - } - if !rec_bytes.is_empty() && !uploaded.contains(&rec_sha) { - upload_block(&client, &base, &session_id, &rec_sha, rec_bytes.clone()).await?; + // 6. The reconstruction object goes up as one more content block. + let has_rec = !rec_bytes.is_empty(); + let rec_size = rec_bytes.len() as u64; + if has_rec && !uploaded.contains(&rec_sha) { + upload_block(&client, &base, &session_id, &rec_sha, rec_bytes).await?; state.uploaded.push(rec_sha.clone()); save_state(&state_path, &state)?; - println!("uploaded reconstruction object ({total}/{total})"); + println!("uploaded reconstruction object"); } - // 6. Managed .gitignore block, then stage the publishable set. + // 7. Managed .gitignore block, then stage the publishable set. let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); if new_gitignore != existing_gitignore { std::fs::write(&gitignore_path, &new_gitignore)?; } git(&root, &["add", "-A"])?; - // 7. Hash the git-stored files from the index (the exact bytes the + // 8. Hash the git-stored files from the index (the exact bytes the // commit stores), then write and stage the manifest. for path in &scan.git_files { let bytes = staged_blob(&root, path)?; @@ -773,12 +761,12 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { license: args.license.clone(), parent: parent_ref, files, - reconstruction: if rec_bytes.is_empty() { + reconstruction: if !has_rec { None } else { Some(ReconstructionRef { sha256: rec_sha, - size: rec_bytes.len() as u64, + size: rec_size, }) }, }; @@ -790,14 +778,27 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; std::fs::write( twigpine_dir.join("model-release.sig"), - format!("{}\n", sign_manifest_bytes(&kp, &manifest_bytes)), + format!( + "{}\n", + manifest::sign( + &ed25519_dalek::SigningKey::from_bytes(&kp.to_seed()), + &manifest_bytes, + ) + ), + )?; + git( + &root, + &[ + "add", + ".twigpine/model-release.json", + ".twigpine/model-release.sig", + ], )?; - git(&root, &["add", "-A"])?; - // 8. Commit when the index differs, push, and claim HEAD. + // 9. Commit when the index differs, push, and claim HEAD. let has_changes = git(&root, &["diff", "--cached", "--quiet"]).is_err(); if has_changes { - let n = release_commits(&root).len() + 1; + let n = prior_commits.len() + 1; git(&root, &["commit", "-m", &format!("model release {n}")])?; } else { // Nothing staged: a re-publish of identical content lands here, and @@ -844,7 +845,7 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let release_id = claim["release_id"].as_i64().unwrap_or_default(); println!("release {release_id} claimed; verifying"); - // 9. Poll until the verification worker settles the release. + // 10. Poll until the verification worker settles the release. let release_path = format!("{base}/models/releases/{commit}"); let deadline = Instant::now() + POLL_BUDGET; loop { @@ -886,22 +887,25 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { mod tests { use super::*; - const T: u64 = 1024; // test threshold + const THR: u64 = 1024; #[test] fn classify_by_threshold_tracking_and_ignore() { // Below threshold: tracked or unignored-untracked are git files. - assert_eq!(classify(T - 1, true, false, false, T), Class::Git); - assert_eq!(classify(T - 1, false, false, false, T), Class::Git); - assert_eq!(classify(T - 1, false, true, false, T), Class::Ignored); - assert_eq!(classify(T - 1, false, true, true, T), Class::Ignored); + assert_eq!(classify(THR - 1, true, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, true, false, THR), Class::Ignored); + assert_eq!(classify(THR - 1, false, true, true, THR), Class::Ignored); // At/above threshold: tracked refuses; untracked chunks unless // ignored outside the managed block. - assert_eq!(classify(T, true, false, false, T), Class::LargeTracked); - assert_eq!(classify(T + 1, true, true, false, T), Class::LargeTracked); - assert_eq!(classify(T, false, false, false, T), Class::Chunked); - assert_eq!(classify(T, false, true, true, T), Class::Chunked); - assert_eq!(classify(T, false, true, false, T), Class::Ignored); + assert_eq!(classify(THR, true, false, false, THR), Class::LargeTracked); + assert_eq!( + classify(THR + 1, true, true, false, THR), + Class::LargeTracked + ); + assert_eq!(classify(THR, false, false, false, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, true, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, false, THR), Class::Ignored); } #[test] @@ -1036,32 +1040,6 @@ mod tests { ); } - #[test] - fn cli_signature_matches_manifest_sign() { - // The two paths sign the same domain-tagged bytes with the same key: - // manifest::sign takes a raw SigningKey, the CLI signs through Keypair. - let seed = [9u8; 32]; - let signing = ed25519_dalek::SigningKey::from_bytes(&seed); - let kp = twigpine_core::identity::Keypair::from_seed(&seed).unwrap(); - let m = Manifest { - schema: MANIFEST_SCHEMA_V1.to_string(), - repo: "alice/m".to_string(), - publisher_did: kp.did().to_string(), - license: "mit".to_string(), - parent: None, - files: vec![], - reconstruction: Some(ReconstructionRef { - sha256: "a".repeat(64), - size: 1, - }), - }; - let bytes = m.to_bytes().unwrap(); - let sig = sign_manifest_bytes(&kp, &bytes); - assert_eq!(sig, manifest::sign(&signing, &bytes)); - let parsed = manifest::verify(&bytes, &sig, &kp.did()).unwrap(); - assert_eq!(parsed.repo, "alice/m"); - } - #[test] fn remote_url_parses_both_schemes() { assert_eq!( diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 70d2a33e..97f391bb 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -182,7 +182,13 @@ impl DedupIndex { } pub fn add(&mut self, rec: &Reconstruction) { - for block in &rec.blocks { + self.add_block_entries(&rec.blocks); + } + + /// Index only `entries`: callers packing several files can add each + /// file's fresh block table instead of re-scanning every prior entry. + pub fn add_block_entries(&mut self, entries: &[BlockEntry]) { + for block in entries { for (i, chunk) in block.chunks.iter().enumerate() { // First writer wins: two priors carrying the same chunk are // interchangeable, so keep the earliest. diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index d20007e2..9c2e7c35 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -48,14 +48,6 @@ fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result Ok(()) } -#[derive(Debug, Deserialize, Default)] -pub struct OpenSessionBody { - /// Optional commit sha of the declared parent release. Informational at - /// open time; the claim re-anchors the parent through the manifest. - #[serde(default)] - pub parent_release: Option, -} - /// POST `/api/v1/repos/{owner}/{repo}/models/sessions` — open an upload /// session. Owner-only (a session writes bytes the owner is billed for) on a /// fully public repo. @@ -63,20 +55,17 @@ pub async fn open_model_session( State(state): State, Path((owner, name)): Path<(String, String)>, Extension(auth): Extension, - _body: Option>, + _body: Option>, ) -> Result { hosting_enabled(&state)?; let caller = &auth.0; let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; require_repo_owner(&record, caller)?; require_fully_public(&record, &rules)?; - let session = models::open_session( - &state.db, - caller, - &record.id, - state.config.model_session_ttl_secs, - ) - .await?; + let session = state + .db + .model_open_session(caller, &record.id, state.config.model_session_ttl_secs) + .await?; Ok(( axum::http::StatusCode::CREATED, Json(json!({ @@ -97,7 +86,9 @@ pub async fn get_model_session( let caller = &auth.0; let (record, _rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; require_repo_owner(&record, caller)?; - let session = models::load_session(&state.db, &id) + let session = state + .db + .model_load_session(&id) .await? .filter(|s| s.repo_id == record.id) .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; @@ -130,8 +121,8 @@ pub async fn put_model_block( "a model block PUT requires the session header".into(), )); }; - let pool = &state.db; - let Some(session) = models::load_session(pool, &session_id).await? else { + let db = &state.db; + let Some(session) = db.model_load_session(&session_id).await? else { return Err(AppError::NotFound("model upload session not found".into())); }; // authorize_repo_read 404s a repo the session owner can no longer read; @@ -168,19 +159,20 @@ pub async fn put_model_block( // node-wide quota, and it slides the session expiry in the same write. let session_cap = state.config.effective_model_max_session_bytes() as i64; let node_cap = state.config.model_node_quota_bytes as i64; - let Some(_) = models::admit_bytes( - pool, - &session.id, - declared as i64, - state.config.model_session_ttl_secs, - session_cap, - node_cap, - ) - .await? + let Some(_) = db + .model_admit_bytes( + &session.id, + declared as i64, + state.config.model_session_ttl_secs, + session_cap, + node_cap, + ) + .await? else { // Not admitted: re-check whether the session died (404 hides the // session) or a cap refused (named quota). - let session = models::load_session(pool, &session_id) + let session = db + .model_load_session(&session_id) .await? .filter(|s| s.state == "open" && s.expires_at > models::ts_now()); return match session { @@ -197,49 +189,48 @@ pub async fn put_model_block( .into_body() .into_data_stream() .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); - let outcome = store + if let Err(e) = store .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) - .await; - let outcome = match outcome { - Ok(o) => o, - Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; - return Err(match e { - BlockStoreError::DigestMismatch => { - AppError::BadRequest(format!("block body does not hash to the named id {sha}")) - } - BlockStoreError::TooLarge(cap) => { - AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) - } - BlockStoreError::Unknown => AppError::Conflict( - "the write's outcome is unknown; check the object before retrying".into(), - ), - other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), - }); - } - }; - let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. + .await + { + let _ = db.model_refund_bytes(&session.id, declared as i64).await; + return Err(match e { + BlockStoreError::DigestMismatch => { + AppError::BadRequest(format!("block body does not hash to the named id {sha}")) + } + BlockStoreError::TooLarge(cap) => { + AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + } + BlockStoreError::Unknown => AppError::Conflict( + "the write's outcome is unknown; check the object before retrying".into(), + ), + other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), + }); + } + // Stored and AlreadyPresent both leave the bytes stored. // Past this point the object exists; a bookkeeping failure must refund // the admission or the session's charge leaks until it expires. let size = match store.size(&block_id).await { Ok(s) => s.unwrap_or(declared), Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + let _ = db.model_refund_bytes(&session.id, declared as i64).await; return Err(AppError::Internal(anyhow::anyhow!( "block size lookup failed: {e}" ))); } }; - let duplicate = match models::record_block(pool, &session.id, &sha, size, declared as i64).await + let duplicate = match db + .model_record_block(&session.id, &sha, size, declared as i64) + .await { Ok(d) => d, Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; - return Err(e); + let _ = db.model_refund_bytes(&session.id, declared as i64).await; + return Err(e.into()); } }; - let fresh = models::load_session(pool, &session.id).await?; + let fresh = db.model_load_session(&session.id).await?; Ok(Json(json!({ "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), "duplicate": duplicate, @@ -327,7 +318,9 @@ pub async fn get_model_release( let caller = auth.map(|Extension(AuthenticatedDid(d))| d); let (record, _rules) = authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; - let release = models::release_by_commit(&state.db, &record.id, &commit) + let release = state + .db + .model_release_by_commit(&record.id, &commit) .await? .ok_or_else(|| AppError::NotFound("model release not found".into()))?; Ok(Json(release_view(&release))) @@ -350,25 +343,30 @@ pub async fn get_model_reconstruction( if !record.is_public || !rules.is_empty() { return Err(AppError::NotFound("model release not found".into())); } - let release = models::release_by_commit(&state.db, &record.id, &commit) + let release = state + .db + .model_release_by_commit(&record.id, &commit) .await? .filter(|r| r.state == "published") .ok_or_else(|| AppError::NotFound("model release not found".into()))?; - let (manifest_bytes, manifest) = models::claim::read_verified_manifest( - &state.git_bin, - &std::path::PathBuf::from(&record.disk_path), - &release.commit_sha, - &record.owner_did, - ) - .await?; - let _ = manifest_bytes; - let Some(rec_ref) = &manifest.reconstruction else { + // The stored reconstruction ref was bound when the release verified; + // re-reading and re-verifying the manifest per GET is wasted work. + let Some(sha) = state.db.model_reconstruction_sha(release.id).await? else { return Err(AppError::NotFound( "release has no reconstruction object".into(), )); }; let store = state.block_store.clone().expect("checked above"); - let bytes = models::read_block(&store, &rec_ref.sha256, rec_ref.size) + let size = store + .size( + &BlockId::parse(&sha) + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?, + ) + .await + .ok() + .flatten() + .ok_or_else(|| AppError::NotFound("reconstruction object not stored".into()))?; + let bytes = models::read_block(&store, &sha, size) .await .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; Ok(( diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 0fe0d0d9..3fb66e3c 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -524,13 +524,13 @@ pub struct MarkerCleanup { pub dead_letter: bool, } +pub mod model_queries; + /// The lifecycle states of a row in `pending_ref_transitions`. Persisted as a /// TEXT column with one of these string values; the constants are the canonical /// spellings, and tests + the recovery drain all use them so a typo on one /// side or the other cannot silently mismatch the other. #[allow(dead_code)] // constants are used by tests + the next-slice handler -pub mod model_queries; - pub mod pending_state { #[allow(dead_code)] pub const PREPARED: &str = "prepared"; diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 2244b6ce..272c96ec 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -1,13 +1,11 @@ //! Model-hosting queries. Timestamps follow the repo convention: rfc3339 //! text in TEXT columns, written and compared through the helpers here. -#[cfg(any(test, feature = "test-harness"))] -use sqlx::PgPool; use sqlx::{Postgres, Transaction}; use super::{Db, Result}; -fn ts_now() -> String { +pub(crate) fn ts_now() -> String { chrono::Utc::now().to_rfc3339() } @@ -258,6 +256,19 @@ impl Db { Ok(row.map(Into::into)) } + /// The reconstruction object sha a release was claimed with, if any. + /// The reconstruction GET serves by this stored ref: the manifest it + /// names is immutable under the pinned commit and was verified at claim. + pub async fn model_reconstruction_sha(&self, id: i64) -> Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT reconstruction_sha256 FROM model_releases WHERE id = $1", + ) + .bind(id) + .fetch_optional(&self.pool) + .await? + .flatten()) + } + pub async fn model_release_by_id(&self, id: i64) -> Result> { let row = sqlx::query_as::<_, ReleaseTuple>(&format!( "SELECT {RELEASE_COLS} FROM model_releases WHERE id = $1" @@ -499,31 +510,36 @@ impl Db { Ok(row.into()) } - /// Link `sha` to the release and drop it from the publisher's open - /// sessions, so the same bytes stop counting twice node-wide. - pub async fn model_tx_link_release_block( + /// Link `shas` to the release and drop them from the publisher's open + /// sessions, so the same bytes stop counting twice node-wide. Batched: + /// this runs inside the claim's advisory lock, so a manifest naming + /// thousands of blocks must not pay two round trips per block. + pub async fn model_tx_link_release_blocks( &self, tx: &mut Transaction<'_, Postgres>, release_id: i64, publisher_did: &str, - sha: &str, + shas: &[String], ) -> Result<()> { + if shas.is_empty() { + return Ok(()); + } sqlx::query( "INSERT INTO model_release_blocks (release_id, block_sha256) - VALUES ($1, $2) ON CONFLICT DO NOTHING", + SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING", ) .bind(release_id) - .bind(sha) + .bind(shas) .execute(&mut **tx) .await?; sqlx::query( "DELETE FROM model_session_blocks sb USING model_upload_sessions s WHERE s.id = sb.session_id AND s.owner_did = $1 - AND s.state = 'open' AND sb.block_sha256 = $2", + AND s.state = 'open' AND sb.block_sha256 = ANY($2)", ) .bind(publisher_did) - .bind(sha) + .bind(shas) .execute(&mut **tx) .await?; Ok(()) @@ -637,9 +653,9 @@ impl Db { .await?) } - pub async fn model_drop_session_blocks(&self, session_id: &str) -> Result<()> { - sqlx::query("DELETE FROM model_session_blocks WHERE session_id = $1") - .bind(session_id) + pub async fn model_drop_sessions_blocks(&self, session_ids: &[String]) -> Result<()> { + sqlx::query("DELETE FROM model_session_blocks WHERE session_id = ANY($1)") + .bind(session_ids) .execute(&self.pool) .await?; Ok(()) @@ -735,12 +751,6 @@ impl Db { } } -/// The PgPool behind a `Db`, for test fixtures that seed rows directly. -#[cfg(any(test, feature = "test-harness"))] -pub fn test_pool(db: &Db) -> &PgPool { - db.pool() -} - #[cfg(test)] mod tests { use super::*; @@ -762,17 +772,14 @@ mod tests { #[sqlx::test] async fn admit_bytes_enforces_session_cap_and_slides_expiry(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; - let s = db - .model_open_session("did:owner", "r1", 3600) - .await - .unwrap(); + let s = db.model_open_session("did:owner", "r1", 60).await.unwrap(); let first = db .model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) .await .unwrap() .expect("first admission"); assert_eq!(first.bytes_received, 100); - assert!(first.expires_at >= s.expires_at); + assert!(first.expires_at > s.expires_at); // Over the per-identity session cap: refused. assert!(db .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) @@ -795,11 +802,21 @@ mod tests { .await .unwrap(); let sha = "a".repeat(64); + // First PUT: admit the block's bytes, then record the link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); assert!(!db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); - // Same block again: duplicate, admission refunded. + // Same block again: the second admission is charged then refunded + // when the record sees the existing link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("second admission"); assert!(db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); let s2 = db.model_load_session(&s.id).await.unwrap().unwrap(); - assert_eq!(s2.bytes_received, 0); + assert_eq!(s2.bytes_received, 100); } #[sqlx::test] @@ -834,7 +851,9 @@ mod tests { db.model_expire_sessions().await.unwrap(), vec![s.id.clone()] ); - db.model_drop_session_blocks(&s.id).await.unwrap(); + db.model_drop_sessions_blocks(std::slice::from_ref(&s.id)) + .await + .unwrap(); // The block is now unreferenced: marked, then deletable past grace. assert_eq!(db.model_remark_liveness().await.unwrap(), 1); diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 52da7912..d2628d33 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -1,6 +1,16 @@ use anyhow::{bail, Context, Result}; use std::path::Path; use std::process::Command; +/// Ref namespaces clients must never see: `refs/gitlawb/requests/*` is +/// internal bookkeeping, and `refs/gitlawb/releases/*` pins published model +/// releases so gc never prunes them. One shared list keeps the +/// repo-config writers in lockstep. +const HIDDEN_REFS: &[(&str, &str)] = &[ + ("uploadpack.hideRefs", "refs/gitlawb/requests/"), + ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), +]; /// Initialize a new bare git repository with SHA-1 object format (default). /// @@ -88,18 +98,11 @@ pub fn init_bare(path: &Path) -> Result<()> { Ok(_) => {} } - // Hide the internal marker namespace from clone/fetch - // advertisement. `refs/gitlawb/requests/*` carries request UUIDs - // and would otherwise leak per-push metadata to every client and - // grow advertisement cost with push count. `refs/gitlawb/releases/*` - // pins published model releases so gc never prunes them; it is - // likewise not for clients. - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + // Hide the internal marker namespaces from clone/fetch + // advertisement: `refs/gitlawb/requests/*` would leak per-push + // metadata to every client and grow advertisement cost with push + // count. + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: same init-time local `git config` as above. let out = Command::new("git") .args(["config", "--add", key, value]) @@ -130,12 +133,7 @@ pub fn ensure_marker_hidden(repo_path: &Path) { } pub fn ensure_marker_hidden_checked(repo_path: &Path) -> Result<()> { - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: reached only through the #[allow(dead_code)] // ensure_marker_hidden wrapper; the push path runs this config through // verify_recovery_prereqs_bounded's timeout runner. @@ -218,12 +216,7 @@ pub async fn verify_recovery_prereqs_bounded( ); } } - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + for &(key, value) in HIDDEN_REFS { let current = run_git(git_bin, repo_path, &["config", "--get-all", key], timeout).await?; let already = String::from_utf8_lossy(¤t.stdout) .lines() diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 5d92cca8..84db6791 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -26,7 +26,6 @@ fn bad_request(msg: impl Into) -> AppError { AppError::BadRequest(msg.into()) } -/// Read `commit:path` bytes from the repo on disk, bounded. pub(crate) async fn git_show( git_bin: &str, disk_path: &std::path::Path, @@ -60,7 +59,6 @@ pub(crate) async fn git_show( } } -/// Whether commit `sha` resolves in the repo. pub async fn commit_exists( git_bin: &str, disk_path: &std::path::Path, @@ -117,13 +115,12 @@ pub async fn claim_release( let db = &state.db; let disk_path = std::path::PathBuf::from(&record.disk_path); - // The pushed commit must exist and carry the signed manifest. if !commit_exists(&state.git_bin, &disk_path, commit).await? { return Err(bad_request("commit not found in this repository")); } let (manifest_bytes, manifest) = read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; - let m_sha = super::manifest_sha256(&manifest_bytes); + let m_sha = twigpine_core::cid::sha256_hex(&manifest_bytes); let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); let blocks = super::referenced_blocks(state, &manifest).await?; @@ -150,8 +147,12 @@ pub async fn claim_release( // Lock the referenced block rows so a racing sweep cannot delete one // mid-claim, and require each to exist. if !blocks.is_empty() { - let present = db.model_tx_lock_present_blocks(&mut tx, &blocks).await?; - if let Some(missing) = blocks.iter().find(|b| !present.contains(b)) { + let present: std::collections::HashSet = db + .model_tx_lock_present_blocks(&mut tx, &blocks) + .await? + .into_iter() + .collect(); + if let Some(missing) = blocks.iter().find(|b| !present.contains(b.as_str())) { return Err(bad_request(format!( "manifest references block {} which is not stored on this node", &missing[..16] @@ -161,12 +162,18 @@ pub async fn claim_release( // Authorization: every referenced block must arrive through the caller's // open session, a live release of the caller's, or the declared parent. - let caller_session_blocks = db.model_tx_session_blocks(&mut tx, caller).await?; - let caller_release_blocks = db + let caller_session_blocks: std::collections::HashSet = db + .model_tx_session_blocks(&mut tx, caller) + .await? + .into_iter() + .collect(); + let caller_release_blocks: std::collections::HashSet = db .model_tx_publisher_release_blocks(&mut tx, caller) - .await?; - let parent_blocks: Vec = match &manifest.parent { - None => Vec::new(), + .await? + .into_iter() + .collect(); + let parent_blocks: std::collections::HashSet = match &manifest.parent { + None => std::collections::HashSet::new(), Some(parent) => { let (powner, pname) = parent .repo @@ -189,7 +196,7 @@ pub async fn claim_release( "declared parent is not a published release on this node", )); } - rows + rows.into_iter().collect() } }; for b in &blocks { @@ -258,12 +265,10 @@ pub async fn claim_release( .await?; let release_id = row.id; - for b in &blocks { - // Claimed blocks leave the caller's open sessions' charge: the - // release now carries them, so session bytes stop double-counting. - db.model_tx_link_release_block(&mut tx, release_id, caller, b) - .await?; - } + // Claimed blocks leave the caller's open sessions' charge: the + // release now carries them, so session bytes stop double-counting. + db.model_tx_link_release_blocks(&mut tx, release_id, caller, &blocks) + .await?; db.model_tx_recount_open_session_bytes(&mut tx, caller) .await?; diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index ee45d2b5..dfee0f64 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -4,8 +4,8 @@ //! re-checks it. //! //! All SQL lives in `crate::db::model_queries` as typed `Db` methods; the -//! free functions here are the thin `&Db`-taking seams the handlers and -//! workers share. +//! free functions here are the store read helpers the handlers and workers +//! share. pub mod claim; pub mod sweep; @@ -13,11 +13,12 @@ pub mod verify; use std::sync::Arc; -use crate::db::model_queries::{ModelRelease, ModelSession}; -use crate::db::Db; +use crate::db::model_queries::ModelRelease; use crate::error::AppError; use crate::state::AppState; +pub(crate) use crate::db::model_queries::ts_now; + /// Transport + store hard cap on one block (KTD1: 64 MiB target, 128 MiB cap). pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; @@ -26,98 +27,8 @@ pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; /// lock is what makes them safe under racing claims. pub(crate) const CLAIM_LOCK_KEY: i64 = 0x6D6F64656C636C61; // "modelcla" -pub type SessionRow = ModelSession; pub type ReleaseRow = ModelRelease; -/// rfc3339 UTC `secs` from now: the repo's TEXT timestamp convention. -pub fn ts_from_now(secs: i64) -> String { - (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() -} - -pub fn ts_now() -> String { - chrono::Utc::now().to_rfc3339() -} - -/// 256-bit random session id, hex-encoded: the bearer capability for block -/// PUTs. Anyone holding it may append blocks to the session it names, so it -/// is never logged or returned to anyone but its creator. -pub fn new_session_id() -> String { - hex::encode(rand::random::<[u8; 32]>()) -} - -pub async fn open_session( - db: &Db, - owner_did: &str, - repo_id: &str, - ttl_secs: u64, -) -> Result { - Ok(db.model_open_session(owner_did, repo_id, ttl_secs).await?) -} - -pub async fn load_session(db: &Db, id: &str) -> Result, AppError> { - Ok(db.model_load_session(id).await?) -} - -/// Atomically admit `claimed` bytes against the caller's per-identity -/// open-session cap and the node-wide quota (claimed quota plus every open -/// session's bytes), sliding the session's expiry forward in the same -/// update. Returns the post-update row when admitted, `None` when the -/// session is closed, expired, or the admission would exceed a cap; the -/// caller re-checks the session to pick the honest denial. -pub async fn admit_bytes( - db: &Db, - session_id: &str, - claimed: i64, - ttl_secs: u64, - session_cap: i64, - node_cap: i64, -) -> Result, AppError> { - Ok(db - .model_admit_bytes(session_id, claimed, ttl_secs, session_cap, node_cap) - .await?) -} - -/// Refund a previously admitted charge when the store or the bookkeeping -/// fails. Best-effort under races; an expired session frees the bytes anyway. -pub async fn refund_bytes(db: &Db, session_id: &str, bytes: i64) -> Result<(), AppError> { - db.model_refund_bytes(session_id, bytes).await?; - Ok(()) -} - -/// Book the stored block against the session inside one transaction. Returns -/// `true` when this PUT was a duplicate within the session (the admission -/// credit was refunded). -pub async fn record_block( - db: &Db, - session_id: &str, - block_sha: &str, - size: u64, - admitted: i64, -) -> Result { - Ok(db - .model_record_block(session_id, block_sha, size, admitted) - .await?) -} - -pub async fn release_by_commit( - db: &Db, - repo_id: &str, - commit: &str, -) -> Result, AppError> { - Ok(db.model_release_by_commit(repo_id, commit).await?) -} - -pub async fn release_by_id(db: &Db, id: i64) -> Result, AppError> { - Ok(db.model_release_by_id(id).await?) -} - -/// sha256 of the manifest bytes, as hex. -pub fn manifest_sha256(manifest_bytes: &[u8]) -> String { - use sha2::Digest; - hex::encode(sha2::Sha256::digest(manifest_bytes)) -} - -/// Collect `len` bytes of a stored object starting at `start`. pub async fn read_range( store: &Arc, sha: &str, @@ -135,7 +46,6 @@ pub async fn read_range( Ok(out) } -/// Collect a stored object's whole body via a range read. pub async fn read_block( store: &Arc, sha: &str, diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index c11f6ea9..00202bfa 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -24,9 +24,7 @@ pub async fn sweep_once(state: &AppState) -> Result { // session no longer confers liveness. let expired = db.model_expire_sessions().await?; stats.sessions_expired = expired.len() as u64; - for sid in &expired { - db.model_drop_session_blocks(sid).await?; - } + db.model_drop_sessions_blocks(&expired).await?; // Re-mark liveness both ways: blocks that lost every live reference get // an unreferenced_since stamp; blocks that regained one clear theirs. diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 5a823e36..ae35c3bb 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -3,6 +3,7 @@ //! then mark the release published (and pin the hidden ref). Rejection frees //! the quota reservation and drops the block refs. +use futures::StreamExt; use sha2::Digest; use std::io::Write; use twigpine_core::model::manifest::{detect_format, StorageKind}; @@ -34,7 +35,7 @@ impl Write for VerifySink { /// Verify one release end to end. Idempotent: a release no longer in /// `verifying` returns immediately. pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), AppError> { - let Some(release) = super::release_by_id(&state.db, release_id).await? else { + let Some(release) = state.db.model_release_by_id(release_id).await? else { return Ok(()); }; if release.state != "verifying" { @@ -68,7 +69,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await; } }; - if super::manifest_sha256(&manifest_bytes) != release.manifest_sha256 { + if twigpine_core::cid::sha256_hex(&manifest_bytes) != release.manifest_sha256 { return reject_release(state, release_id, "manifest digest changed since claim").await; } @@ -102,10 +103,12 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App } }; + let rec_by_path: std::collections::HashMap<&str, _> = + rec.files.iter().map(|f| (f.path.as_str(), f)).collect(); for file in &manifest.files { match file.storage { StorageKind::Chunked => { - let Some(entry) = rec.files.iter().find(|f| f.path == file.path).cloned() else { + let Some(&entry) = rec_by_path.get(file.path.as_str()) else { return reject_release( state, release_id, @@ -126,7 +129,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // backend. Blocks were hash-verified at write, so the // whole-file digest is the check that matters here. let slices = match twigpine_core::model::reconstruction::map_file_range( - &entry, &rec, 0, file.size, + entry, &rec, 0, file.size, ) { Ok(s) => s, Err(e) => { @@ -142,15 +145,22 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App hasher: sha2::Sha256::new(), head: Vec::new(), }; - for slice in &slices { - let bytes = match super::read_range( - &store, - &slice.block, - slice.offset, - slice.len, - ) - .await - { + // Ordered prefetch: `buffered` preserves order while + // overlapping the store's per-slice round trips. + let jobs = slices + .iter() + .map(|s| (s.block.clone(), s.offset, s.len)) + .collect::>(); + let fetched = + futures::stream::iter(jobs.into_iter().map(|(block, offset, len)| { + let store = store.clone(); + async move { super::read_range(&store, &block, offset, len).await } + })) + .buffered(4) + .collect::>() + .await; + for bytes in fetched { + let bytes = match bytes { Ok(b) => b, Err(e) => { return reject_release( @@ -197,7 +207,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await { Ok(Some(bytes)) => { - let got = hex::encode(sha2::Sha256::digest(&bytes)); + let got = twigpine_core::cid::sha256_hex(&bytes); if got != file.sha256 || bytes.len() as u64 != file.size { return reject_release( state, diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index 236641f4..0d3116a4 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -9,20 +9,14 @@ mod support; use serde_json::{json, Value}; -use sha2::Digest; +use support::bounded_client; use support::signing::signed_request; +use twigpine_core::cid::sha256_hex; use twigpine_core::http_sig::sign_request; use twigpine_core::identity::Keypair; use twigpine_node::test_harness::{spawn_node, TestNode}; -fn bounded_client() -> reqwest::Client { - reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(30)) - .build() - .expect("client builds") -} - fn sessions_path(owner: &str, repo: &str) -> String { format!("/api/v1/repos/{owner}/{repo}/models/sessions") } @@ -330,7 +324,7 @@ async fn put_block_without_session_header_unauthorized(pool: sqlx::PgPool) { let client = bounded_client(); let owner_did = Keypair::generate().did().to_string(); node.seed_repo(&owner_did, "model", true).await; - let sha = hex::encode(sha2::Sha256::digest(b"block")); + let sha = sha256_hex(b"block"); let resp = put_block( &client, @@ -356,7 +350,7 @@ async fn put_block_bogus_session_not_found(pool: sqlx::PgPool) { let owner_did = Keypair::generate().did().to_string(); node.seed_repo(&owner_did, "model", true).await; let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -384,7 +378,7 @@ async fn put_block_session_for_other_repo_not_found(pool: sqlx::PgPool) { node.seed_repo(&owner_did, "model-b", true).await; let session_id = seed_open_session(&node, &repo_a, &owner_did).await; let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -410,21 +404,16 @@ async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { let owner_did = Keypair::generate().did().to_string(); let repo_id = node.seed_repo(&owner_did, "model", true).await; let session_id = "e".repeat(64); - sqlx::query( - "INSERT INTO model_upload_sessions - (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) - VALUES ($1,$2,$3,$4,$5,0,'open')", - ) - .bind(&session_id) - .bind(&owner_did) - .bind(&repo_id) - .bind(chrono::Utc::now().to_rfc3339()) - .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) - .execute(&pool) - .await - .expect("seed expired session"); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -441,10 +430,6 @@ async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { node.shutdown().await; } -/// Happy path: a block whose body hashes to the id in the path is stored, -/// reported with the session's running byte count and `duplicate:false`; -/// resending it reports `duplicate:true`; a body that does not match the -/// named id is refused with 400. #[sqlx::test] async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) { let node = spawn_node(pool).await; @@ -454,7 +439,7 @@ async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) let session_id = seed_open_session(&node, &repo_id, &owner_did).await; let body = b"the quick brown fox".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, &node.base_url, @@ -728,3 +713,72 @@ async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { node.shutdown().await; } + +/// The reconstruction GET and the claims POST hide a repo that is not fully +/// public: every caller class gets the same 404, none reach the store or the +/// commit lookup. The deny sweep cannot drive the hostile-only legs for the +/// reconstruction route, so they live here. +#[sqlx::test] +async fn reconstruction_and_claims_deny_on_private_repo(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + let commit = "c".repeat(40); + let rec_path = format!( + "{}/reconstruction", + release_path(&owner_did, "model", &commit) + ); + + for (label, req) in [ + ( + "anon GET reconstruction", + client.get(format!("{}{}", node.base_url, rec_path)), + ), + ( + "stranger GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &stranger, + ), + ), + ( + "owner GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &owner, + ), + ), + ( + "stranger POST claims", + signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + serde_json::to_vec(&serde_json::json!({ + "commit": commit, + "branch": "main", + })) + .expect("claim body"), + &stranger, + ) + .header("content-type", "application/json"), + ), + ] { + let resp = req.send().await.expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "{label}"); + } + + node.shutdown().await; +} diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 07f8c411..4cf536ba 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -1055,7 +1055,9 @@ pub fn deny_bearing_routes() -> &'static [Row] { gate: GateClass::OwnerGate, handler: "models::claim_model_release", // A well-formed claim body; the owner twin passes the owner gate and - // fails the commit lookup (400), which is still a Not403 twin. + // fails the commit lookup (the seeded placeholder disk_path makes + // it a 500 today, a real on-disk repo would make it 400), which is + // still a Not403 twin. body: Some(r#"{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","branch":"main"}"#), needs: NO_ENTITY, reach: Reach::None, From 0e7fb3c43e74cfc92976d8eb06f391d88747c7e1 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:28:21 -0600 Subject: [PATCH 12/20] fix(node): harden model publishing after the review pass 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. --- crates/twigpine-cli/src/model.rs | 164 +++++++++++++--- .../twigpine-core/src/model/reconstruction.rs | 83 ++++++--- crates/twigpine-node/src/api/models.rs | 23 ++- crates/twigpine-node/src/blockstore/fs.rs | 2 +- crates/twigpine-node/src/blockstore/mod.rs | 4 + crates/twigpine-node/src/blockstore/s3.rs | 2 +- crates/twigpine-node/src/db/model_queries.rs | 154 +++++++++++---- crates/twigpine-node/src/git/store.rs | 2 +- crates/twigpine-node/src/models/claim.rs | 101 ++++++---- crates/twigpine-node/src/models/mod.rs | 5 +- crates/twigpine-node/src/models/sweep.rs | 11 ++ crates/twigpine-node/src/models/verify.rs | 176 +++++++++++++++--- 12 files changed, 566 insertions(+), 161 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index ea2edbd7..9805a892 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -22,7 +22,9 @@ use twigpine_core::model::manifest::{ self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, }; -use twigpine_core::model::reconstruction::{pack_file, BlockEntry, DedupIndex, Reconstruction}; +use twigpine_core::model::reconstruction::{ + pack_file_with, BlockEntry, DedupIndex, Reconstruction, +}; use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; use crate::identity::load_keypair_from_dir; @@ -270,6 +272,39 @@ fn tracked_paths(root: &Path) -> Result> { /// Paths listed inside the managed .gitignore block (empty when there is no /// block): previously published chunked files. +/// One repo-relative path as a gitignore pattern line: pattern +/// metacharacters and a trailing space are backslash-escaped. +fn escape_gitignore_path(p: &str) -> String { + let mut out = String::new(); + let mut chars = p.chars().peekable(); + while let Some(c) = chars.next() { + if matches!(c, '\\' | '!' | '#' | '[' | ']') { + out.push('\\'); + } + if c == ' ' && chars.peek().is_none() { + out.push('\\'); + } + out.push(c); + } + out +} + +fn unescape_gitignore_path(line: &str) -> String { + let mut out = String::new(); + let mut escaped = false; + for c in line.chars() { + if escaped { + out.push(c); + escaped = false; + } else if c == '\\' { + escaped = true; + } else { + out.push(c); + } + } + out +} + fn managed_block_paths(gitignore: &str) -> Vec { let mut inside = false; let mut out = Vec::new(); @@ -283,7 +318,7 @@ fn managed_block_paths(gitignore: &str) -> Vec { break; } if inside && !t.is_empty() { - out.push(t.to_string()); + out.push(unescape_gitignore_path(t)); } } out @@ -376,7 +411,7 @@ fn upsert_managed_block(existing: &str, paths: &[String]) -> String { out.push(String::new()); } out.push(GITIGNORE_BEGIN.to_string()); - out.extend(paths.iter().cloned()); + out.extend(paths.iter().map(|p| escape_gitignore_path(p))); out.push(GITIGNORE_END.to_string()); } let mut s = out.join("\n"); @@ -440,7 +475,18 @@ fn read_head(path: &Path, n: u64) -> Result> { /// Bytes of the staged index blob for `path`: exactly what the release /// commit will store, filters and symlink handling included. fn staged_blob(root: &Path, path: &str) -> Result> { - Ok(git(root, &["show", &format!(":{path}")])?.stdout) + // Resolve the blob sha through the index rather than `:{path}` revspec + // syntax: a path that opens with magic characters is parsed as revspec + // there, not as a filename. + let out = git(root, &["ls-files", "-s", "-z", "--", path])?; + let stdout = String::from_utf8(out.stdout).context("ls-files output was not utf-8")?; + // ` \t`: the sha is the second blank field. + let sha = stdout + .split(' ') + .nth(1) + .filter(|s| !s.is_empty()) + .with_context(|| format!("{path} is not staged in the index"))?; + Ok(git(root, &["cat-file", "blob", sha])?.stdout) } /// Fetch a prior release's reconstruction object for dedup. A 404 means the @@ -664,34 +710,56 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let mut rec = Reconstruction::new(); let mut files: Vec = Vec::new(); for path in &scan.chunked_files { - let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; - let packed = pack_file(path, file, &dedup)?; + // Pack on a blocking thread and upload each block as it seals: a + // bounded channel keeps resident memory to a couple of blocks + // rather than the whole file. The dedup index moves to the thread + // through an Arc and comes back when it finishes. + let shared_dedup = std::sync::Arc::new(std::mem::take(&mut dedup)); + let task_dedup = shared_dedup.clone(); + let (block_tx, mut block_rx) = + tokio::sync::mpsc::channel::(2); + let pack_path = path.clone(); + let pack_root = root.clone(); + let pack_task = tokio::task::spawn_blocking(move || { + let file = std::fs::File::open(pack_root.join(&pack_path)) + .map_err(|e| std::io::Error::new(e.kind(), format!("open {pack_path}: {e}")))?; + pack_file_with(&pack_path, file, &task_dedup, move |block| { + block_tx + .blocking_send(block) + .map_err(|_| std::io::Error::other("block upload channel closed")) + }) + }); + while let Some(block) = block_rx.recv().await { + let sha = block.sha256; + if uploaded.contains(&sha) { + continue; + } + upload_block(&client, &base, &session_id, &sha, block.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded block {}", &sha[..16]); + } + let (file_entry, block_entries) = pack_task + .await + .context("pack task failed")? + .with_context(|| format!("pack {path}"))?; + dedup = std::sync::Arc::try_unwrap(shared_dedup).unwrap_or_else(|a| (*a).clone()); // Make this file's fresh chunks visible to the next file's dedup. - dedup.add_block_entries(&packed.block_entries); + dedup.add_block_entries(&block_entries); let head = read_head(&root.join(path), 64)?; files.push(ManifestFile { path: path.clone(), - size: packed.file.size, - sha256: packed.file.sha256.clone(), + size: file_entry.size, + sha256: file_entry.sha256.clone(), format: detect_format(&head, path), storage: StorageKind::Chunked, }); - rec.files.push(packed.file); - for e in packed.block_entries { + rec.files.push(file_entry); + for e in block_entries { all_entries.insert(e.sha256.clone(), e.clone()); rec.blocks.push(e); } - for b in packed.new_blocks { - let sha = b.sha256; - if uploaded.contains(&sha) { - continue; - } - upload_block(&client, &base, &session_id, &sha, b.data).await?; - state.uploaded.push(sha.clone()); - uploaded.insert(sha.clone()); - save_state(&state_path, &state)?; - println!("uploaded block {}", &sha[..16]); - } } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. @@ -733,12 +801,42 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { println!("uploaded reconstruction object"); } - // 7. Managed .gitignore block, then stage the publishable set. + // 7. Managed .gitignore block, then stage exactly the publishable set + // through a NUL pathspec: a bare `git add -A` would sweep in work the + // scan never saw (files created or un-ignored during the upload, or + // index changes staged for something else). let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); if new_gitignore != existing_gitignore { std::fs::write(&gitignore_path, &new_gitignore)?; } - git(&root, &["add", "-A"])?; + let pathspec_path = git_dir.join("twigpine-model-pathspec"); + { + let mut spec = Vec::new(); + for p in &scan.git_files { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + for p in [ + ".gitignore", + ".twigpine/model-release.json", + ".twigpine/model-release.sig", + ] { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + std::fs::write(&pathspec_path, spec)?; + } + let staged = git( + &root, + &[ + "add", + "-A", + "--pathspec-file-nul", + &format!("--pathspec-from-file={}", pathspec_path.display()), + ], + ); + let _ = std::fs::remove_file(&pathspec_path); + staged?; // 8. Hash the git-stored files from the index (the exact bytes the // commit stores), then write and stage the manifest. @@ -849,7 +947,23 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let release_path = format!("{base}/models/releases/{commit}"); let deadline = Instant::now() + POLL_BUDGET; loop { - let resp = client.get_signed(&release_path).await?; + // One transport hiccup should not abort the publish; the signed + // status read is idempotent, so retry it a few times. + let resp = 'poll: { + let mut last = None; + for _ in 0..3 { + match client.get_signed(&release_path).await { + Ok(r) => break 'poll r, + Err(e) => { + last = Some(e); + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + } + return Err(last + .expect("three attempts ran") + .context("release status request failed")); + }; let v: Value = read_json(resp, "release status").await?; match v["state"].as_str() { Some("published") => { diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 97f391bb..0b7401fd 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -99,6 +99,21 @@ impl Reconstruction { /// Structural sanity: terms index real blocks, chunk ranges are ordered, /// and each file's terms sum to its declared size. pub fn validate(&self) -> Result<(), ModelError> { + for block in &self.blocks { + let sum: u64 = block + .chunks + .iter() + .try_fold(0u64, |acc, c| acc.checked_add(c.len)) + .ok_or_else(|| { + ModelError::Invalid(format!("block {} chunk lengths overflow", block.sha256)) + })?; + if sum != block.size { + return Err(ModelError::Invalid(format!( + "block {} chunks sum to {sum} but the entry declares {}", + block.sha256, block.size + ))); + } + } let blocks: HashMap<&str, &BlockEntry> = self.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect(); for file in &self.files { @@ -128,15 +143,19 @@ impl Reconstruction { } let span: u64 = block.chunks[term.chunk_start as usize..term.chunk_end as usize] .iter() - .map(|c| c.len) - .sum(); + .try_fold(0u64, |acc, c| acc.checked_add(c.len)) + .ok_or_else(|| { + ModelError::Invalid(format!("{}: term lengths overflow", file.path)) + })?; if span != term.length { return Err(ModelError::Invalid(format!( "{}: term length {span} != declared {}", file.path, term.length ))); } - total += term.length; + total = total.checked_add(term.length).ok_or_else(|| { + ModelError::Invalid(format!("{}: file size overflow", file.path)) + })?; } if total != file.size { return Err(ModelError::Invalid(format!( @@ -162,7 +181,7 @@ impl Default for Reconstruction { /// Chunk-sha lookup over prior reconstruction objects, the dedup surface: /// a chunk whose hash a prior release already stored can be referenced by /// term instead of re-uploaded. -#[derive(Default)] +#[derive(Default, Clone)] pub struct DedupIndex { /// chunk sha256 -> (block sha256, chunk index inside that block) by_chunk: HashMap, @@ -203,14 +222,14 @@ impl DedupIndex { /// Seal the accumulating block of new chunks: patch its id into the terms /// written while it was still open, then append the block-table entry and /// queue the bytes for upload. -fn seal_pending( +fn seal_pending std::io::Result<()>>( pending: &mut Vec, terms: &mut [Term], block_entries: &mut Vec, - new_blocks: &mut Vec, -) { + on_block: &mut F, +) -> std::io::Result<()> { if pending.is_empty() { - return; + return Ok(()); } let chunks = std::mem::take(pending); let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum::()); @@ -241,7 +260,7 @@ fn seal_pending( }) .collect(), }); - new_blocks.push(block); + on_block(block) } /// What `pack_file` produced: the file's entry, the new blocks to store and @@ -254,16 +273,38 @@ pub struct PackedFile { /// Chunk and pack one file, reusing terms for chunks a prior reconstruction /// already holds (`dedup`). `path` is the repo-relative path recorded in the -/// entry. +/// entry. Every sealed block is held in the result; publishers of large +/// files should prefer `pack_file_with`, which keeps memory bounded by a +/// block instead of the file. pub fn pack_file( path: &str, reader: R, dedup: &DedupIndex, ) -> std::io::Result { + let mut new_blocks: Vec = Vec::new(); + let (file, block_entries) = pack_file_with(path, reader, dedup, |b| { + new_blocks.push(b); + Ok(()) + })?; + Ok(PackedFile { + file, + new_blocks, + block_entries, + }) +} + +/// `pack_file` with each sealed block handed to `on_block` as it finishes: +/// the caller can upload and drop it while the file is still packing, so a +/// file of any size packs in block-sized memory. +pub fn pack_file_with std::io::Result<()>>( + path: &str, + reader: R, + dedup: &DedupIndex, + mut on_block: F, +) -> std::io::Result<(FileEntry, Vec)> { let mut file_hasher = sha2::Sha256::new(); let mut terms: Vec = Vec::new(); - let mut new_blocks: Vec = Vec::new(); let mut block_entries: Vec = Vec::new(); // Chunks not found in `dedup` accumulate into one pending block that // seals only at the target size or EOF. Sealing on every reused-chunk @@ -312,22 +353,12 @@ pub fn pack_file( }), } if pending_bytes >= BLOCK_TARGET { - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; pending_bytes = 0; } } } - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; let file = FileEntry { path: path.to_string(), @@ -335,11 +366,7 @@ pub fn pack_file( sha256: hex::encode(file_hasher.finalize()), terms, }; - Ok(PackedFile { - file, - new_blocks, - block_entries, - }) + Ok((file, block_entries)) } /// Byte-range mapping: which slices of which blocks serve file bytes diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 9c2e7c35..d62770a6 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -204,20 +204,30 @@ pub async fn put_model_block( BlockStoreError::Unknown => AppError::Conflict( "the write's outcome is unknown; check the object before retrying".into(), ), + BlockStoreError::Body(e) => { + AppError::BadRequest(format!("block body could not be read: {e}")) + } other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), }); } // Stored and AlreadyPresent both leave the bytes stored. // Past this point the object exists; a bookkeeping failure must refund - // the admission or the session's charge leaks until it expires. + // the admission or the session's charge leaks until it expires, and + // must delete the store object or the sweep can never find it (its + // candidate list is model_blocks rows). let size = match store.size(&block_id).await { - Ok(s) => s.unwrap_or(declared), - Err(e) => { + Ok(Some(s)) => s, + r => { let _ = db.model_refund_bytes(&session.id, declared as i64).await; - return Err(AppError::Internal(anyhow::anyhow!( - "block size lookup failed: {e}" - ))); + let _ = store.delete(&block_id).await; + return Err(match r { + Ok(None) => AppError::Internal(anyhow::anyhow!( + "block {sha} absent immediately after write" + )), + Err(e) => AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")), + Ok(Some(_)) => unreachable!(), + }); } }; let duplicate = match db @@ -227,6 +237,7 @@ pub async fn put_model_block( Ok(d) => d, Err(e) => { let _ = db.model_refund_bytes(&session.id, declared as i64).await; + let _ = store.delete(&block_id).await; return Err(e.into()); } }; diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 61da56b1..94439bf7 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -81,7 +81,7 @@ impl BlockStore for FsBlockStore { let mut len: u64 = 0; let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs index 4a89325d..d0fd902e 100644 --- a/crates/twigpine-node/src/blockstore/mod.rs +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -95,6 +95,10 @@ pub enum BlockStoreError { /// unknown. #[error("the write's outcome is unknown; check size() before retrying")] Unknown, + /// The body stream itself failed (client abort, truncated upload): a + /// caller fault, distinct from a store-side `Io`. + #[error("body stream error: {0}")] + Body(io::Error), #[error("i/o error: {0}")] Io(#[from] io::Error), #[error("backend error: {0}")] diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index afafdbc2..29b29def 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -196,7 +196,7 @@ impl BlockStore for S3BlockStore { // ever resident, never the whole body. let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 272c96ec..3db76275 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -25,6 +25,11 @@ pub struct ModelSession { type SessionTuple = (String, String, String, String, i64, String); +/// Global advisory key serializing block-byte admission across sessions +/// (see `model_admit_bytes`). Distinct from `CLAIM_LOCK_KEY` in +/// `crate::models`, which serializes claim admission. +const MODEL_ADMIT_LOCK: i64 = 0x6D6F64656C61646D; // "modeladm" + const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; impl From for ModelSession { @@ -149,6 +154,16 @@ impl Db { session_cap: i64, node_cap: i64, ) -> Result> { + // Serialize admissions process-wide: the per-owner and node-wide cap + // terms read other sessions' bytes_received, and two concurrent PUTs + // on different sessions would otherwise admit against the same stale + // sums. The critical section is one UPDATE, so the global key costs + // nothing next to the upload itself. + let mut tx = self.pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(MODEL_ADMIT_LOCK) + .execute(&mut *tx) + .await?; let row = sqlx::query_as::<_, SessionTuple>(&format!( "UPDATE model_upload_sessions s SET bytes_received = s.bytes_received + $1, @@ -174,8 +189,9 @@ impl Db { .bind(ts_now()) .bind(session_cap) .bind(node_cap) - .fetch_optional(&self.pool) + .fetch_optional(&mut *tx) .await?; + tx.commit().await?; Ok(row.map(Into::into)) } @@ -256,6 +272,19 @@ impl Db { Ok(row.map(Into::into)) } + /// Ids of `verifying` releases stuck past `stale_secs`: the worker + /// retries them forever today, so the sweep rejects them to un-wedge + /// the publisher's one-verifying slot. + pub async fn model_stale_verifying(&self, stale_secs: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases + WHERE state = 'verifying' AND created_at < $1", + ) + .bind(ts_from_now(-stale_secs)) + .fetch_all(&self.pool) + .await?) + } + /// The reconstruction object sha a release was claimed with, if any. /// The reconstruction GET serves by this stored ref: the manifest it /// names is immutable under the pinned commit and was verified at claim. @@ -354,9 +383,10 @@ impl Db { Ok(sqlx::query_scalar( "SELECT sb.block_sha256 FROM model_session_blocks sb JOIN model_upload_sessions s ON s.id = sb.session_id - WHERE s.owner_did = $1 AND s.state = 'open'", + WHERE s.owner_did = $1 AND s.state = 'open' AND s.expires_at > $2", ) .bind(owner_did) + .bind(ts_now()) .fetch_all(&mut **tx) .await?) } @@ -532,11 +562,27 @@ impl Db { .bind(shas) .execute(&mut **tx) .await?; + // The release now carries these blocks, so the sessions stop being + // charged for exactly the bytes that moved. Subtracting the moved + // set (rather than recounting links) preserves bytes admitted but + // not yet recorded by a PUT still in flight. sqlx::query( - "DELETE FROM model_session_blocks sb - USING model_upload_sessions s - WHERE s.id = sb.session_id AND s.owner_did = $1 - AND s.state = 'open' AND sb.block_sha256 = ANY($2)", + "WITH moved AS ( + DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE s.id = sb.session_id AND s.owner_did = $1 + AND s.state = 'open' AND sb.block_sha256 = ANY($2) + RETURNING sb.session_id, sb.block_sha256 + ), per_session AS ( + SELECT m.session_id, COALESCE(SUM(b.size), 0)::bigint AS bytes + FROM moved m + JOIN model_blocks b ON b.sha256 = m.block_sha256 + GROUP BY m.session_id + ) + UPDATE model_upload_sessions s + SET bytes_received = GREATEST(s.bytes_received - ps.bytes, 0) + FROM per_session ps + WHERE ps.session_id = s.id", ) .bind(publisher_did) .bind(shas) @@ -545,29 +591,12 @@ impl Db { Ok(()) } - pub async fn model_tx_recount_open_session_bytes( - &self, - tx: &mut Transaction<'_, Postgres>, - owner_did: &str, - ) -> Result<()> { - sqlx::query( - "UPDATE model_upload_sessions s - SET bytes_received = COALESCE(( - SELECT SUM(b.size) FROM model_session_blocks sb - JOIN model_blocks b ON b.sha256 = sb.block_sha256 - WHERE sb.session_id = s.id), 0) - WHERE s.owner_did = $1 AND s.state = 'open'", - ) - .bind(owner_did) - .execute(&mut **tx) - .await?; - Ok(()) - } - // ── verification ─────────────────────────────────────────────────────── - pub async fn model_mark_published(&self, release_id: i64) -> Result<()> { - sqlx::query( + /// `false` when the release left `verifying` first (the stale-verify + /// sweep rejected it mid-run); the caller then unwinds what it wrote. + pub async fn model_mark_published(&self, release_id: i64) -> Result { + let done = sqlx::query( "UPDATE model_releases SET state = 'published', published_at = $2 WHERE id = $1 AND state = 'verifying'", @@ -575,14 +604,23 @@ impl Db { .bind(release_id) .bind(ts_now()) .execute(&self.pool) - .await?; - Ok(()) + .await? + .rows_affected(); + Ok(done > 0) } /// Reject: mark the release, drop its refs, and refund the publisher the /// bytes no other live release still references. pub async fn model_reject_release(&self, release_id: i64, reason: &str) -> Result<()> { let mut tx = self.pool.begin().await?; + // The refund's "no other live release references this block" test + // and a concurrent claim's "not already claimed" test must agree; + // the claim lock makes them serialize. Same order as claim_release + // (advisory first, then rows), so no deadlock is introduced. + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(crate::models::CLAIM_LOCK_KEY) + .execute(&mut *tx) + .await?; let released: Option<(String,)> = sqlx::query_as( "UPDATE model_releases SET state = 'rejected', failure_reason = $2 @@ -719,6 +757,19 @@ impl Db { tx: &mut Transaction<'_, Postgres>, sha: &str, ) -> Result { + // Lock the block row first. READ COMMITTED snapshots are taken per + // statement, so folding the liveness subqueries into the locking + // SELECT would evaluate them against the pre-lock snapshot and miss + // a link committed while this statement waited. + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM model_blocks WHERE sha256 = $1 FOR UPDATE)", + ) + .bind(sha) + .fetch_one(&mut **tx) + .await?; + if !exists { + return Ok(true); + } Ok(sqlx::query_scalar::<_, bool>( "SELECT NOT EXISTS ( SELECT 1 FROM model_release_blocks rb @@ -728,14 +779,11 @@ impl Db { AND NOT EXISTS ( SELECT 1 FROM model_session_blocks sb JOIN model_upload_sessions s ON s.id = sb.session_id - WHERE sb.block_sha256 = $1 AND s.state = 'open') - FROM model_blocks b - WHERE b.sha256 = $1 FOR UPDATE", + WHERE sb.block_sha256 = $1 AND s.state = 'open')", ) .bind(sha) - .fetch_optional(&mut **tx) - .await? - .unwrap_or(false)) + .fetch_one(&mut **tx) + .await?) } pub async fn model_tx_delete_block_row( @@ -873,6 +921,42 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn session_blocks_ignore_expired_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "c".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap(), + vec![sha.clone()] + ); + tx.rollback().await.unwrap(); + + // Past the wall-clock TTL the row still says 'open' until the sweep + // runs, yet the claim-side reachability set must already be empty. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap() + .is_empty()); + tx.rollback().await.unwrap(); + } + #[sqlx::test] async fn reserve_quota_caps_first_and_later_claims(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index d2628d33..f3e65607 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -5,7 +5,7 @@ use std::process::Command; /// internal bookkeeping, and `refs/gitlawb/releases/*` pins published model /// releases so gc never prunes them. One shared list keeps the /// repo-config writers in lockstep. -const HIDDEN_REFS: &[(&str, &str)] = &[ +pub(crate) const HIDDEN_REFS: &[(&str, &str)] = &[ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), ("uploadpack.hideRefs", "refs/gitlawb/releases/"), diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 84db6791..bfc3f4b9 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -2,7 +2,7 @@ //! the check-then-act tail (other-verifying probe, quota reservation, release //! insert) runs inside one transaction under the claim advisory lock. -use twigpine_core::model::manifest::Manifest; +use twigpine_core::model::manifest::{Manifest, StorageKind}; use crate::db::model_queries::ClaimPersist; use crate::db::RepoRecord; @@ -93,7 +93,7 @@ pub(crate) async fn read_verified_manifest( .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; let sig_text = String::from_utf8(sig_text).map_err(|_| bad_request("model-release.sig is not utf-8"))?; - let did: twigpine_core::did::Did = owner_did + let did: twigpine_core::did::Did = crate::db::canonical_did(owner_did) .parse() .map_err(|_| bad_request("repo owner DID does not resolve"))?; let manifest = twigpine_core::model::manifest::verify(&manifest_bytes, &sig_text, &did) @@ -120,10 +120,51 @@ pub async fn claim_release( } let (manifest_bytes, manifest) = read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; + let expected_repo = format!( + "{}/{}", + crate::db::canonical_did(&record.owner_did), + record.name + ); + if manifest.repo != expected_repo { + return Err(bad_request("manifest names a different repository")); + } + if manifest.reconstruction.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return Err(bad_request( + "chunked files declared but the manifest has no reconstruction object", + )); + } let m_sha = twigpine_core::cid::sha256_hex(&manifest_bytes); let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); let blocks = super::referenced_blocks(state, &manifest).await?; + // Resolve the declared parent before the transaction: the repo lookup + // uses its own pool connection and must not sit behind the global + // advisory lock, where pool pressure would stall every claim. + let parent = match &manifest.parent { + None => None, + Some(parent) => { + let (powner, pname) = parent + .repo + .split_once('/') + .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; + // A parent only confers blocks while its repo is fully public: + // a withdrawn parent cannot launder references. + let (precord, prules) = + crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; + if !precord.is_public || !prules.is_empty() { + return Err(bad_request( + "declared parent's repo is no longer fully public", + )); + } + Some((precord.id, parent.commit.clone())) + } + }; + let mut tx = db.model_begin().await?; db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; @@ -155,7 +196,7 @@ pub async fn claim_release( if let Some(missing) = blocks.iter().find(|b| !present.contains(b.as_str())) { return Err(bad_request(format!( "manifest references block {} which is not stored on this node", - &missing[..16] + missing.get(..16).unwrap_or(missing) ))); } } @@ -172,24 +213,11 @@ pub async fn claim_release( .await? .into_iter() .collect(); - let parent_blocks: std::collections::HashSet = match &manifest.parent { + let parent_blocks: std::collections::HashSet = match &parent { None => std::collections::HashSet::new(), - Some(parent) => { - let (powner, pname) = parent - .repo - .split_once('/') - .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; - // A parent only confers blocks while its repo is fully public: - // a withdrawn parent cannot launder references. - let (precord, prules) = - crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; - if !precord.is_public || !prules.is_empty() { - return Err(bad_request( - "declared parent's repo is no longer fully public", - )); - } + Some((prepo_id, pcommit)) => { let rows = db - .model_tx_release_blocks_at_commit(&mut tx, &precord.id, &parent.commit) + .model_tx_release_blocks_at_commit(&mut tx, prepo_id, pcommit) .await?; if rows.is_empty() { return Err(bad_request( @@ -207,7 +235,7 @@ pub async fn claim_release( return Err(bad_request(format!( "block {} is not reachable through an open session, a prior \ release, or the declared parent", - &b[..16] + b.get(..16).unwrap_or(b) ))); } } @@ -234,16 +262,6 @@ pub async fn claim_release( ))); } - // Node-wide quota in the same transaction: claimed bytes plus open - // session bytes. - let node_cap = state.config.model_node_quota_bytes as i64; - let node_total = db.model_tx_node_used(&mut tx).await?; - if node_total > node_cap { - return Err(AppError::TooManyRequests(format!( - "node model storage cap ({node_cap} bytes) would be exceeded" - ))); - } - let persist = ClaimPersist { signature: material.signature.clone(), signature_input: material.signature_input.clone(), @@ -266,12 +284,29 @@ pub async fn claim_release( let release_id = row.id; // Claimed blocks leave the caller's open sessions' charge: the - // release now carries them, so session bytes stop double-counting. + // release now carries them. This must precede the node-cap check or + // the just-claimed bytes count twice (once under quota, once under + // the sessions they still appear linked to). db.model_tx_link_release_blocks(&mut tx, release_id, caller, &blocks) .await?; - db.model_tx_recount_open_session_bytes(&mut tx, caller) - .await?; + + // Node-wide quota in the same transaction: claimed bytes plus open + // session bytes. + let node_cap = state.config.model_node_quota_bytes as i64; + let node_total = db.model_tx_node_used(&mut tx).await?; + if node_total > node_cap { + return Err(AppError::TooManyRequests(format!( + "node model storage cap ({node_cap} bytes) would be exceeded" + ))); + } tx.commit().await?; + + // Pin the commit under the hidden release ref now: between claim and + // publish a force-push plus gc could drop the commit the verifier + // needs. Best-effort; the publish path writes it again. + if let Err(e) = super::verify::write_release_ref(&state.git_bin, &disk_path, commit).await { + tracing::warn!(%commit, "release ref write at claim failed: {e}"); + } Ok(row) } diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index dfee0f64..f4e3e036 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -38,7 +38,10 @@ pub async fn read_range( use futures::StreamExt; let id = crate::blockstore::BlockId::parse(sha) .map_err(|e| crate::blockstore::BlockStoreError::Backend(e.to_string()))?; - let mut stream = store.get_range(&id, start, start + len).await?; + let end = start + .checked_add(len) + .ok_or(crate::blockstore::BlockStoreError::OutOfRange)?; + let mut stream = store.get_range(&id, start, end).await?; let mut out = Vec::with_capacity(len.min(1 << 22) as usize); while let Some(chunk) = stream.next().await { out.extend_from_slice(&chunk?); diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index 00202bfa..ca16a9a4 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -8,6 +8,10 @@ use crate::error::AppError; use crate::state::AppState; +/// A release still `verifying` this many seconds after claim is treated as +/// wedged: the worker died mid-verify or hit a persistent internal error. +const STALE_VERIFY_SECS: i64 = 6 * 3600; + #[derive(Debug, Default)] pub struct SweepStats { pub sessions_expired: u64, @@ -26,6 +30,13 @@ pub async fn sweep_once(state: &AppState) -> Result { stats.sessions_expired = expired.len() as u64; db.model_drop_sessions_blocks(&expired).await?; + // A `verifying` row that outlived its window wedges the publisher's + // one-verifying slot; reject it (which also frees the reservation). + for id in db.model_stale_verifying(STALE_VERIFY_SECS).await? { + db.model_reject_release(id, "verification timed out") + .await?; + } + // Re-mark liveness both ways: blocks that lost every live reference get // an unreferenced_since stamp; blocks that regained one clear theirs. stats.blocks_marked = db.model_remark_liveness().await?; diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index ae35c3bb..096896f9 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -73,38 +73,90 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App return reject_release(state, release_id, "manifest digest changed since claim").await; } - let Some(rec_ref) = &manifest.reconstruction else { - return reject_release(state, release_id, "manifest has no reconstruction object").await; - }; - let store = state - .block_store - .clone() - .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; - let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { - Ok(b) => b, - Err(e) => { - return reject_release( - state, - release_id, - &format!("reconstruction object unreadable: {e}"), - ) - .await; + let rec = match &manifest.reconstruction { + Some(rec_ref) => { + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object unreadable: {e}"), + ) + .await; + } + }; + match Reconstruction::parse(&rec_bytes) { + Ok(r) => Some(r), + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object invalid: {e}"), + ) + .await; + } + } } + None => None, }; - let rec = match Reconstruction::parse(&rec_bytes) { - Ok(r) => r, - Err(e) => { + // An all-Git release legitimately carries no reconstruction object; a + // manifest naming chunked files without one is self-contradictory. + if rec.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return reject_release( + state, + release_id, + "chunked files declared but the manifest has no reconstruction object", + ) + .await; + } + + // Commit ⊆ manifest: a committed file the manifest does not name as + // git-stored slipped past the publish scan; refuse it rather than + // release bytes the manifest never described. + let tree = crate::git::store::run_git_bounded( + &state.git_bin, + &disk_path, + &["ls-tree", "-r", "--name-only", &release.commit_sha], + b"", + std::time::Duration::from_secs(30), + "git ls-tree", + ) + .await + .map_err(AppError::Internal)?; + let manifest_git_paths: std::collections::HashSet<&str> = manifest + .files + .iter() + .filter(|f| f.storage == StorageKind::Git) + .map(|f| f.path.as_str()) + .collect(); + for path in String::from_utf8_lossy(&tree.stdout) + .lines() + .filter(|p| !p.starts_with(".twigpine/")) + { + if !manifest_git_paths.contains(path) { return reject_release( state, release_id, - &format!("reconstruction object invalid: {e}"), + &format!("{path} is committed but not in the manifest"), ) .await; } - }; + } - let rec_by_path: std::collections::HashMap<&str, _> = - rec.files.iter().map(|f| (f.path.as_str(), f)).collect(); + let rec_by_path: std::collections::HashMap<&str, _> = rec + .as_ref() + .map(|r| r.files.iter().map(|f| (f.path.as_str(), f)).collect()) + .unwrap_or_default(); for file in &manifest.files { match file.storage { StorageKind::Chunked => { @@ -128,8 +180,9 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // would force block_on, which has no reactor under the S3 // backend. Blocks were hash-verified at write, so the // whole-file digest is the check that matters here. + let rec = rec.as_ref().expect("entry implies rec"); let slices = match twigpine_core::model::reconstruction::map_file_range( - entry, &rec, 0, file.size, + entry, rec, 0, file.size, ) { Ok(s) => s, Err(e) => { @@ -147,19 +200,25 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App }; // Ordered prefetch: `buffered` preserves order while // overlapping the store's per-slice round trips. + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; let jobs = slices .iter() .map(|s| (s.block.clone(), s.offset, s.len)) .collect::>(); - let fetched = + // Ordered prefetch: `buffered` preserves order while + // overlapping the store's per-slice round trips. Consume + // as slices land: collecting first would hold the whole + // rebuilt file in memory. + let mut fetched = futures::stream::iter(jobs.into_iter().map(|(block, offset, len)| { let store = store.clone(); async move { super::read_range(&store, &block, offset, len).await } })) - .buffered(4) - .collect::>() - .await; - for bytes in fetched { + .buffered(4); + while let Some(bytes) = fetched.next().await { let bytes = match bytes { Ok(b) => b, Err(e) => { @@ -246,17 +305,74 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // Publish: hidden ref first, then the state flip, so a crash leaves a // verifying row the worker retries rather than a dangling ref. write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; - state.db.model_mark_published(release_id).await?; + if !state.db.model_mark_published(release_id).await? { + // The stale-verify sweep rejected the row while this pass ran: + // drop the ref just written so it does not advertise a rejected + // commit. + let ref_name = format!("refs/gitlawb/releases/{}", release.commit_sha); + let _ = crate::git::store::run_git_bounded( + &state.git_bin, + &disk_path, + &["update-ref", "-d", &ref_name], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await; + } Ok(()) } /// `refs/gitlawb/releases/` -> the release commit itself: reachable, /// so `gc` never prunes it, and hidden under the gitlawb ref namespace. +/// Idempotently add the release-ref hideRefs config: repos created before +/// the namespace existed only get it via the push-path prereq, which is +/// warn-and-proceed, so a failed write there would leave release commits +/// advertised to every clone. +async fn ensure_release_refs_hidden( + git_bin: &str, + disk_path: &std::path::Path, +) -> Result<(), AppError> { + for &(key, value) in crate::git::store::HIDDEN_REFS + .iter() + .filter(|(_, v)| v.contains("releases/")) + { + let have = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--get-all", key], + b"", + std::time::Duration::from_secs(30), + "git config --get-all", + ) + .await + .map_err(AppError::Internal)?; + if String::from_utf8_lossy(&have.stdout) + .lines() + .any(|l| l.trim() == value) + { + continue; + } + crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--add", key, value], + b"", + std::time::Duration::from_secs(30), + "git config --add", + ) + .await + .map_err(AppError::Internal)?; + } + Ok(()) +} + pub async fn write_release_ref( git_bin: &str, disk_path: &std::path::Path, commit: &str, ) -> Result<(), AppError> { + ensure_release_refs_hidden(git_bin, disk_path).await?; let out = crate::git::store::run_git_bounded( git_bin, disk_path, From 9207ee2838cda6bc954b10c25caa53eb10b9049c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:29:40 -0600 Subject: [PATCH 13/20] chore(cli): annotate model publish's local git spawns 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. --- crates/twigpine-cli/src/model.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 9805a892..dd2c2ff1 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -87,6 +87,8 @@ pub async fn run(cmd: ModelCmd) -> Result<()> { // ── git helpers ───────────────────────────────────────────────────────────── fn git(root: &Path, args: &[&str]) -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(args) .current_dir(root) @@ -141,6 +143,8 @@ fn release_commits(root: &Path) -> Vec { } fn repo_root() -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["rev-parse", "--show-toplevel"]) .output() @@ -564,6 +568,8 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let branch = match &args.branch { Some(b) => b.clone(), None => { + // allow-unbounded-git: short-lived CLI process; there is no + // request permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["symbolic-ref", "--short", "-q", "HEAD"]) .current_dir(&root) @@ -916,6 +922,8 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { .next() .context("no HEAD commit")?; + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let push = std::process::Command::new("git") .args(["push", &remote_name, &format!("HEAD:{branch}")]) .current_dir(&root) From 236728ec1554b366628342f24e5d504c9680579e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:36:32 -0600 Subject: [PATCH 14/20] fix(node): refuse mirror rows for model publishing 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. --- crates/twigpine-node/src/api/models.rs | 6 ++- crates/twigpine-node/src/models/claim.rs | 4 +- crates/twigpine-node/src/models/verify.rs | 4 +- crates/twigpine-node/tests/models_api.rs | 57 +++++++++++++++++++++++ 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index d62770a6..ce7cdcbd 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -40,7 +40,11 @@ fn hosting_enabled(state: &AppState) -> Result<()> { /// a public one carrying any path-scoped visibility rule, refuses with a /// clear 4xx rather than partially publishing. fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { - if !record.is_public || !rules.is_empty() { + // A mirror row (slash-form id) carries a vacuous publicity pair: its + // is_public is hardcoded true and rules never sync, so passing this + // check on one means nothing. Mirrors are replication-managed, not + // publishable; refuse them the same way as a gated canonical repo. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return Err(AppError::BadRequest( "model hosting requires a fully public repository".into(), )); diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index bfc3f4b9..1d06e483 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -156,7 +156,9 @@ pub async fn claim_release( // a withdrawn parent cannot launder references. let (precord, prules) = crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; - if !precord.is_public || !prules.is_empty() { + // A mirror parent row fails closed the same way: its publicity + // pair is vacuous. + if !precord.is_public || !prules.is_empty() || precord.id.contains('/') { return Err(bad_request( "declared parent's repo is no longer fully public", )); diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 096896f9..6296732f 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -50,7 +50,9 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await? .ok_or_else(|| AppError::NotFound("repo gone".into()))?; let rules = state.db.list_visibility_rules(&record.id).await?; - if !record.is_public || !rules.is_empty() { + // A mirror row (slash-form id) has a vacuous publicity pair, so it can + // never prove full publicity here either. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return reject_release(state, release_id, "repository is no longer fully public").await; } diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index 0d3116a4..ea89c43e 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -145,6 +145,63 @@ async fn open_session_owner_created(pool: sqlx::PgPool) { node.shutdown().await; } +/// A mirror row with no canonical twin carries a vacuous publicity pair: +/// `is_public` is hardcoded true and rules never sync, so neither check may +/// admit it for publishing. Slash-form ids mark mirror rows (issue #244). +#[sqlx::test] +async fn mirror_repo_without_twin_cannot_publish(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos + (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1,'model',$2,'mirrored from peer',true,'main',$3,$3,'/tmp/mirror-model')", + ) + .bind(format!("{owner_did}/model")) + .bind(&owner_did) + .bind(&now) + .execute(&pool) + .await + .expect("mirror row seeds"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + let body = serde_json::to_vec(&json!({"commit": "0".repeat(40), "branch": "main"})).unwrap(); + let signed = sign_request(&owner, "POST", &claims_path(&owner_did, "model"), &body); + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + node.shutdown().await; +} + /// A signed caller who is not the repo owner gets the owner gate's 403. #[sqlx::test] async fn open_session_non_owner_forbidden(pool: sqlx::PgPool) { From 27e971ca8372a78bf496c22e8505121b51a8b4c4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:46:53 -0600 Subject: [PATCH 15/20] fix(node): fail closed on mirror rows at every model publicity check Extend the mirror guard to block PUTs and reconstruction reads, and mark the verify recheck for the push gate's mirror-pair scan. --- crates/twigpine-node/src/api/models.rs | 10 +++++++++- crates/twigpine-node/src/models/verify.rs | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index ce7cdcbd..480d81a2 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -134,6 +134,10 @@ pub async fn put_model_block( // indistinguishable from a missing session. The owner always reads their // own repo, so the fully-public check is what stops bytes landing on a // repo that turned private or gained visibility rules mid-upload. + // mirror-rows-handled: sessions can only bind canonical repos (open + // refuses slash ids); the id check below already makes a mirror row a + // mismatch, and the explicit slash guard keeps the publicity pair from + // being trusted on one. let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; if session.repo_id != record.id @@ -141,6 +145,7 @@ pub async fn put_model_block( || session.expires_at <= models::ts_now() || !record.is_public || !rules.is_empty() + || record.id.contains('/') { return Err(AppError::NotFound("model upload session not found".into())); } @@ -353,9 +358,12 @@ pub async fn get_model_reconstruction( ) -> Result { hosting_enabled(&state)?; let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + // mirror-rows-handled: a mirror row (slash-form id) can never carry a + // claimed release, and its publicity pair is vacuous, so it takes the + // same 404 as a private repo. let (record, rules) = authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; - if !record.is_public || !rules.is_empty() { + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return Err(AppError::NotFound("model release not found".into())); } let release = state diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 6296732f..df4300c5 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -49,6 +49,8 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .get_repo_by_id(&release.repo_id) .await? .ok_or_else(|| AppError::NotFound("repo gone".into()))?; + // mirror-rows-handled: a slash-form id fails closed in the condition + // below; the vacuous pair never admits a mirror for publishing. let rules = state.db.list_visibility_rules(&record.id).await?; // A mirror row (slash-form id) has a vacuous publicity pair, so it can // never prove full publicity here either. From 85e412454c0fc6855e6745562b3f7777c0bc33e0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:25:57 -0600 Subject: [PATCH 16/20] fix(node): pin model.rs on the read_json gate, expire open sessions on 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. --- .../tests/no_parse_before_status.rs | 1 + crates/twigpine-node/src/api/models.rs | 2 +- crates/twigpine-node/tests/models_api.rs | 90 +++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-cli/tests/no_parse_before_status.rs b/crates/twigpine-cli/tests/no_parse_before_status.rs index 708498c1..f9b2bfbd 100644 --- a/crates/twigpine-cli/tests/no_parse_before_status.rs +++ b/crates/twigpine-cli/tests/no_parse_before_status.rs @@ -66,6 +66,7 @@ const CONVERTED_IN_186: &[&str] = &[ "changelog.rs", "issue.rs", "mcp.rs", + "model.rs", "peer.rs", "pr.rs", "protect.rs", diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 480d81a2..d7db08a1 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -94,7 +94,7 @@ pub async fn get_model_session( .db .model_load_session(&id) .await? - .filter(|s| s.repo_id == record.id) + .filter(|s| s.repo_id == record.id && s.expires_at > models::ts_now()) .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; Ok(Json(json!({ "session_id": session.id, diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index ea89c43e..b0402401 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -545,6 +545,96 @@ async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) node.shutdown().await; } +/// A session bearer that declares a small Content-Length but streams a larger +/// valid block must not get the larger block stored under the small charge. +/// Both framing headers are sent so the body is read to EOF by chunked +/// framing while the handler still sees the understated length. +#[sqlx::test] +async fn put_block_understated_content_length_is_not_stored_under_small_charge(pool: sqlx::PgPool) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let node = spawn_node(pool).await; + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = vec![b'x'; 4096]; + let sha = sha256_hex(&body); + let addr = node.base_url.trim_start_matches("http://").to_string(); + let mut sock = tokio::net::TcpStream::connect(&addr) + .await + .expect("connect"); + let head = format!( + "PUT {} HTTP/1.1\r\nHost: {addr}\r\nx-twigpine-model-session: {session_id}\r\n\ + Content-Length: 4\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n", + blocks_path(&owner_did, "model", &sha) + ); + sock.write_all(head.as_bytes()).await.expect("write head"); + sock.write_all(format!("{:x}\r\n", body.len()).as_bytes()) + .await + .expect("write chunk size"); + sock.write_all(&body).await.expect("write body"); + sock.write_all(b"\r\n0\r\n\r\n").await.expect("write end"); + let mut raw = Vec::new(); + let _ = sock.read_to_end(&mut raw).await; + let raw = String::from_utf8_lossy(&raw).to_string(); + let status_line = raw.lines().next().unwrap_or("").to_string(); + eprintln!("raw response: {raw}"); + assert!( + !status_line.contains(" 200 "), + "a block larger than its declared Content-Length must not be admitted: {status_line}" + ); + + node.shutdown().await; +} + +/// An open session past its `expires_at` is dead on the status read too, so +/// the CLI resume path (which abandons a 404) does not keep a lapsed session. +#[sqlx::test] +async fn get_session_expired_open_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let kp = Keypair::generate(); + let owner_did = kp.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "f".repeat(64); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + let path = format!("{}/{session_id}", sessions_path(&owner_did, "model")); + let live = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(live.status().as_u16(), 200, "a live session reads as open"); + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "a lapsed session is not found"); + + node.shutdown().await; +} + // ── POST /models/claims ────────────────────────────────────────────────────── /// A claim against a pushed commit carrying a signed manifest inserts the From 8d6cae263a8ddd7af240484c312cc607126c84b4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:15:46 -0600 Subject: [PATCH 17/20] fix(node): ignore expired sessions in cap sums, refund dedup of released 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. --- crates/twigpine-cli/src/model.rs | 27 ++- crates/twigpine-node/src/db/model_queries.rs | 172 ++++++++++++++++++- 2 files changed, 190 insertions(+), 9 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index dd2c2ff1..017c3847 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -444,9 +444,10 @@ fn load_state(path: &Path) -> PublishState { /// resume set, so it is written and fsync'd rather than left in page cache. fn save_state(path: &Path, state: &PublishState) -> Result<()> { let bytes = serde_json::to_vec(state)?; - let mut f = std::fs::File::create(path).with_context(|| format!("write {}", path.display()))?; - f.write_all(&bytes)?; - f.sync_all()?; + // The file holds the session bearer, so it goes through the owner-only + // writer, then is fsync'd (the helper does not sync). + crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; + std::fs::File::open(path)?.sync_all()?; Ok(()) } @@ -1060,6 +1061,26 @@ mod tests { assert!(managed_block_paths("nothing here\n").is_empty()); } + #[cfg(unix)] + #[test] + fn save_state_is_owner_only_even_over_a_loose_file() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "bearer".to_string(), + uploaded: vec![], + }; + save_state(&path, &state).unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&path), 0o600); + // A resume file left loose by an earlier run is tightened on rewrite. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + save_state(&path, &state).unwrap(); + assert_eq!(mode(&path), 0o600); + assert_eq!(load_state(&path), state); + } + #[test] fn publish_state_round_trips() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 3db76275..57a0abfd 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -174,11 +174,12 @@ impl Db { AND s.bytes_received + $1 + COALESCE(( SELECT SUM(o.bytes_received) FROM model_upload_sessions o WHERE o.owner_did = s.owner_did AND o.state = 'open' AND o.id <> s.id + AND o.expires_at > $4 ), 0) <= $5 AND COALESCE((SELECT SUM(q.bytes_used) FROM model_quota_usage q), 0) + COALESCE(( SELECT SUM(o2.bytes_received) FROM model_upload_sessions o2 - WHERE o2.state = 'open' + WHERE o2.state = 'open' AND o2.expires_at > $4 ), 0) + $1 <= $6 RETURNING {SESSION_COLS}" @@ -211,8 +212,12 @@ impl Db { } /// Book the stored block against the session in one transaction. `true` - /// when this PUT was a duplicate within the session (the admission - /// credit was refunded). + /// when the admission credit was refunded: a duplicate within the + /// session, or a block a verifying or published release already carries + /// (that release was billed at claim, and dedup stays free). A block + /// held only by other open sessions is still charged here, because a + /// refund would let sessions hold bytes nobody bills once the first + /// one expires. pub async fn model_record_block( &self, session_id: &str, @@ -241,7 +246,18 @@ impl Db { .execute(&mut *tx) .await? .rows_affected(); - if linked == 0 { + let refund = linked == 0 + || sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = $1 + AND r.state IN ('verifying', 'published'))", + ) + .bind(block_sha) + .fetch_one(&mut *tx) + .await?; + if refund { sqlx::query( "UPDATE model_upload_sessions SET bytes_received = GREATEST(bytes_received - $1, 0) @@ -253,7 +269,7 @@ impl Db { .await?; } tx.commit().await?; - Ok(linked == 0) + Ok(refund) } pub async fn model_release_by_commit( @@ -493,11 +509,14 @@ impl Db { /// Node-wide used bytes: claimed quota plus every open session's bytes. pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { // SUM over bigint returns numeric; cast back so the i64 decode holds. + // A session past its wall-clock expiry is dead before the sweep + // flips its state, so it does not count against the cap. Ok(sqlx::query_scalar::<_, Option>( "SELECT (COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions - WHERE state = 'open'), 0))::bigint", + WHERE state = 'open' AND expires_at > $1), 0))::bigint", ) + .bind(ts_now()) .fetch_one(&mut **tx) .await? .unwrap_or(0)) @@ -921,6 +940,147 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn caps_ignore_wall_clock_dead_open_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // A same-owner peer and a different-owner peer each hold 900 bytes. + let peer_same = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + let peer_other = db.model_open_session("did:other", "r1", 60).await.unwrap(); + for s in [&peer_same, &peer_other] { + db.model_admit_bytes(&s.id, 900, 3600, 10_000, 100_000) + .await + .unwrap() + .expect("peer admission"); + } + // Past the wall-clock TTL the rows still say 'open' until the sweep. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1") + .bind("2000-01-01T00:00:00+00:00") + .execute(&pool) + .await + .unwrap(); + + // Claim-side node total must not count the dead sessions. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!(db.model_tx_node_used(&mut tx).await.unwrap(), 0); + tx.rollback().await.unwrap(); + + // Per-owner term: the dead same-owner peer must not eat the cap. + let live = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live.id, 200, 3600, 1000, 100_000) + .await + .unwrap() + .is_some()); + // Node-wide term: both dead peers (1800) must not eat a 1000 cap. + let live2 = db.model_open_session("did:third", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live2.id, 200, 3600, 10_000, 1000) + .await + .unwrap() + .is_some()); + } + + async fn seed_release_with_block(pool: &sqlx::PgPool, state: &str, commit: &str, sha: &str) { + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't') + ON CONFLICT DO NOTHING", + ) + .bind(sha) + .execute(pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1', $1, 'main', 'did:owner', $2, 'm', 's', 'i', 'ss', '\\x00', 't') + RETURNING id", + ) + .bind(commit) + .bind(state) + .fetch_one(pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1, $2)") + .bind(rid) + .bind(sha) + .execute(pool) + .await + .unwrap(); + } + + async fn session_bytes(pool: &sqlx::PgPool, id: &str) -> i64 { + sqlx::query_scalar("SELECT bytes_received FROM model_upload_sessions WHERE id = $1") + .bind(id) + .fetch_one(pool) + .await + .unwrap() + } + + #[sqlx::test] + async fn record_block_refunds_only_bytes_a_live_release_already_carries(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + + // Block already carried by a published release: a new session's + // link is free, the release was billed at claim. + let carried = "d".repeat(64); + seed_release_with_block(&pool, "published", "c1", &carried).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(db + .model_record_block(&s.id, &carried, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 0); + + // Block only in a rejected release: nothing bills it, so the + // session keeps the charge. + let dead = "e".repeat(64); + seed_release_with_block(&pool, "rejected", "c2", &dead).await; + let s2 = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s2.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s2.id, &dead, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s2.id).await, 100); + + // Block held only by another open session: that session is the + // one billed, and a refund here would let a session pair hold + // unbilled bytes once the first expires. + let held = "f".repeat(64); + let a = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let b = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + for x in [&a, &b] { + db.model_admit_bytes(&x.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + } + assert!(!db.model_record_block(&a.id, &held, 100, 100).await.unwrap()); + assert!(!db.model_record_block(&b.id, &held, 100, 100).await.unwrap()); + assert_eq!(session_bytes(&pool, &b.id).await, 100); + } + #[sqlx::test] async fn session_blocks_ignore_expired_sessions(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; From b518cad5490cb6c866117e2a2bdc56bc3b447147 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:30:38 -0600 Subject: [PATCH 18/20] fix(node): refund and skip the session link only for blocks the owner'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. --- crates/twigpine-node/src/db/model_queries.rs | 93 ++++++++++++++------ 1 file changed, 65 insertions(+), 28 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 57a0abfd..4779b787 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -213,11 +213,13 @@ impl Db { /// Book the stored block against the session in one transaction. `true` /// when the admission credit was refunded: a duplicate within the - /// session, or a block a verifying or published release already carries - /// (that release was billed at claim, and dedup stays free). A block - /// held only by other open sessions is still charged here, because a - /// refund would let sessions hold bytes nobody bills once the first - /// one expires. + /// session, or a block a verifying or published release of the session's + /// own owner already carries. Claim authorizes that release's blocks + /// without a session link and billed them at claim, so the block is + /// neither charged nor linked here; a link would outlive the release and + /// hold the block unbilled once it is rejected. Blocks carried by another + /// publisher's release, or held only by other open sessions, are still + /// charged and linked. pub async fn model_record_block( &self, session_id: &str, @@ -236,27 +238,33 @@ impl Db { .bind(ts_now()) .execute(&mut *tx) .await?; - let linked = sqlx::query( - "INSERT INTO model_session_blocks (session_id, block_sha256) - VALUES ($1, $2) - ON CONFLICT (session_id, block_sha256) DO NOTHING", + let own_release_carries = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + JOIN model_upload_sessions s ON s.owner_did = r.publisher_did + WHERE rb.block_sha256 = $1 AND s.id = $2 + AND r.state IN ('verifying', 'published'))", ) - .bind(session_id) .bind(block_sha) - .execute(&mut *tx) - .await? - .rows_affected(); - let refund = linked == 0 - || sqlx::query_scalar::<_, bool>( - "SELECT EXISTS ( - SELECT 1 FROM model_release_blocks rb - JOIN model_releases r ON r.id = rb.release_id - WHERE rb.block_sha256 = $1 - AND r.state IN ('verifying', 'published'))", + .bind(session_id) + .fetch_one(&mut *tx) + .await?; + let linked = if own_release_carries { + 0 + } else { + sqlx::query( + "INSERT INTO model_session_blocks (session_id, block_sha256) + VALUES ($1, $2) + ON CONFLICT (session_id, block_sha256) DO NOTHING", ) + .bind(session_id) .bind(block_sha) - .fetch_one(&mut *tx) - .await?; + .execute(&mut *tx) + .await? + .rows_affected() + }; + let refund = linked == 0; if refund { sqlx::query( "UPDATE model_upload_sessions @@ -980,7 +988,13 @@ mod tests { .is_some()); } - async fn seed_release_with_block(pool: &sqlx::PgPool, state: &str, commit: &str, sha: &str) { + async fn seed_release_with_block( + pool: &sqlx::PgPool, + publisher: &str, + state: &str, + commit: &str, + sha: &str, + ) { sqlx::query( "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't') ON CONFLICT DO NOTHING", @@ -994,11 +1008,12 @@ mod tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ('r1', $1, 'main', 'did:owner', $2, 'm', 's', 'i', 'ss', '\\x00', 't') + VALUES ('r1', $1, 'main', $3, $2, 'm', 's', 'i', 'ss', '\\x00', 't') RETURNING id", ) .bind(commit) .bind(state) + .bind(publisher) .fetch_one(pool) .await .unwrap(); @@ -1022,10 +1037,11 @@ mod tests { async fn record_block_refunds_only_bytes_a_live_release_already_carries(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; - // Block already carried by a published release: a new session's - // link is free, the release was billed at claim. + // Block already carried by the owner's published release: claim + // authorizes it without a link and billed it, so the PUT is free + // and leaves no link behind to outlive the release. let carried = "d".repeat(64); - seed_release_with_block(&pool, "published", "c1", &carried).await; + seed_release_with_block(&pool, "did:owner", "published", "c1", &carried).await; let s = db .model_open_session("did:owner", "r1", 3600) .await @@ -1039,11 +1055,32 @@ mod tests { .await .unwrap()); assert_eq!(session_bytes(&pool, &s.id).await, 0); + let links: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM model_session_blocks WHERE session_id = $1") + .bind(&s.id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(links, 0); + + // Another publisher's published release bills its owner, not this + // session, and the session needs the link to claim the block. + let theirs = "9".repeat(64); + seed_release_with_block(&pool, "did:other", "published", "c3", &theirs).await; + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s.id, &theirs, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 100); // Block only in a rejected release: nothing bills it, so the // session keeps the charge. let dead = "e".repeat(64); - seed_release_with_block(&pool, "rejected", "c2", &dead).await; + seed_release_with_block(&pool, "did:owner", "rejected", "c2", &dead).await; let s2 = db .model_open_session("did:owner", "r1", 3600) .await From 2a3497ce17e36844fcd19039db6e2a456312f88a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:37:22 -0600 Subject: [PATCH 19/20] docs(node): state that a rejected release is final for its commit --- crates/twigpine-node/src/models/claim.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 1d06e483..45abb9c2 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -171,7 +171,10 @@ pub async fn claim_release( db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; // Replay by request digest, then idempotent re-claim by (repo, commit): - // both return the original row. + // both return the original row, whatever its state. A rejected release + // is final for that commit: verification judges the pinned, immutable + // commit, so a retry would re-run the same checks, and the publisher + // retries by minting a new commit. if let Some(existing) = db .model_tx_release_by_digest(&mut tx, &material.request_digest) .await? From 590207909b755ac9a0f6c5e84f62a8fb7dcafb8a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:28:06 -0600 Subject: [PATCH 20/20] fix(node): fsync the publish resume file through a writable handle and 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. --- crates/twigpine-cli/src/model.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 017c3847..4ad197db 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -447,7 +447,10 @@ fn save_state(path: &Path, state: &PublishState) -> Result<()> { // The file holds the session bearer, so it goes through the owner-only // writer, then is fsync'd (the helper does not sync). crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; - std::fs::File::open(path)?.sync_all()?; + std::fs::OpenOptions::new() + .write(true) + .open(path)? + .sync_all()?; Ok(()) } @@ -623,8 +626,10 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } eprintln!( - "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" + "publishing stores the blocks in this node's configured block store and commits a \ + signed release manifest to git: the bytes stay available only while this node \ + keeps them and the repo stays readable, and nothing is pinned to IPFS or \ + anchored to Arweave" ); if !args.yes && !confirm_publish()? { println!("aborted");