From 7ec00c3b91e798315ec8dcd32b65461326077cf8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:56:32 -0600 Subject: [PATCH 01/14] feat(node): add the HF read surface and release durability Serve published model releases through Hugging Face-compatible metadata and resolve routes, resolved from release rows rather than git history and gated on full publicity so private, mirrored, and rule-bearing repos answer the same 404. Byte serving covers git and chunked files with single-range, suffix, If-Range, and conditional support under a dedicated per-IP limiter and download semaphore. Publishing now also enqueues an idempotent durability job set: block, manifest, reconstruction, and block-map pins to Kubo and optionally Pinata, then a compact Irys anchor once every pin lands. A policy fence fails every pending sibling and withholds the anchor when a repo stops being fully public; local serving never waits on the providers. --- crates/twigpine-node/Cargo.toml | 5 + crates/twigpine-node/src/api/hf.rs | 543 ++++++++++ crates/twigpine-node/src/api/mod.rs | 2 + crates/twigpine-node/src/api/models.rs | 2 +- crates/twigpine-node/src/arweave.rs | 215 ++++ crates/twigpine-node/src/auth/mod.rs | 2 + crates/twigpine-node/src/config.rs | 16 + crates/twigpine-node/src/db/model_queries.rs | 307 ++++++ crates/twigpine-node/src/ipfs_pin.rs | 18 + crates/twigpine-node/src/lib.rs | 16 + crates/twigpine-node/src/models/durability.rs | 994 ++++++++++++++++++ crates/twigpine-node/src/models/mod.rs | 2 + crates/twigpine-node/src/models/serve.rs | 302 ++++++ crates/twigpine-node/src/models/verify.rs | 5 + crates/twigpine-node/src/pinata.rs | 37 +- crates/twigpine-node/src/server.rs | 35 +- crates/twigpine-node/src/state.rs | 17 + crates/twigpine-node/src/test_harness.rs | 2 + crates/twigpine-node/src/test_support.rs | 2 + crates/twigpine-node/tests/deny_harness.rs | 22 + crates/twigpine-node/tests/hf_api.rs | 917 ++++++++++++++++ 21 files changed, 3455 insertions(+), 6 deletions(-) create mode 100644 crates/twigpine-node/src/api/hf.rs create mode 100644 crates/twigpine-node/src/models/durability.rs create mode 100644 crates/twigpine-node/src/models/serve.rs create mode 100644 crates/twigpine-node/tests/hf_api.rs diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index acf6097c..e66273f4 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -33,6 +33,11 @@ name = "models_api" path = "tests/models_api.rs" required-features = ["test-harness"] +[[test]] +name = "hf_api" +path = "tests/hf_api.rs" +required-features = ["test-harness"] + [dependencies] twigpine-core = { path = "../twigpine-core" } async-trait = "0.1" diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs new file mode 100644 index 00000000..56decd1e --- /dev/null +++ b/crates/twigpine-node/src/api/hf.rs @@ -0,0 +1,543 @@ +//! Hugging Face-compatible model read surface (KTD8, KTD9). +//! +//! Endpoints: +//! GET /hf/api/models/{owner}/{repo} model info +//! GET /hf/api/models/{owner}/{repo}/revision/{rev} revision info +//! GET /hf/api/models/{owner}/{repo}/tree/{rev}[/{path}] file tree +//! GET /hf/api/models/{owner}/{repo}/refs branch refs +//! HEAD|GET /hf/{owner}/{repo}/resolve/{rev}/{*path} file bytes +//! +//! Metadata comes from the newest published release row and its manifest, +//! never from arbitrary git history: a plain push after a release does not +//! move HF `main`. Publicity is checked before any release lookup, so a +//! private, mirrored, or rule-bearing repo answers the same 404 as a +//! missing one and releases never leak existence. +//! +//! HF bearer tokens are ignored: `Authorization: Bearer hf_...` carries no +//! signature headers, so the caller reads as anonymous and never gets a +//! 401 from the signature middleware. + +use std::sync::Arc; + +use axum::body::Body; +use axum::extract::{Path, State}; +use axum::http::header::{ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, ETAG}; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Extension; +use serde_json::json; +use twigpine_core::model::manifest::{FileFormat, Manifest, StorageKind}; +use twigpine_core::model::reconstruction::Reconstruction; + +use crate::api::authorize_repo_read; +use crate::api::models::require_fully_public; +use crate::auth::AuthenticatedDid; +use crate::blockstore::BlockStore; +use crate::db::{RepoRecord, VisibilityRule}; +use crate::error::AppError; +use crate::models::claim::git_show; +use crate::models::serve::{self, RangeSpec}; +use crate::models::ReleaseRow; +use crate::state::AppState; + +/// Manifest and signature paths inside the release commit (the same paths +/// `models::claim` reads at claim time). +const MANIFEST_PATH: &str = ".twigpine/model-release.json"; + +const X_REPO_COMMIT: HeaderName = HeaderName::from_static("x-repo-commit"); +const X_ERROR_CODE: HeaderName = HeaderName::from_static("x-error-code"); + +/// HF error body: `{"error": code}` with the code repeated in +/// `X-Error-Code`, the shape HF clients dispatch on. +fn hf_deny(status: StatusCode, code: &'static str) -> Response { + let mut resp = (status, axum::Json(json!({"error": code}))).into_response(); + if let Ok(v) = HeaderValue::from_str(code) { + resp.headers_mut().insert(X_ERROR_CODE, v); + } + resp +} + +fn hosting_enabled(state: &AppState) -> Result<(), AppError> { + if state.block_store.is_none() { + return Err(AppError::NotFound("model hosting not enabled".into())); + } + Ok(()) +} + +/// The caller's DID, or `None` for anonymous. A bearer token is not a +/// signature header, so it never reaches here. +fn caller_did(auth: &Option>) -> Option<&str> { + auth.as_ref().map(|e| e.0 .0.as_str()) +} + +/// The second half of the read gate every HF handler runs (the +/// `authorize_repo_read` call itself stays inline in each handler so the +/// egress guard sees it): model hosting serves only a fully public repo, +/// and anything else answers the same bare 404 so release existence cannot +/// be inferred through the model surface. +fn require_fully_public_404(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<(), AppError> { + if require_fully_public(record, rules).is_err() { + return Err(AppError::RepoNotFound(record.id.clone())); + } + Ok(()) +} + +/// Resolve the HF revision to a published release row. +/// +/// A 40-hex rev is a commit pin. `main` resolves to the newest published +/// release recorded on `main`, then on the repo's git default branch (a +/// `master` default still serves HF `main`). Any other string is a branch +/// name resolving to its newest published release. +async fn release_for_rev( + state: &AppState, + record: &RepoRecord, + rev: &str, +) -> Result, AppError> { + let rev = rev.trim(); + if rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()) { + let rel = state + .db + .model_release_by_commit(&record.id, rev) + .await? + .filter(|r| r.state == "published"); + return Ok(rel); + } + if rev == "main" { + if let Some(rel) = state + .db + .model_release_for_branch(&record.id, "main") + .await? + { + return Ok(Some(rel)); + } + if record.default_branch != "main" { + return Ok(state + .db + .model_release_for_branch(&record.id, &record.default_branch) + .await?); + } + return Ok(None); + } + Ok(state.db.model_release_for_branch(&record.id, rev).await?) +} + +/// The "no such revision" answer: `RepoNotFound` when the repo has no +/// published release at all, `RevisionNotFound` when releases exist but +/// none match `rev` (KTD8). +async fn revision_or_repo_not_found( + state: &AppState, + record: &RepoRecord, +) -> Result { + Ok( + if state.db.model_release_newest(&record.id).await?.is_none() { + hf_deny(StatusCode::NOT_FOUND, "RepoNotFound") + } else { + hf_deny(StatusCode::NOT_FOUND, "RevisionNotFound") + }, + ) +} + +/// Load and re-verify the manifest recorded for a published release. The +/// bytes' sha256 is checked against the release row, and the manifest +/// signature input was already bound to the repo owner DID at claim and +/// verification time, so nothing identity-shaped inside the artifact is +/// trusted here. +async fn load_manifest( + state: &AppState, + record: &RepoRecord, + release: &ReleaseRow, +) -> Result { + let disk = std::path::Path::new(&record.disk_path); + let bytes = git_show(&state.git_bin, disk, &release.commit_sha, MANIFEST_PATH) + .await? + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "published release {} has no manifest at its commit", + release.id + )) + })?; + if twigpine_core::cid::sha256_hex(&bytes) != release.manifest_sha256 { + return Err(AppError::Internal(anyhow::anyhow!( + "manifest sha mismatch for release {}", + release.id + ))); + } + Manifest::parse(&bytes).map_err(|e| AppError::Internal(anyhow::anyhow!("manifest parse: {e}"))) +} + +fn siblings(manifest: &Manifest) -> serde_json::Value { + serde_json::Value::Array( + manifest + .files + .iter() + .map(|f| { + let mut o = json!({"rfilename": f.path}); + if f.format == FileFormat::Pickle { + o["unsafe"] = json!(true); + } + o + }) + .collect(), + ) +} + +fn model_info_json( + record: &RepoRecord, + release: &ReleaseRow, + manifest: &Manifest, +) -> serde_json::Value { + json!({ + "id": format!("{}/{}", record.owner_did, record.name), + "modelId": format!("{}/{}", record.owner_did, record.name), + "sha": release.commit_sha, + "lastModified": release + .published_at + .clone() + .unwrap_or_else(|| release.created_at.clone()), + "private": false, + "gated": false, + "disabled": false, + "siblings": siblings(manifest), + "tags": [], + "pipeline_tag": null, + "downloads": 0, + "likes": 0, + "library_name": null, + }) +} + +/// Manifest files under `prefix` as HF tree entries. `oid` is the file's +/// sha256; chunked files also carry an `lfs` block, and pickle entries an +/// `unsafe` marker, so an HF client knows exactly what it would pull down. +fn tree_entries(manifest: &Manifest, prefix: &str) -> Vec { + let mut out = Vec::new(); + for f in &manifest.files { + if !f.path.starts_with(prefix) { + continue; + } + let mut e = json!({ + "type": "file", + "path": f.path, + "size": f.size, + "oid": f.sha256, + }); + if f.storage == StorageKind::Chunked { + e["lfs"] = json!({ + "oid": f.sha256, + "size": f.size, + "pointerSize": f.size, + }); + } + if f.format == FileFormat::Pickle { + e["unsafe"] = json!(true); + } + out.push(e); + } + out +} + +/// `GET /hf/api/models/{owner}/{repo}`, model info for the newest +/// published release (`sha` is the release commit, `siblings` the manifest +/// file list). +pub async fn hf_model_info( + State(state): State, + Path((owner, name)): Path<(String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + let Some(release) = state.db.model_release_newest(&record.id).await? else { + return Ok(hf_deny(StatusCode::NOT_FOUND, "RepoNotFound")); + }; + let manifest = load_manifest(&state, &record, &release).await?; + Ok(axum::Json(model_info_json(&record, &release, &manifest)).into_response()) +} + +/// `GET /hf/api/models/{owner}/{repo}/revision/{rev}`, model info pinned +/// to one revision. +pub async fn hf_revision_info( + State(state): State, + Path((owner, name, rev)): Path<(String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + let Some(release) = release_for_rev(&state, &record, &rev).await? else { + return revision_or_repo_not_found(&state, &record).await; + }; + let manifest = load_manifest(&state, &record, &release).await?; + Ok(axum::Json(model_info_json(&record, &release, &manifest)).into_response()) +} + +/// `GET /hf/api/models/{owner}/{repo}/tree/{rev}`, flat file list for a +/// revision. +pub async fn hf_tree( + State(state): State, + Path((owner, name, rev)): Path<(String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + tree_response(&state, &record, &rev, "").await +} + +/// `GET /hf/api/models/{owner}/{repo}/tree/{rev}/{*path}`, file list for a +/// path prefix. HF treats a tree path as a directory prefix; entries are +/// flat paths regardless. +pub async fn hf_tree_path( + State(state): State, + Path((owner, name, rev, path)): Path<(String, String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + let prefix = if path.ends_with('/') { + path + } else { + format!("{path}/") + }; + tree_response(&state, &record, &rev, &prefix).await +} + +async fn tree_response( + state: &AppState, + record: &RepoRecord, + rev: &str, + prefix: &str, +) -> Result { + let Some(release) = release_for_rev(state, record, rev).await? else { + return revision_or_repo_not_found(state, record).await; + }; + let manifest = load_manifest(state, record, &release).await?; + Ok(axum::Json(serde_json::Value::Array(tree_entries(&manifest, prefix))).into_response()) +} + +/// `GET /hf/api/models/{owner}/{repo}/refs`: `main` names the newest +/// published release's commit regardless of the repo's git default branch. +/// The HF surface is defined by releases, so a repo with none answers the +/// same RepoNotFound as every other endpoint. +pub async fn hf_refs( + State(state): State, + Path((owner, name)): Path<(String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + let Some(release) = state.db.model_release_newest(&record.id).await? else { + return Ok(hf_deny(StatusCode::NOT_FOUND, "RepoNotFound")); + }; + let branches = vec![json!({"name": "main", "targetCommit": release.commit_sha})]; + Ok(axum::Json(json!({ + "branches": branches, + "converts": [], + "tags": [], + })) + .into_response()) +} + +/// `HEAD|GET /hf/{owner}/{repo}/resolve/{rev}/{*path}`, byte-exact, +/// resumable file bytes (KTD9). `X-Repo-Commit` is on every answer, +/// including `EntryNotFound`, so a client can always pin what it read. +pub async fn hf_resolve( + State(state): State, + Path((owner, name, rev, path)): Path<(String, String, String, String)>, + method: Method, + headers: HeaderMap, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = caller_did(&auth); + let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; + require_fully_public_404(&record, &rules)?; + let Some(release) = release_for_rev(&state, &record, &rev).await? else { + return revision_or_repo_not_found(&state, &record).await; + }; + let manifest = load_manifest(&state, &record, &release).await?; + let Some(file) = manifest.files.iter().find(|f| f.path == path) else { + let mut resp = hf_deny(StatusCode::NOT_FOUND, "EntryNotFound"); + resp.headers_mut().insert( + X_REPO_COMMIT, + HeaderValue::from_str(&release.commit_sha) + .unwrap_or_else(|_| HeaderValue::from_static("")), + ); + return Ok(resp); + }; + + let etag = format!("\"{}\"", file.sha256); + + // Conditional request: a client already holding this object (weak or + // strong match, or `*`) gets a 304 with the same pinning headers, no + // body and no store read. + if let Some(cond) = headers + .get(axum::http::header::IF_NONE_MATCH) + .and_then(|v| v.to_str().ok()) + { + let hit = cond.trim() == "*" + || cond.split(',').any(|t| { + let t = t.trim(); + // If-None-Match compares weakly: strip an optional `W/`. + let t = t.strip_prefix("W/").unwrap_or(t); + t.trim_matches('"') == file.sha256 + }); + if hit { + let mut resp = Response::new(Body::empty()); + *resp.status_mut() = StatusCode::NOT_MODIFIED; + if let Ok(v) = HeaderValue::from_str(&etag) { + resp.headers_mut().insert(ETAG, v); + } + if let Ok(v) = HeaderValue::from_str(&release.commit_sha) { + resp.headers_mut().insert(X_REPO_COMMIT, v); + } + return Ok(resp); + } + } + + let range = headers + .get(axum::http::header::RANGE) + .and_then(|v| v.to_str().ok()); + let if_range = headers + .get(axum::http::header::IF_RANGE) + .and_then(|v| v.to_str().ok()); + let spec = serve::resolve(range, if_range, &etag, file.size); + let (status, _start, len) = match spec { + RangeSpec::Full => (StatusCode::OK, 0u64, file.size), + RangeSpec::Single { start, end_incl } => { + (StatusCode::PARTIAL_CONTENT, start, end_incl - start + 1) + } + RangeSpec::Unsatisfiable => { + let mut resp = hf_deny(StatusCode::RANGE_NOT_SATISFIABLE, "RangeNotSatisfiable"); + if let Ok(v) = HeaderValue::from_str(&format!("bytes */{}", file.size)) { + resp.headers_mut().insert(CONTENT_RANGE, v); + } + resp.headers_mut().insert( + X_REPO_COMMIT, + HeaderValue::from_str(&release.commit_sha) + .unwrap_or_else(|_| HeaderValue::from_static("")), + ); + resp.headers_mut() + .insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); + return Ok(resp); + } + }; + + let mut out_headers = HeaderMap::new(); + if let Ok(v) = HeaderValue::from_str(&release.commit_sha) { + out_headers.insert(X_REPO_COMMIT, v); + } + if let Ok(v) = HeaderValue::from_str(&etag) { + out_headers.insert(ETAG, v); + } + out_headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); + out_headers.insert( + CONTENT_LENGTH, + HeaderValue::from_str(&len.to_string()).unwrap_or_else(|_| HeaderValue::from_static("0")), + ); + out_headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("application/octet-stream"), + ); + if let RangeSpec::Single { start, end_incl } = spec { + if let Ok(v) = HeaderValue::from_str(&format!("bytes {start}-{end_incl}/{}", file.size)) { + out_headers.insert(CONTENT_RANGE, v); + } + } + + if method == Method::HEAD { + // Headers mirror GET (including a ranged answer's 206/416) without + // touching the store: a HEAD never opens a block stream. + let mut resp = Response::new(Body::empty()); + *resp.status_mut() = status; + resp.headers_mut().extend(out_headers); + return Ok(resp); + } + + let store: Arc = state + .block_store + .clone() + .ok_or_else(|| AppError::NotFound("model hosting not enabled".into()))?; + // Bound concurrent model downloads: a stalled reader upstream must not + // starve every other consumer of the node. + let _permit = state + .model_download_semaphore + .acquire() + .await + .map_err(|_| AppError::Internal(anyhow::anyhow!("download semaphore closed")))?; + + let body = match file.storage { + StorageKind::Git => { + // Git-stored files are under the chunking threshold, so one + // blob read is bounded by definition; a ranged answer slices it. + let bytes = git_show( + &state.git_bin, + std::path::Path::new(&record.disk_path), + &release.commit_sha, + &file.path, + ) + .await? + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "release {} file {} missing from git", + release.id, + file.path + )) + })?; + match spec { + RangeSpec::Full => Body::from(bytes), + RangeSpec::Single { start, .. } => { + let s = (start as usize).min(bytes.len()); + let e = (start as usize + len as usize).min(bytes.len()); + Body::from(bytes[s..e].to_vec()) + } + RangeSpec::Unsatisfiable => unreachable!("handled above"), + } + } + StorageKind::Chunked => { + let rec_ref = manifest.reconstruction.as_ref().ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "release {} chunked file has no reconstruction ref", + release.id + )) + })?; + let rec_bytes = crate::models::read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("reconstruction read: {e}")))?; + let rec = Reconstruction::parse(&rec_bytes) + .map_err(|e| AppError::Internal(anyhow::anyhow!("reconstruction parse: {e}")))?; + let entry = rec + .files + .iter() + .find(|e| e.path == file.path) + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "reconstruction has no entry for {}", + file.path + )) + })?; + let (want_start, want_end) = match spec { + RangeSpec::Full => (0u64, file.size), + RangeSpec::Single { start, end_incl } => (start, end_incl + 1), + RangeSpec::Unsatisfiable => unreachable!("handled above"), + }; + let slices = twigpine_core::model::reconstruction::map_file_range( + entry, &rec, want_start, want_end, + ) + .map_err(|e| AppError::Internal(anyhow::anyhow!("range map: {e}")))?; + Body::from_stream(serve::slices_stream(store, slices)) + } + }; + + let mut resp = Response::new(body); + *resp.status_mut() = status; + resp.headers_mut().extend(out_headers); + Ok(resp) +} diff --git a/crates/twigpine-node/src/api/mod.rs b/crates/twigpine-node/src/api/mod.rs index 5d69fadd..409d3f38 100644 --- a/crates/twigpine-node/src/api/mod.rs +++ b/crates/twigpine-node/src/api/mod.rs @@ -10,6 +10,7 @@ pub mod certs; pub mod changelog; pub mod encrypted; pub mod events; +pub mod hf; pub mod ipfs; pub mod issues; pub mod labels; @@ -1204,6 +1205,7 @@ mod tests { async fn t() { let _ = did_matches(x, y); } } (include_str!("changelog.rs"), "changelog.rs"), (include_str!("encrypted.rs"), "encrypted.rs"), (include_str!("events.rs"), "events.rs"), + (include_str!("hf.rs"), "hf.rs"), (include_str!("issues.rs"), "issues.rs"), (include_str!("labels.rs"), "labels.rs"), (include_str!("models.rs"), "models.rs"), diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 480d81a2..a53afa69 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -39,7 +39,7 @@ fn hosting_enabled(state: &AppState) -> Result<()> { /// 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<()> { +pub(crate) fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { // 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 diff --git a/crates/twigpine-node/src/arweave.rs b/crates/twigpine-node/src/arweave.rs index 76383eaa..ca026762 100644 --- a/crates/twigpine-node/src/arweave.rs +++ b/crates/twigpine-node/src/arweave.rs @@ -103,6 +103,129 @@ pub async fn anchor_ref_update( Ok(tx_id) } +/// The compact release anchor (KTD10). One permanent record per published +/// model release: the pointers an independent consumer needs to rebuild the +/// release (manifest, reconstruction, and the sha256-to-provider-CID block +/// map, all pinned on IPFS) plus the publisher's claim signature. +/// +/// Identity fields are RECORD-KEEPING ONLY. `owner_did` and `node_did` +/// inside this payload are attacker-controllable text: an independent +/// consumer binds manifest verification to a DID it already trusts +/// (fetched or pinned out of band), never to a DID read out of the anchor. +#[derive(Debug, Clone)] +pub struct ReleaseAnchor { + /// `"owner/name"` on the node. + pub repo: String, + pub owner_did: String, + /// The release commit the manifest and signature live in. + pub release_commit: String, + /// sha256 of the manifest bytes, the content key the manifest is + /// resolved by (the CID beside it is provider metadata). + pub manifest_sha256: String, + /// Provider CID the manifest bytes were pinned under. + pub manifest_cid: String, + /// sha256 and provider CID of the reconstruction object, when the + /// release has chunked files. + pub reconstruction_sha256: Option, + pub reconstruction_cid: Option, + /// Provider CID of the block map object (sha256 -> provider CID for + /// every content block the release references). + pub block_map_cid: String, + /// The publisher's detached manifest signature (base64), so the anchor + /// alone reproves the release once the consumer has manifest bytes and + /// an externally anchored owner DID. + pub claim_signature: String, + pub timestamp: String, + pub node_did: String, +} + +/// Anchor a model release root to Arweave via Irys. +/// +/// The payload is a few hundred bytes: the file and block sets live behind +/// `block_map_cid` on IPFS rather than inline, so the anchor stays far +/// under the 100 KiB free-upload ceiling even for a 5,000-file, +/// 3,000-block release. Returns the Irys transaction ID, or `Ok("")` when +/// `irys_url` is empty (anchoring disabled). +pub async fn anchor_model_release( + client: &reqwest::Client, + irys_url: &str, + anchor: &ReleaseAnchor, +) -> Result { + if irys_url.is_empty() { + return Ok(String::new()); + } + + let body = serde_json::to_vec(&release_anchor_payload(anchor))?; + let url = format!("{}/upload", irys_url.trim_end_matches('/')); + + let resp = client + .post(&url) + .header("Content-Type", "application/json") + .header("x-irys-tags", build_release_tags_header(anchor)) + .body(body) + .send() + .await + .map_err(|e| anyhow::anyhow!("Irys upload failed: {e}"))?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + return Err(anyhow::anyhow!("Irys returned {status}: {body}")); + } + + let json: serde_json::Value = resp + .json() + .await + .map_err(|e| anyhow::anyhow!("failed to parse Irys response: {e}"))?; + + let tx_id = json["id"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("no 'id' in Irys response: {json}"))? + .to_string(); + + tracing::info!( + repo = %anchor.repo, + commit = %anchor.release_commit, + tx_id = %tx_id, + "anchored model release to Arweave" + ); + + Ok(tx_id) +} + +/// The anchored JSON. Kept as its own function so the size and parse-back +/// guarantees are unit-testable without an HTTP mock. +pub fn release_anchor_payload(anchor: &ReleaseAnchor) -> serde_json::Value { + json!({ + "schema": "gitlawb/model-release-anchor/v1", + "repo": anchor.repo, + "owner_did": anchor.owner_did, + "release_commit": anchor.release_commit, + "manifest_sha256": anchor.manifest_sha256, + "manifest_cid": anchor.manifest_cid, + "reconstruction_sha256": anchor.reconstruction_sha256, + "reconstruction_cid": anchor.reconstruction_cid, + "block_map_cid": anchor.block_map_cid, + "claim_signature": anchor.claim_signature, + "timestamp": anchor.timestamp, + "node_did": anchor.node_did, + }) +} + +/// Irys tag header for a release anchor. The five tags a discovery query +/// needs; identity tags are indexable metadata, not authorization input. +fn build_release_tags_header(anchor: &ReleaseAnchor) -> String { + [ + "App-Name:gitlawb".to_string(), + "Schema:gitlawb/model-release-anchor/v1".to_string(), + format!("Repo:{}", sanitize_tag(&anchor.repo)), + format!("Owner-DID:{}", sanitize_tag(&anchor.owner_did)), + format!("Release-Commit:{}", sanitize_tag(&anchor.release_commit)), + format!("Node-DID:{}", sanitize_tag(&anchor.node_did)), + ] + .join(",") +} + /// A per-push manifest of the blobs encrypted this push (Option B3). The /// `blobs` slice is `(oid, cid)` tuples. Anchored directly to Arweave as its JSON /// body so the discovery index survives total node loss. Recipient identities are @@ -413,4 +536,96 @@ mod tests { assert_eq!(sanitize_tag("alice/myrepo"), "alice/myrepo"); assert_eq!(sanitize_tag("hello world!"), "helloworld"); } + + fn release_anchor() -> ReleaseAnchor { + ReleaseAnchor { + repo: "did:key:z6Mkowner/m".into(), + owner_did: "did:key:z6Mkowner".into(), + release_commit: "a".repeat(40), + manifest_sha256: "b".repeat(64), + manifest_cid: "bafkreimanifestcid".into(), + reconstruction_sha256: Some("c".repeat(64)), + reconstruction_cid: Some("bafkreireccid".into()), + block_map_cid: "bafkreimapcid".into(), + claim_signature: "c2ln".into(), + timestamp: "2026-03-14T00:00:00Z".into(), + node_did: "did:key:z6Mknode".into(), + } + } + + #[tokio::test] + async fn test_model_release_anchor_noop_when_url_empty() { + let client = reqwest::Client::new(); + assert_eq!( + anchor_model_release(&client, "", &release_anchor()) + .await + .unwrap(), + "" + ); + } + + #[tokio::test] + async fn test_model_release_anchor_posts_payload_and_tags() { + let mut server = mockito::Server::new_async().await; + let _mock = server + .mock("POST", "/upload") + .match_header( + "x-irys-tags", + mockito::Matcher::AllOf(vec![ + mockito::Matcher::Regex("App-Name:gitlawb".to_string()), + mockito::Matcher::Regex( + "Schema:gitlawb/model-release-anchor/v1".to_string(), + ), + mockito::Matcher::Regex(format!("Release-Commit:{}", "a".repeat(40))), + ]), + ) + .match_body(mockito::Matcher::AllOf(vec![ + mockito::Matcher::PartialJsonString( + r#"{"schema":"gitlawb/model-release-anchor/v1"}"#.to_string(), + ), + mockito::Matcher::PartialJsonString( + r#"{"block_map_cid":"bafkreimapcid"}"#.to_string(), + ), + mockito::Matcher::PartialJsonString( + r#"{"manifest_sha256":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}"# + .to_string(), + ), + ])) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"RELTX1","timestamp":1710000000000}"#) + .create_async() + .await; + + let client = reqwest::Client::new(); + let tx = anchor_model_release(&client, &server.url(), &release_anchor()) + .await + .expect("anchor posts"); + assert_eq!(tx, "RELTX1"); + _mock.assert_async().await; + } + + #[test] + fn release_anchor_payload_stays_compact_and_parseable() { + let anchor = release_anchor(); + let v = release_anchor_payload(&anchor); + let bytes = serde_json::to_vec(&v).unwrap(); + // The anchor must stay far under the Irys 100 KiB free-upload + // ceiling: everything larger lives behind the block-map CID. + assert!( + bytes.len() < 4 * 1024, + "anchor payload grew: {} bytes", + bytes.len() + ); + let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + parsed["schema"].as_str(), + Some("gitlawb/model-release-anchor/v1") + ); + assert_eq!( + parsed["release_commit"].as_str(), + Some("a".repeat(40).as_str()) + ); + assert_eq!(parsed["claim_signature"].as_str(), Some("c2ln")); + } } diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index 24c09296..b02efbd0 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -1302,8 +1302,10 @@ mod tests { git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys(16), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), + hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store: None, + model_download_semaphore: Arc::new(tokio::sync::Semaphore::new(64)), } } diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index bb56a020..85c1dadf 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1022,6 +1022,22 @@ pub struct Config { /// operations, share this per-IP budget with REST task reads. #[arg(long, env = "TWIGPINE_TASK_READ_RATE_LIMIT", default_value_t = 1200)] pub task_read_rate_limit: usize, + + /// Per-client-IP rate limit for the HF-compatible model read routes + /// (`/hf/api/models/...` and `/hf/.../resolve/...`), in requests per hour. + /// These reads run the publicity gate plus release and manifest lookups + /// before any answer, so the brake bounds the cost of anonymous probes. + /// Keyed on the resolved client IP via `TWIGPINE_TRUSTED_PROXY`. + /// `0` disables. Default: 600. + #[arg(long, env = "TWIGPINE_HF_READ_RATE_LIMIT", default_value_t = 600)] + pub hf_read_rate_limit: usize, + + /// Maximum concurrent model `resolve` body streams. A chunked download + /// holds block-store connections for the life of the response, so this + /// bounds how many slow readers can run before later requests defer. + /// Default: 16. + #[arg(long, env = "TWIGPINE_MODEL_DOWNLOAD_PERMITS", default_value_t = 16)] + pub model_download_permits: usize, } /// Default for `--key-path`. Resolved through [`default_key_location`]. diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 3db76275..c478f529 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -797,6 +797,313 @@ impl Db { .await?; Ok(()) } + + // ── release resolution (HF read surface) ─────────────────────────────── + + /// The newest published release recorded on `branch` (the revision + /// resolution the HF read surface applies). + pub async fn model_release_for_branch( + &self, + repo_id: &str, + branch: &str, + ) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND branch = $2 AND state = 'published' + ORDER BY id DESC LIMIT 1" + )) + .bind(repo_id) + .bind(branch) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// The newest published release on the repo, whatever branch recorded it + /// (the `refs` endpoint's default target). + pub async fn model_release_newest(&self, repo_id: &str) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND state = 'published' + ORDER BY id DESC LIMIT 1" + )) + .bind(repo_id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// The reconstruction object's sha for a release, when the manifest + /// declared one (all-git releases have none). `ModelRelease` does not + /// carry the column; the durability enqueue needs it directly. + pub async fn model_release_reconstruction_sha( + &self, + release_id: i64, + ) -> Result> { + Ok( + sqlx::query_scalar("SELECT reconstruction_sha256 FROM model_releases WHERE id = $1") + .bind(release_id) + .fetch_optional(&self.pool) + .await? + .flatten(), + ) + } + + /// Every block a release references, in stable order. The + /// `pin_block` job material and (after the pins land) the block-CID + /// map's key set. + pub async fn model_release_blocks(&self, release_id: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT block_sha256 FROM model_release_blocks + WHERE release_id = $1 ORDER BY block_sha256", + ) + .bind(release_id) + .fetch_all(&self.pool) + .await?) + } + + // ── durability jobs ──────────────────────────────────────────────────── + + /// Idempotent enqueue: the (release, kind, object) unique key makes a + /// re-run a no-op, so the publish path, a retry, and the startup + /// backfill all share it. One statement, so a release's job set is + /// all-or-nothing. + pub async fn model_durability_enqueue( + &self, + release_id: i64, + jobs: &[(String, String)], + ) -> Result { + if jobs.is_empty() { + return Ok(0); + } + let kinds: Vec<&str> = jobs.iter().map(|(k, _)| k.as_str()).collect(); + let keys: Vec<&str> = jobs.iter().map(|(_, o)| o.as_str()).collect(); + let now = ts_now(); + let inserted = sqlx::query( + "INSERT INTO model_durability_jobs + (release_id, kind, object_key, state, attempts, created_at, updated_at) + SELECT $1, j.k, j.o, 'pending', 0, $2, $2 + FROM unnest($3::text[], $4::text[]) AS j(k, o) + ON CONFLICT (release_id, kind, object_key) DO NOTHING", + ) + .bind(release_id) + .bind(now) + .bind(&kinds) + .bind(&keys) + .execute(&self.pool) + .await? + .rows_affected(); + Ok(inserted) + } + + /// Published releases with no durability rows at all: the startup + /// backfill set. A release's rows are inserted atomically, so "none" + /// cannot split from "partial" under a crash. + pub async fn model_releases_missing_durability(&self, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT r.id FROM model_releases r + WHERE r.state = 'published' + AND NOT EXISTS ( + SELECT 1 FROM model_durability_jobs j WHERE j.release_id = r.id) + ORDER BY r.id LIMIT $1", + ) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + /// Oldest pending jobs, bounded. A pending row is work the worker has + /// not completed; a `failed` row stays out of the drain (an operator + /// or a later fix decides it, not the loop). + pub async fn model_durability_pending(&self, limit: i64) -> Result> { + Ok(sqlx::query_as::<_, DurabilityTuple>( + "SELECT id, release_id, kind, object_key, state, attempts, provider_cid + FROM model_durability_jobs + WHERE state = 'pending' ORDER BY id LIMIT $1", + ) + .bind(limit) + .fetch_all(&self.pool) + .await? + .into_iter() + .map(Into::into) + .collect()) + } + + /// Record the provider CID and mark the job done. The CID is metadata: + /// `object_key` (the sha256) stays the resolver key no matter what the + /// provider answered. + pub async fn model_durability_done(&self, id: i64, provider_cid: &str) -> Result<()> { + sqlx::query( + "UPDATE model_durability_jobs + SET state = 'done', provider_cid = $2, last_error = NULL, updated_at = $3 + WHERE id = $1 AND state = 'pending'", + ) + .bind(id) + .bind(provider_cid) + .bind(ts_now()) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Bump the attempt count and record the error, leaving the job + /// pending for the next pass. Returns the new attempt count so the + /// caller can fail the job past its retry budget. + pub async fn model_durability_record_error(&self, id: i64, err: &str) -> Result { + Ok(sqlx::query_scalar( + "UPDATE model_durability_jobs + SET attempts = attempts + 1, last_error = $2, updated_at = $3 + WHERE id = $1 + RETURNING attempts", + ) + .bind(id) + .bind(err) + .bind(ts_now()) + .fetch_one(&self.pool) + .await?) + } + + /// Terminal failure: the job leaves the drain set until an operator + /// (or a corrected re-enqueue path) resets it. + pub async fn model_durability_mark_failed(&self, id: i64, err: &str) -> Result<()> { + sqlx::query( + "UPDATE model_durability_jobs + SET state = 'failed', last_error = $2, updated_at = $3 + WHERE id = $1", + ) + .bind(id) + .bind(err) + .bind(ts_now()) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Fail every pending job for a release in one update: the + /// "repo is no longer fully public" stop, where nothing further is + /// pinned and the anchor never posts. + pub async fn model_durability_fail_pending( + &self, + release_id: i64, + reason: &str, + ) -> Result { + Ok(sqlx::query( + "UPDATE model_durability_jobs + SET state = 'failed', last_error = $2, updated_at = $3 + WHERE release_id = $1 AND state = 'pending'", + ) + .bind(release_id) + .bind(reason) + .bind(ts_now()) + .execute(&self.pool) + .await? + .rows_affected()) + } + + /// (pending, failed) counts for a release's jobs of `kind`, the + /// `pin_block_map` gate (`pin_block`) and the anchor gate. + pub async fn model_durability_kind_counts( + &self, + release_id: i64, + kind: &str, + ) -> Result<(i64, i64)> { + let (pending, failed): (Option, Option) = sqlx::query_as( + "SELECT COUNT(*) FILTER (WHERE state = 'pending'), + COUNT(*) FILTER (WHERE state = 'failed') + FROM model_durability_jobs + WHERE release_id = $1 AND kind = $2", + ) + .bind(release_id) + .bind(kind) + .fetch_one(&self.pool) + .await?; + Ok((pending.unwrap_or(0), failed.unwrap_or(0))) + } + + /// (pending, failed) counts for a release's jobs of every kind EXCEPT + /// `kind`, the anchor gate ("only after all pin jobs are done"). + pub async fn model_durability_other_counts( + &self, + release_id: i64, + kind: &str, + ) -> Result<(i64, i64)> { + let (pending, failed): (Option, Option) = sqlx::query_as( + "SELECT COUNT(*) FILTER (WHERE state = 'pending'), + COUNT(*) FILTER (WHERE state = 'failed') + FROM model_durability_jobs + WHERE release_id = $1 AND kind <> $2", + ) + .bind(release_id) + .bind(kind) + .fetch_one(&self.pool) + .await?; + Ok((pending.unwrap_or(0), failed.unwrap_or(0))) + } + + /// (object_key, provider_cid) pairs for done jobs of `kind`, keyed so + /// the block map can map every block sha to its provider CID. + pub async fn model_durability_done_cids( + &self, + release_id: i64, + kind: &str, + ) -> Result> { + Ok(sqlx::query_as( + "SELECT object_key, provider_cid FROM model_durability_jobs + WHERE release_id = $1 AND kind = $2 AND state = 'done' + ORDER BY object_key", + ) + .bind(release_id) + .bind(kind) + .fetch_all(&self.pool) + .await?) + } + + /// The provider CID of the done job of `kind`, when one exists + /// (manifest, reconstruction, map lookups for the anchor payload). + pub async fn model_durability_done_cid( + &self, + release_id: i64, + kind: &str, + ) -> Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT provider_cid FROM model_durability_jobs + WHERE release_id = $1 AND kind = $2 AND state = 'done' + LIMIT 1", + ) + .bind(release_id) + .bind(kind) + .fetch_optional(&self.pool) + .await? + .flatten()) + } +} + +/// One `model_durability_jobs` row. +#[derive(Debug, Clone)] +pub struct DurabilityJob { + pub id: i64, + pub release_id: i64, + pub kind: String, + pub object_key: String, + pub state: String, + pub attempts: i32, + pub provider_cid: Option, +} + +type DurabilityTuple = (i64, i64, String, String, String, i32, Option); + +impl From for DurabilityJob { + fn from(t: DurabilityTuple) -> Self { + DurabilityJob { + id: t.0, + release_id: t.1, + kind: t.2, + object_key: t.3, + state: t.4, + attempts: t.5, + provider_cid: t.6, + } + } } #[cfg(test)] diff --git a/crates/twigpine-node/src/ipfs_pin.rs b/crates/twigpine-node/src/ipfs_pin.rs index 8490baaa..848fecb9 100644 --- a/crates/twigpine-node/src/ipfs_pin.rs +++ b/crates/twigpine-node/src/ipfs_pin.rs @@ -1707,6 +1707,24 @@ pub async fn pin_git_object( Ok(cid) } +/// Pin one model content object's bytes on the local Kubo node. +/// +/// This is [`pin_git_object`] under a name that says what the durability +/// worker is doing: the bytes are arbitrary content, the add goes in with +/// `raw-leaves=true&cid-version=1&pin=true`, and the returned `Hash` is a +/// PROVIDER CID recorded next to (never instead of) the sha256 that keys +/// the object. For objects over Kubo's chunk threshold the returned CID is +/// the dag-pb root rather than the raw-leaf CID the small-object case +/// computes locally. +pub async fn pin_model_object( + ipfs_api: &str, + sha256_hex: &str, + data: &[u8], + request_timeout: Option, +) -> Result { + pin_git_object(ipfs_api, sha256_hex, data, request_timeout).await +} + /// Fetch raw bytes for a CID from the local Kubo node (`/api/v0/cat`). pub async fn cat(ipfs_api: &str, cid: &str) -> Result> { if ipfs_api.is_empty() { diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 881632ec..6a2a133f 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -636,8 +636,16 @@ pub async fn run() -> Result<()> { std::time::Duration::from_secs(3600), 200_000, ), + hf_read_rate_limiter: rate_limit::RateLimiter::new_bounded( + config.hf_read_rate_limit, + std::time::Duration::from_secs(3600), + 200_000, + ), git_bin: "git".to_string(), block_store, + model_download_semaphore: Arc::new(tokio::sync::Semaphore::new( + config.model_download_permits.max(1), + )), }; // One-time re-encryption of any webhook HMAC secrets still resting as @@ -662,6 +670,9 @@ pub async fn run() -> Result<()> { if config.task_read_rate_limit == 0 { tracing::warn!("TWIGPINE_TASK_READ_RATE_LIMIT=0 — per-IP task read rate limiting disabled"); } + if config.hf_read_rate_limit == 0 { + tracing::warn!("TWIGPINE_HF_READ_RATE_LIMIT=0: per-IP HF read rate limiting disabled"); + } // Periodic peer-count poll for the metrics gauge. If p2p is disabled // we still set the gauge to 0 so dashboards don't show "no data". @@ -923,6 +934,9 @@ pub async fn run() -> Result<()> { state.clone(), ))); model_workers.push(tokio::spawn(models::sweep::run_sweep_worker(state.clone()))); + model_workers.push(tokio::spawn(models::durability::run_durability_worker( + state.clone(), + ))); } // `into_make_service_with_connect_info` exposes the socket peer address as @@ -1781,6 +1795,7 @@ mod rate_limiter_sweep_tests { state.ipfs_rate_limiter = RateLimiter::new(10, window); state.ipfs_work_rate_limiter = RateLimiter::new(10, window); state.task_read_rate_limiter = RateLimiter::new(10, window); + state.hf_read_rate_limiter = RateLimiter::new(10, window); let limiters = |s: &crate::state::AppState| { [ @@ -1795,6 +1810,7 @@ mod rate_limiter_sweep_tests { s.ipfs_rate_limiter.clone(), s.ipfs_work_rate_limiter.clone(), s.task_read_rate_limiter.clone(), + s.hf_read_rate_limiter.clone(), ] }; for l in limiters(&state) { diff --git a/crates/twigpine-node/src/models/durability.rs b/crates/twigpine-node/src/models/durability.rs new file mode 100644 index 00000000..fc8e8dc4 --- /dev/null +++ b/crates/twigpine-node/src/models/durability.rs @@ -0,0 +1,994 @@ +//! Durability outbox for published releases (KTD10, KTD13). +//! +//! Publishing a release enqueues one job per content object: +//! `pin_block` for every block the release references, `pin_manifest` and +//! `pin_reconstruction` for the git-resident objects, `pin_block_map` for +//! the sha256-to-provider-CID map, and `anchor` for the Irys release root. +//! Jobs are keyed `(release, kind, object)` so re-enqueueing is a no-op, +//! and the startup backfill inserts missing sets atomically. +//! +//! The worker drains pending jobs oldest-first under a batch budget. Each +//! pin re-checks the repository is still fully public and holds a +//! `PolicyFence` across the irreversible provider call, so a repo turned +//! private mid-drain stops every sibling job and the anchor never posts. +//! Provider CIDs are recorded in `provider_cid` beside `object_key`: the +//! sha256 stays the resolver key no matter what a provider answered. +//! +//! A failed job stays `pending` (attempts bumped) until `MAX_ATTEMPTS`, +//! then `failed`; an anchor outage therefore leaves the anchor pending +//! while local downloads keep serving. Nothing in this module gates the +//! read surface. + +use std::time::Duration; + +use crate::db::model_queries::DurabilityJob; +use crate::error::AppError; +use crate::ipfs_pin::PolicyFence; +use crate::models::claim::git_show; +use crate::state::AppState; + +pub const KIND_BLOCK: &str = "pin_block"; +pub const KIND_MANIFEST: &str = "pin_manifest"; +pub const KIND_RECONSTRUCTION: &str = "pin_reconstruction"; +pub const KIND_BLOCK_MAP: &str = "pin_block_map"; +pub const KIND_ANCHOR: &str = "anchor"; + +/// Attempts before a job leaves the drain set as `failed`. +const MAX_ATTEMPTS: i32 = 8; +/// Jobs drained per worker pass; a larger backlog rolls to the next tick. +const DRAIN_BATCH: i64 = 32; +/// Releases one backfill pass enqueues for. +const BACKFILL_BATCH: i64 = 64; +/// Worker cadence. Short enough that a publish lands pins promptly, long +/// enough that an empty drain is cheap. +const TICK_SECS: u64 = 30; + +const MANIFEST_PATH: &str = ".twigpine/model-release.json"; +const SIG_PATH: &str = ".twigpine/model-release.sig"; + +/// Enqueue the full job set for one published release. Idempotent: the +/// `(release, kind, object)` unique key makes a second call insert +/// nothing, so the publish hook, a retry, and the startup backfill share +/// this entry point. +pub async fn enqueue_for_release(state: &AppState, release_id: i64) -> Result<(), AppError> { + let Some(release) = state.db.model_release_by_id(release_id).await? else { + return Ok(()); + }; + if release.state != "published" { + return Ok(()); + } + let mut jobs: Vec<(String, String)> = state + .db + .model_release_blocks(release_id) + .await? + .into_iter() + .map(|sha| (KIND_BLOCK.to_string(), sha)) + .collect(); + jobs.push((KIND_MANIFEST.to_string(), release.manifest_sha256.clone())); + if let Some(rec_sha) = state + .db + .model_release_reconstruction_sha(release_id) + .await? + { + jobs.push((KIND_RECONSTRUCTION.to_string(), rec_sha)); + } + // Release-level jobs key on the commit: it scopes the row, nothing + // resolves object bytes through it. + jobs.push((KIND_BLOCK_MAP.to_string(), release.commit_sha.clone())); + jobs.push((KIND_ANCHOR.to_string(), release.commit_sha)); + state.db.model_durability_enqueue(release_id, &jobs).await?; + Ok(()) +} + +/// Startup/repair backfill: enqueue the full job set for every published +/// release that has none. The enqueue is one `INSERT ... ON CONFLICT DO +/// NOTHING` per release, so a crash mid-backfill leaves no partial set. +async fn backfill_missing(state: &AppState) -> Result<(), AppError> { + for release_id in state + .db + .model_releases_missing_durability(BACKFILL_BATCH) + .await? + { + enqueue_for_release(state, release_id).await?; + } + Ok(()) +} + +/// One worker pass: backfill, then drain a bounded batch of pending jobs. +/// Exposed for tests; the worker loop calls it every tick. +pub async fn durability_pass(state: &AppState) -> Result<(), AppError> { + backfill_missing(state).await?; + for job in state.db.model_durability_pending(DRAIN_BATCH).await? { + process_job(state, &job).await?; + } + Ok(()) +} + +/// The durability worker: backfill, drain, tick. Exits on node shutdown. +pub async fn run_durability_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); + let mut interval = tokio::time::interval(Duration::from_secs(TICK_SECS)); + loop { + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } + if let Err(e) = durability_pass(&state).await { + tracing::warn!("model durability pass failed: {e}"); + } + } +} + +/// Whether the repo a release belongs to may still be published outbound: +/// fully public, no visibility rules, no mirror row, not quarantined. A +/// `false` means every pending job for the release stops and the anchor +/// must never post (KTD10: pins stop when publicity changes). +async fn still_publishable(state: &AppState, repo_id: &str) -> Result { + let Some(record) = state.db.get_repo_by_id(repo_id).await? else { + return Ok(false); + }; + if !record.is_public || record.id.contains('/') { + return Ok(false); + } + if state.db.is_repo_quarantined(&record.id).await? { + return Ok(false); + } + Ok(state.db.list_visibility_rules(&record.id).await?.is_empty()) +} + +/// Process one pending job. Errors are recorded (attempts bumped, failed +/// past `MAX_ATTEMPTS`) rather than propagated, so one wedged provider +/// cannot stall the drain behind it. +async fn process_job(state: &AppState, job: &DurabilityJob) -> Result<(), AppError> { + let Some(release) = state.db.model_release_by_id(job.release_id).await? else { + state + .db + .model_durability_mark_failed(job.id, "release row is gone") + .await?; + return Ok(()); + }; + if release.state != "published" { + state + .db + .model_durability_mark_failed(job.id, "release is no longer published") + .await?; + return Ok(()); + } + + // A gated job waits for its inputs rather than erroring: the map waits + // on the block pins, the anchor waits on everything else. + match job.kind.as_str() { + KIND_BLOCK_MAP => { + let (pending, failed) = state + .db + .model_durability_kind_counts(job.release_id, KIND_BLOCK) + .await?; + if pending > 0 { + return Ok(()); + } + if failed > 0 { + state + .db + .model_durability_mark_failed( + job.id, + "a block pin failed; the map would be incomplete", + ) + .await?; + return Ok(()); + } + } + KIND_ANCHOR => { + let (pending, failed) = state + .db + .model_durability_other_counts(job.release_id, KIND_ANCHOR) + .await?; + if pending > 0 { + return Ok(()); + } + if failed > 0 { + state + .db + .model_durability_mark_failed( + job.id, + "a pin job failed; the anchor would be incomplete", + ) + .await?; + return Ok(()); + } + } + _ => {} + } + + if !still_publishable(state, &release.repo_id).await? { + state + .db + .model_durability_fail_pending(job.release_id, "repository is no longer fully public") + .await?; + return Ok(()); + } + + // The policy fence is checked immediately before the irreversible + // provider call; a stale epoch re-runs the publicity check rather than + // assuming the bump was publicity-shaped. + let fence = PolicyFence::capture(&state.db, &release.repo_id).await; + + let result = execute_job(state, &release, job, fence.as_ref()).await; + match result { + Ok(JobOutcome::Deferred) => Ok(()), + Ok(JobOutcome::Done(cid)) => { + state.db.model_durability_done(job.id, &cid).await?; + Ok(()) + } + Err(e) => { + let attempts = state + .db + .model_durability_record_error(job.id, &e.to_string()) + .await?; + if attempts >= MAX_ATTEMPTS { + state + .db + .model_durability_mark_failed(job.id, &e.to_string()) + .await?; + } + Ok(()) + } + } +} + +enum JobOutcome { + /// The job's inputs are not ready yet; it stays pending untouched. + Deferred, + /// Provider work completed; the string is the recorded provider CID + /// (or anchor tx id), never the resolver key. + Done(String), +} + +/// Run the job's own work. `fence` is the captured policy epoch, checked +/// right before each provider call. +async fn execute_job( + state: &AppState, + release: &crate::models::ReleaseRow, + job: &DurabilityJob, + fence: Option<&PolicyFence>, +) -> Result { + match job.kind.as_str() { + KIND_BLOCK | KIND_RECONSTRUCTION => { + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("no block store")))?; + let id = crate::blockstore::BlockId::parse(&job.object_key) + .map_err(|e| AppError::Internal(anyhow::anyhow!("bad object key: {e}")))?; + let len = store + .size(&id) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")))? + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "object {} is not in the block store", + job.object_key + )) + })?; + let bytes = crate::models::read_block(&store, &job.object_key, len) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("block read failed: {e}")))?; + pin_bytes(state, &job.object_key, &bytes, fence).await + } + KIND_MANIFEST => { + let bytes = git_bytes(state, release, MANIFEST_PATH).await?; + pin_bytes(state, &job.object_key, &bytes, fence).await + } + KIND_BLOCK_MAP => { + let pairs = state + .db + .model_durability_done_cids(job.release_id, KIND_BLOCK) + .await?; + let map: serde_json::Map = pairs + .into_iter() + .map(|(sha, cid)| (sha, serde_json::Value::String(cid))) + .collect(); + let payload = serde_json::json!({ + "schema": "gitlawb/model-block-map/v1", + "release": release.commit_sha, + "blocks": map, + }); + let bytes = serde_json::to_vec(&payload) + .map_err(|e| AppError::Internal(anyhow::anyhow!("block map serialize: {e}")))?; + pin_bytes(state, &job.object_key, &bytes, fence).await + } + KIND_ANCHOR => post_anchor(state, release, job, fence).await, + other => Err(AppError::Internal(anyhow::anyhow!( + "unknown durability job kind {other}" + ))), + } +} + +/// Read a path out of the release commit (manifest, signature). A missing +/// object is a job error like a missing store block: retry until the +/// attempt budget fails it. +async fn git_bytes( + state: &AppState, + release: &crate::models::ReleaseRow, + path: &str, +) -> Result, AppError> { + let record = state + .db + .get_repo_by_id(&release.repo_id) + .await? + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("repo row gone")))?; + git_show( + &state.git_bin, + std::path::Path::new(&record.disk_path), + &release.commit_sha, + path, + ) + .await? + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!( + "release {} has no {path} at its commit", + release.id + )) + }) +} + +/// Pin `data` under `object_key` on every configured provider (Kubo, then +/// Pinata), fenced. The fence is checked immediately before the first +/// upload so a publicity change between the job-top check and here cannot +/// push one more object out. +async fn pin_bytes( + state: &AppState, + object_key: &str, + data: &[u8], + fence: Option<&PolicyFence>, +) -> Result { + if let Some(f) = fence { + if !f.is_current().await { + return Ok(JobOutcome::Deferred); + } + } + let kubo = crate::ipfs_pin::pin_model_object( + &state.config.ipfs_api, + object_key, + data, + Some(Duration::from_secs(120)), + ) + .await + .map_err(AppError::Internal)?; + let pinata = crate::pinata::pin_model_object( + &state.http_client, + &state.config.pinata_upload_url, + &state.config.pinata_jwt, + object_key, + data, + ) + .await + .map_err(AppError::Internal)?; + // The recorded CID is provider metadata. Prefer Kubo's confirmed + // answer, then Pinata's; when neither provider is configured the + // locally computed raw CID still gives the map a real address (the + // local store remains the canonical resolution path anyway). + let cid = if !kubo.is_empty() { + kubo + } else if !pinata.is_empty() { + pinata + } else { + twigpine_core::cid::Cid::from_git_object_bytes(data).to_string() + }; + Ok(JobOutcome::Done(cid)) +} + +/// Gather the release root and post the Irys anchor. Disabled Irys is a +/// completed job, not an error: the operator configured no anchor tier, +/// and leaving the job pending forever would pin the whole drain set. +async fn post_anchor( + state: &AppState, + release: &crate::models::ReleaseRow, + job: &DurabilityJob, + fence: Option<&PolicyFence>, +) -> Result { + if state.config.irys_url.is_empty() { + return Ok(JobOutcome::Done(String::new())); + } + let manifest_cid = state + .db + .model_durability_done_cid(job.release_id, KIND_MANIFEST) + .await? + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("manifest pin has no provider CID")))?; + let block_map_cid = state + .db + .model_durability_done_cid(job.release_id, KIND_BLOCK_MAP) + .await? + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block map pin has no provider CID")))?; + let (rec_sha, rec_cid) = match state + .db + .model_release_reconstruction_sha(job.release_id) + .await? + { + Some(sha) => { + let cid = state + .db + .model_durability_done_cid(job.release_id, KIND_RECONSTRUCTION) + .await? + .ok_or_else(|| { + AppError::Internal(anyhow::anyhow!("reconstruction pin has no provider CID")) + })?; + (Some(sha), Some(cid)) + } + None => (None, None), + }; + let signature = String::from_utf8(git_bytes(state, release, SIG_PATH).await?) + .map_err(|_| AppError::Internal(anyhow::anyhow!("model-release.sig is not utf-8")))?; + let record = state + .db + .get_repo_by_id(&release.repo_id) + .await? + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("repo row gone")))?; + + if let Some(f) = fence { + if !f.is_current().await { + return Ok(JobOutcome::Deferred); + } + } + let anchor = crate::arweave::ReleaseAnchor { + repo: format!("{}/{}", record.owner_did, record.name), + owner_did: record.owner_did.clone(), + release_commit: release.commit_sha.clone(), + manifest_sha256: release.manifest_sha256.clone(), + manifest_cid, + reconstruction_sha256: rec_sha, + reconstruction_cid: rec_cid, + block_map_cid, + claim_signature: signature.trim().to_string(), + timestamp: chrono::Utc::now().to_rfc3339(), + node_did: state.node_did.as_str().to_string(), + }; + let tx = + crate::arweave::anchor_model_release(&state.http_client, &state.config.irys_url, &anchor) + .await + .map_err(AppError::Internal)?; + Ok(JobOutcome::Done(tx)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + use crate::blockstore::{BlockId, BlockStore}; + use crate::test_support::test_state_with; + use futures::StreamExt as _; + use twigpine_core::cid::sha256_hex; + + async fn put_block(store: &Arc, bytes: &[u8]) -> String { + let sha = sha256_hex(bytes); + let id = BlockId::parse(&sha).expect("id"); + let body = futures::stream::iter(vec![Ok::<_, std::io::Error>(bytes::Bytes::from( + bytes.to_vec(), + ))]) + .boxed(); + store.put_verified(&id, body, u64::MAX).await.expect("put"); + sha + } + + fn git(dir: &std::path::Path, args: &[&str]) -> String { + 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() + } + + /// A release commit carrying the manifest and its detached signature. + fn make_release_git(dir: &std::path::Path, manifest: &[u8], sig: &str) -> String { + git(dir, &["init", "-q", "-b", "main"]); + std::fs::create_dir_all(dir.join(".twigpine")).unwrap(); + std::fs::write(dir.join(".twigpine/model-release.json"), manifest).unwrap(); + std::fs::write(dir.join(".twigpine/model-release.sig"), sig).unwrap(); + git(dir, &["add", "-A"]); + git( + dir, + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "rel", + ], + ); + git(dir, &["rev-parse", "HEAD"]) + } + + async fn seed_repo(db: &crate::db::Db, id: &str, public: bool, disk: &std::path::Path) { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1,'m','did:owner',$2,'main','t','t',$3)", + ) + .bind(id) + .bind(public) + .bind(disk.to_str().unwrap()) + .execute(db.pool()) + .await + .expect("seed repo"); + } + + async fn seed_block_row(db: &crate::db::Db, sha: &str, size: u64) { + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) + VALUES ($1,$2,'t') ON CONFLICT DO NOTHING", + ) + .bind(sha) + .bind(size as i64) + .execute(db.pool()) + .await + .expect("seed block row"); + } + + /// A published release row, then links for each block sha. + async fn seed_release( + db: &crate::db::Db, + repo_id: &str, + commit: &str, + state: &str, + manifest_sha: &str, + rec_sha: Option<&str>, + block_shas: &[String], + ) -> i64 { + let id: i64 = sqlx::query_scalar( + "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, created_at, published_at) + VALUES ($1,$2,'main','did:owner',$3,$4,$5,'sig','input','signing',\ + decode('00','hex'),'t','t') + RETURNING id", + ) + .bind(repo_id) + .bind(commit) + .bind(state) + .bind(manifest_sha) + .bind(rec_sha) + .fetch_one(db.pool()) + .await + .expect("seed release"); + for sha in block_shas { + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) + VALUES ($1,$2)", + ) + .bind(id) + .bind(sha) + .execute(db.pool()) + .await + .expect("link block"); + } + id + } + + /// Every pending job's (kind, object_key), for assertions. + async fn pending_kinds(db: &crate::db::Db, release_id: i64) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT kind, object_key FROM model_durability_jobs + WHERE release_id = $1 AND state = 'pending' ORDER BY id", + ) + .bind(release_id) + .fetch_all(db.pool()) + .await + .expect("pending kinds") + } + + async fn job_states(db: &crate::db::Db, release_id: i64) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT kind, state FROM model_durability_jobs + WHERE release_id = $1 ORDER BY id", + ) + .bind(release_id) + .fetch_all(db.pool()) + .await + .expect("job states") + } + + /// Enqueue builds the whole job set for a published release and a + /// repeat call inserts nothing. + #[sqlx::test] + async fn enqueue_full_set_idempotent(pool: sqlx::PgPool) { + let state = test_state_with(pool.clone(), |_| {}).await; + let dir = tempfile::tempdir().unwrap(); + seed_repo(&state.db, "r1", true, dir.path()).await; + let b1 = sha256_hex(b"one"); + let b2 = sha256_hex(b"two"); + let rec = sha256_hex(b"rec"); + for (sha, n) in [(&b1, 3u64), (&b2, 3), (&rec, 3)] { + seed_block_row(&state.db, sha, n).await; + } + let id = seed_release( + &state.db, + "r1", + &"a".repeat(40), + "published", + &"b".repeat(64), + Some(&rec), + &[b1.clone(), b2.clone()], + ) + .await; + + enqueue_for_release(&state, id).await.unwrap(); + enqueue_for_release(&state, id).await.unwrap(); + let jobs = pending_kinds(&state.db, id).await; + let kinds: Vec<&str> = jobs.iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!( + kinds.len(), + 6, + "two blocks + manifest + rec + map + anchor: {kinds:?}" + ); + assert_eq!(kinds.iter().filter(|k| **k == KIND_BLOCK).count(), 2); + for want in [ + KIND_MANIFEST, + KIND_RECONSTRUCTION, + KIND_BLOCK_MAP, + KIND_ANCHOR, + ] { + assert!(kinds.contains(&want), "missing {want}: {kinds:?}"); + } + + // A non-published release enqueues nothing. + let id2 = seed_release( + &state.db, + "r1", + &"c".repeat(40), + "verifying", + &"d".repeat(64), + None, + &[], + ) + .await; + enqueue_for_release(&state, id2).await.unwrap(); + assert!(pending_kinds(&state.db, id2).await.is_empty()); + } + + /// The backfill enqueues published releases with no job rows and skips + /// a verifying row entirely. + #[sqlx::test] + async fn backfill_enqueues_published_missing_only(pool: sqlx::PgPool) { + let state = test_state_with(pool.clone(), |_| {}).await; + let dir = tempfile::tempdir().unwrap(); + seed_repo(&state.db, "r1", true, dir.path()).await; + let published = seed_release( + &state.db, + "r1", + &"a".repeat(40), + "published", + &"b".repeat(64), + None, + &[], + ) + .await; + let verifying = seed_release( + &state.db, + "r1", + &"c".repeat(40), + "verifying", + &"d".repeat(64), + None, + &[], + ) + .await; + backfill_missing(&state).await.unwrap(); + assert_eq!(pending_kinds(&state.db, published).await.len(), 3); + assert!(pending_kinds(&state.db, verifying).await.is_empty()); + } + + /// A full drain on a mockito Kubo + Irys pins the block, the manifest, + /// the block map, and posts the anchor only once every pin is done. + #[sqlx::test] + async fn drain_pins_maps_and_anchors(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let mut irys = mockito::Server::new_async().await; + + let dir = tempfile::tempdir().unwrap(); + let block_dir = tempfile::tempdir().unwrap(); + let manifest = br#"{"schema":"gitlawb/model-release/v1","files":[]}"#.to_vec(); + let commit = make_release_git(dir.path(), &manifest, "sig"); + let manifest_sha = sha256_hex(&manifest); + let block_bytes = b"BLOCKBYTES-durability".to_vec(); + + let mut state = test_state_with(pool.clone(), |cfg| { + cfg.ipfs_api = kubo.url(); + cfg.irys_url = irys.url(); + }) + .await; + let store: Arc = Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir.path().to_path_buf()).unwrap(), + ); + state.block_store = Some(store.clone()); + + let block_sha = put_block(&store, &block_bytes).await; + seed_block_row(&state.db, &block_sha, block_bytes.len() as u64).await; + seed_repo(&state.db, "r1", true, dir.path()).await; + let release_id = seed_release( + &state.db, + "r1", + &commit, + "published", + &manifest_sha, + None, + std::slice::from_ref(&block_sha), + ) + .await; + + // Kubo answers each add with the CID the pin code computes locally, + // matched on a marker byte sequence inside the multipart body. + for (marker, data) in [ + ("BLOCKBYTES", &block_bytes), + ("model-release/v1", &manifest), + ] { + kubo.mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex(marker.to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(data) + )) + .create_async() + .await; + } + // The map body is generated inside execute_job; its CID is + // computed the same way, from the serialized payload. + let map_cid_holder = kubo + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex("model-block-map".to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(|req| { + // Answer the CID of whatever bytes were posted: mirrors + // Kubo exactly, so the recorded cid is the confirmed one. + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + // multipart: strip to the raw object bytes between the + // boundary preamble and the trailing boundary. + let start = body + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4) + .unwrap_or(0); + let end = body + .windows(2) + .rposition(|w| w == b"\r\n") + .unwrap_or(body.len()); + let object = &body[start..end]; + format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(object) + ) + .into_bytes() + }) + .create_async() + .await; + let irys_mock = irys + .mock("POST", "/upload") + .match_header( + "x-irys-tags", + mockito::Matcher::AllOf(vec![ + mockito::Matcher::Regex("Schema:gitlawb/model-release-anchor/v1".to_string()), + mockito::Matcher::Regex(format!("Release-Commit:{commit}")), + ]), + ) + .match_body(mockito::Matcher::PartialJsonString(format!( + r#"{{"release_commit":"{commit}"}}"# + ))) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"TXDUR1"}"#) + .create_async() + .await; + + enqueue_for_release(&state, release_id).await.unwrap(); + // Gated jobs may defer inside one pass; a few passes is the + // steady-state the worker converges to. + for _ in 0..4 { + durability_pass(&state).await.unwrap(); + } + + let states = job_states(&state.db, release_id).await; + assert_eq!(states.len(), 4, "{states:?}"); + for (kind, st) in &states { + assert_eq!(st, "done", "{kind} not done: {states:?}"); + } + let tx = state + .db + .model_durability_done_cid(release_id, KIND_ANCHOR) + .await + .unwrap(); + assert_eq!(tx.as_deref(), Some("TXDUR1")); + // The block pin recorded the provider CID beside the sha256 key. + let block_cid = state + .db + .model_durability_done_cid(release_id, KIND_BLOCK) + .await + .unwrap() + .expect("block cid"); + assert_eq!( + block_cid, + twigpine_core::cid::Cid::from_git_object_bytes(&block_bytes).to_string() + ); + irys_mock.assert_async().await; + map_cid_holder.assert_async().await; + } + + /// While a pin job is still pending, the map and anchor defer rather + /// than posting incomplete addresses; once the object appears the next + /// pass completes the chain. + #[sqlx::test] + async fn anchor_defers_until_pins_complete(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let mut irys = mockito::Server::new_async().await; + + let dir = tempfile::tempdir().unwrap(); + let block_dir = tempfile::tempdir().unwrap(); + let manifest = br#"{"schema":"gitlawb/model-release/v1","files":[]}"#.to_vec(); + let commit = make_release_git(dir.path(), &manifest, "sig"); + let block_bytes = b"BLOCKBYTES-later".to_vec(); + let block_sha = sha256_hex(&block_bytes); + + let mut state = test_state_with(pool.clone(), |cfg| { + cfg.ipfs_api = kubo.url(); + cfg.irys_url = irys.url(); + }) + .await; + let store: Arc = Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir.path().to_path_buf()).unwrap(), + ); + state.block_store = Some(store.clone()); + + seed_block_row(&state.db, &block_sha, block_bytes.len() as u64).await; + seed_repo(&state.db, "r1", true, dir.path()).await; + let release_id = seed_release( + &state.db, + "r1", + &commit, + "published", + &sha256_hex(&manifest), + None, + std::slice::from_ref(&block_sha), + ) + .await; + + for (marker, data) in [ + ("BLOCKBYTES", &block_bytes), + ("model-release/v1", &manifest), + ] { + kubo.mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex(marker.to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(data) + )) + .create_async() + .await; + } + kubo.mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex("model-block-map".to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(|req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let start = body + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4) + .unwrap_or(0); + let end = body + .windows(2) + .rposition(|w| w == b"\r\n") + .unwrap_or(body.len()); + let object = &body[start..end]; + format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(object) + ) + .into_bytes() + }) + .create_async() + .await; + let irys_mock = irys + .mock("POST", "/upload") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"TXLATE"}"#) + .expect(0) + .create_async() + .await; + + enqueue_for_release(&state, release_id).await.unwrap(); + // The block is NOT in the store: its pin errors, and the gated + // jobs must not run ahead of it. + durability_pass(&state).await.unwrap(); + let states = job_states(&state.db, release_id).await; + assert_eq!( + states.iter().filter(|(_, s)| s == "pending").count(), + 3, + "block pin retries while map and anchor wait: {states:?}" + ); + + irys_mock.assert_async().await; + + // Now the object exists; the chain completes end to end. + put_block(&store, &block_bytes).await; + let irys_done = irys + .mock("POST", "/upload") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"TXLATE"}"#) + .create_async() + .await; + for _ in 0..4 { + durability_pass(&state).await.unwrap(); + } + let states = job_states(&state.db, release_id).await; + for (kind, st) in &states { + assert_eq!(st, "done", "{kind} not done: {states:?}"); + } + irys_done.assert_async().await; + } + + /// A repo that stops being fully public fails every pending job for + /// the release in one pass, and nothing reaches Irys. + #[sqlx::test] + async fn private_transition_fails_all_pending(pool: sqlx::PgPool) { + let mut irys = mockito::Server::new_async().await; + let dir = tempfile::tempdir().unwrap(); + let commit = make_release_git(dir.path(), b"{}", "sig"); + + let mut state = test_state_with(pool.clone(), |cfg| { + cfg.irys_url = irys.url(); + }) + .await; + let block_dir = tempfile::tempdir().unwrap(); + state.block_store = Some(Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir.path().to_path_buf()).unwrap(), + )); + + seed_repo(&state.db, "r1", true, dir.path()).await; + let release_id = seed_release( + &state.db, + "r1", + &commit, + "published", + &"b".repeat(64), + None, + &[], + ) + .await; + enqueue_for_release(&state, release_id).await.unwrap(); + assert_eq!(pending_kinds(&state.db, release_id).await.len(), 3); + + let irys_mock = irys + .mock("POST", "/upload") + .with_status(200) + .expect(0) + .create_async() + .await; + + sqlx::query("UPDATE repos SET is_public = false WHERE id = 'r1'") + .execute(state.db.pool()) + .await + .unwrap(); + durability_pass(&state).await.unwrap(); + let states = job_states(&state.db, release_id).await; + for (kind, st) in &states { + assert_eq!(st, "failed", "{kind} should be failed: {states:?}"); + } + irys_mock.assert_async().await; + } +} diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index f4e3e036..4486b145 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -8,6 +8,8 @@ //! share. pub mod claim; +pub mod durability; +pub mod serve; pub mod sweep; pub mod verify; diff --git a/crates/twigpine-node/src/models/serve.rs b/crates/twigpine-node/src/models/serve.rs new file mode 100644 index 00000000..99baaddc --- /dev/null +++ b/crates/twigpine-node/src/models/serve.rs @@ -0,0 +1,302 @@ +//! Byte-exact, resumable downloads for the HF resolve route (KTD9). +//! +//! The pure half is `resolve`: turn a `Range`/`If-Range` header pair into a +//! `RangeSpec` over a file of `total` bytes. The streaming half is +//! `slices_stream`, which turns `map_file_range`'s block slices into one +//! ordered byte stream over the block store: a chunked file of any size +//! never buffers past one store chunk, so node memory is bounded by the +//! block size rather than the file size. + +use std::io; +use std::sync::Arc; + +use bytes::Bytes; +use futures::stream::BoxStream; +use futures::StreamExt; +use twigpine_core::model::reconstruction::BlockSlice; + +use crate::blockstore::{BlockId, BlockStore, BlockStoreError}; + +/// What a `Range`/`If-Range` pair resolves to over `total` bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RangeSpec { + /// No satisfiable single range: send the whole body with a 200. + Full, + /// Send `start..=end_incl` with a 206. + Single { start: u64, end_incl: u64 }, + /// No range can be satisfied: 416 with `Content-Range: bytes */total`. + Unsatisfiable, +} + +/// Resolve `Range` and `If-Range` header values against a file of `total` +/// bytes whose validator is `etag` (the quoted form is compared +/// quote-insensitively). +/// +/// Only a single satisfiable range is honored: a malformed `Range`, a +/// multi-range spec, and an `If-Range` that does not match the current +/// validator all fall back to a full 200 (KTD9: a downloader resumes with +/// one contiguous span, and the RFC lets a server ignore a range it cannot +/// honor rather than answering multipart). A `start` past the end is the +/// one hard answer: 416. +pub fn resolve(range: Option<&str>, if_range: Option<&str>, etag: &str, total: u64) -> RangeSpec { + let Some(raw) = range else { + return RangeSpec::Full; + }; + if let Some(cond) = if_range { + let cond = cond.trim().trim_matches('"'); + if cond != etag.trim().trim_matches('"') { + // A stale validator makes the range meaningless: full body. + return RangeSpec::Full; + } + } + let Some(spec) = raw.trim().strip_prefix("bytes=") else { + return RangeSpec::Full; + }; + let spec = spec.trim(); + if spec.is_empty() || spec.contains(',') { + // Multi-range is deliberately not served: a full 200 is a valid + // answer and keeps the response shape a downloader can consume. + return RangeSpec::Full; + } + let Some((first, last)) = spec.split_once('-') else { + return RangeSpec::Full; + }; + let first = first.trim(); + let last = last.trim(); + if first.is_empty() { + // Suffix range `bytes=-N`: the last N bytes. + let Ok(n) = last.parse::() else { + return RangeSpec::Full; + }; + if n == 0 { + return RangeSpec::Full; + } + let len = n.min(total); + if len == 0 { + return RangeSpec::Unsatisfiable; + } + return RangeSpec::Single { + start: total - len, + end_incl: total - 1, + }; + } + let Ok(start) = first.parse::() else { + return RangeSpec::Full; + }; + if start >= total { + return RangeSpec::Unsatisfiable; + } + let end_incl = if last.is_empty() { + total - 1 + } else { + match last.parse::() { + Ok(e) => e.min(total - 1), + Err(_) => return RangeSpec::Full, + } + }; + if start > end_incl { + // An empty span is an invalid range, not an unsatisfiable one. + return RangeSpec::Full; + } + RangeSpec::Single { start, end_incl } +} + +/// Chain the block slices into one ordered byte stream. Each slice is a +/// `get_range` against the block store: the store's own chunked stream is +/// flattened, so a range spanning several blocks still yields contiguous +/// file bytes and peak memory tracks the store's read chunking, never the +/// file's length. +pub fn slices_stream( + store: Arc, + slices: Vec, +) -> BoxStream<'static, io::Result> { + futures::stream::iter(slices) + .then(move |slice| { + let store = store.clone(); + async move { + let id = + BlockId::parse(&slice.block).map_err(|e| io::Error::other(e.to_string()))?; + let end = slice + .offset + .checked_add(slice.len) + .ok_or_else(|| io::Error::other("slice range overflow"))?; + store + .get_range(&id, slice.offset, end) + .await + .map_err(store_to_io) + } + }) + .flat_map(|res| -> BoxStream<'static, io::Result> { + match res { + Ok(s) => s, + Err(e) => futures::stream::once(std::future::ready(Err(e))).boxed(), + } + }) + .boxed() +} + +fn store_to_io(e: BlockStoreError) -> io::Error { + io::Error::other(e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ETAG: &str = "\"abc123\""; + + #[test] + fn no_range_is_full() { + assert_eq!(resolve(None, None, ETAG, 100), RangeSpec::Full); + } + + #[test] + fn open_ended_range() { + assert_eq!( + resolve(Some("bytes=1000-"), None, ETAG, 2000), + RangeSpec::Single { + start: 1000, + end_incl: 1999 + } + ); + } + + #[test] + fn closed_range_and_clamped_end() { + assert_eq!( + resolve(Some("bytes=0-99"), None, ETAG, 2000), + RangeSpec::Single { + start: 0, + end_incl: 99 + } + ); + // An end past the last byte clamps, not errors. + assert_eq!( + resolve(Some("bytes=1990-5000"), None, ETAG, 2000), + RangeSpec::Single { + start: 1990, + end_incl: 1999 + } + ); + } + + #[test] + fn suffix_range() { + assert_eq!( + resolve(Some("bytes=-50"), None, ETAG, 2000), + RangeSpec::Single { + start: 1950, + end_incl: 1999 + } + ); + // A suffix longer than the file clamps to the whole file. + assert_eq!( + resolve(Some("bytes=-5000"), None, ETAG, 100), + RangeSpec::Single { + start: 0, + end_incl: 99 + } + ); + } + + #[test] + fn out_of_bounds_is_unsatisfiable() { + assert_eq!( + resolve(Some("bytes=2000-"), None, ETAG, 2000), + RangeSpec::Unsatisfiable + ); + assert_eq!( + resolve(Some("bytes=-1"), None, ETAG, 0), + RangeSpec::Unsatisfiable + ); + } + + #[test] + fn malformed_and_multi_fall_back_to_full() { + for bad in [ + "items=0-9", + "bytes=", + "bytes=a-b", + "bytes=10-5", + "bytes=0-10,20-30", + "bytes=-0", + "bytes", + ] { + assert_eq!( + resolve(Some(bad), None, ETAG, 100), + RangeSpec::Full, + "{bad} must fall back to a full 200" + ); + } + } + + #[test] + fn if_range_gates_the_range() { + // Matching validator (quoted, like we emit): the range applies. + assert_eq!( + resolve(Some("bytes=0-9"), Some("\"abc123\""), ETAG, 100), + RangeSpec::Single { + start: 0, + end_incl: 9 + } + ); + // Bare (unquoted) comparison still matches. + assert_eq!( + resolve(Some("bytes=0-9"), Some("abc123"), ETAG, 100), + RangeSpec::Single { + start: 0, + end_incl: 9 + } + ); + // A stale etag makes the range meaningless: full body. + assert_eq!( + resolve(Some("bytes=0-9"), Some("\"old\""), ETAG, 100), + RangeSpec::Full + ); + } + + /// Two slices on two different blocks chain into one contiguous byte + /// stream; a missing block surfaces as a stream error rather than a + /// short or fabricated body. + #[tokio::test] + async fn slices_stream_chains_blocks_and_fails_on_missing() { + let dir = tempfile::tempdir().expect("tempdir"); + let store: Arc = Arc::new( + crate::blockstore::fs::FsBlockStore::new(dir.path().to_path_buf()).expect("fs store"), + ); + let mut ids = Vec::new(); + for bytes in [b"hello-".as_slice(), b"world!".as_slice()] { + let id = BlockId::parse(&twigpine_core::cid::sha256_hex(bytes)).expect("id"); + let body = futures::stream::iter(vec![Ok(Bytes::from(bytes.to_vec()))]).boxed(); + store.put_verified(&id, body, u64::MAX).await.expect("put"); + ids.push(id.as_str().to_string()); + } + + let slices = vec![ + BlockSlice { + block: ids[0].clone(), + offset: 0, + len: 6, + }, + BlockSlice { + block: ids[1].clone(), + offset: 1, + len: 5, + }, + ]; + let mut out = Vec::new(); + let mut s = slices_stream(store.clone(), slices); + while let Some(c) = s.next().await { + out.extend_from_slice(&c.expect("slice bytes")); + } + assert_eq!(out, b"hello-orld!"); + + let missing = vec![BlockSlice { + block: "0".repeat(64), + offset: 0, + len: 1, + }]; + let mut s = slices_stream(store, missing); + assert!(s.next().await.expect("an item").is_err()); + } +} diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index df4300c5..91f7bcf2 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -323,7 +323,12 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App "git update-ref", ) .await; + return Ok(()); } + // Published: enqueue the pin + anchor job set. Idempotent, so a + // verify retry after a crash re-runs this harmlessly, and the worker + // drains it under the durability budget. + crate::models::durability::enqueue_for_release(state, release_id).await?; Ok(()) } diff --git a/crates/twigpine-node/src/pinata.rs b/crates/twigpine-node/src/pinata.rs index 6090a0e7..3ecd895d 100644 --- a/crates/twigpine-node/src/pinata.rs +++ b/crates/twigpine-node/src/pinata.rs @@ -28,15 +28,46 @@ pub async fn pin_object( if jwt.is_empty() { return Ok(String::new()); } + upload(client, upload_url, jwt, &format!("git-{sha}"), data).await +} + +/// Pin one model content object's bytes on Pinata (v3 API). +/// +/// Same upload path as [`pin_object`] with a `model-` pin name so the +/// warm-tier copy is distinguishable from git objects in the Pinata +/// console. Returns the provider CID on success, `Ok("")` when +/// `jwt` is empty (Pinata not configured). The CID is metadata recorded +/// alongside the sha256 resolver key, never in place of it. +pub async fn pin_model_object( + client: &reqwest::Client, + upload_url: &str, + jwt: &str, + sha: &str, + data: &[u8], +) -> Result { + if jwt.is_empty() { + return Ok(String::new()); + } + upload(client, upload_url, jwt, &format!("model-{sha}"), data).await +} - let filename = format!("git-{}.bin", &sha[..sha.len().min(8)]); +/// The shared v3 multipart upload. `name` is the pin name Pinata records; +/// the returned `data.cid` is the provider CID. +async fn upload( + client: &reqwest::Client, + upload_url: &str, + jwt: &str, + name: &str, + data: &[u8], +) -> Result { + let filename = format!("{}.bin", &name[..name.len().min(16)]); let part = reqwest::multipart::Part::bytes(data.to_vec()) .file_name(filename) .mime_str("application/octet-stream")?; let form = reqwest::multipart::Form::new() .part("file", part) .text("network", "public") - .text("name", format!("git-{sha}")); + .text("name", name.to_string()); let resp = client .post(upload_url) @@ -63,7 +94,7 @@ pub async fn pin_object( .ok_or_else(|| anyhow::anyhow!("no 'data.cid' in Pinata response: {json}"))? .to_string(); - tracing::debug!(sha = %sha, %cid, "pinned git object to Pinata"); + tracing::debug!(name = %name, %cid, "pinned object to Pinata"); Ok(cid) } diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index e8f66d33..1290c39b 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -14,7 +14,7 @@ use tower_http::trace::{DefaultOnFailure, DefaultOnResponse, TraceLayer}; use tracing::Level; use crate::api::{ - agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, models, peers, + agents, arweave, bounties, certs, changelog, events, hf, ipfs, issues, labels, models, peers, profiles, protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, webhooks, }; @@ -824,7 +824,38 @@ pub fn build_router(state: AppState) -> Router { auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), auth::optional_signature, )); - signed.merge(claims).merge(blocks).merge(reads) + // HF-compatible read surface (KTD8/KTD9): anonymous reads of a fully + // public repo, optional signature for owner reads, own per-IP brake + // so a prober flood cannot burn the publicity lookups of every other + // read surface. HF bearer tokens carry no signature headers and read + // as anonymous, never a 401. + let hf_limiter = rate_limit::IpRateLimiter { + limiter: state.hf_read_rate_limiter.clone(), + trust: state.push_limiter_trust, + }; + let hf = Router::new() + .route("/hf/api/models/{owner}/{repo}", get(hf::hf_model_info)) + .route( + "/hf/api/models/{owner}/{repo}/revision/{rev}", + get(hf::hf_revision_info), + ) + .route("/hf/api/models/{owner}/{repo}/tree/{rev}", get(hf::hf_tree)) + .route( + "/hf/api/models/{owner}/{repo}/tree/{rev}/{*path}", + get(hf::hf_tree_path), + ) + .route("/hf/api/models/{owner}/{repo}/refs", get(hf::hf_refs)) + .route( + "/hf/{owner}/{repo}/resolve/{rev}/{*path}", + get(hf::hf_resolve), + ) + .layer(middleware::from_fn_with_state( + auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), + auth::optional_signature, + )) + .layer(middleware::from_fn(rate_limit::rate_limit_by_ip)) + .layer(axum::Extension(hf_limiter)); + signed.merge(claims).merge(blocks).merge(reads).merge(hf) } else { Router::new() }; diff --git a/crates/twigpine-node/src/state.rs b/crates/twigpine-node/src/state.rs index 6925d7f3..d8c777ca 100644 --- a/crates/twigpine-node/src/state.rs +++ b/crates/twigpine-node/src/state.rs @@ -378,6 +378,14 @@ pub struct AppState { /// The same per-IP hourly budget applies to GraphQL `tasks` / `task` /// queries and WebSocket task queries via `TaskReadBrake`. pub task_read_rate_limiter: RateLimiter, + /// Per-client-IP rate limiter for the HF-compatible model read routes. + /// `/hf/api/models/...` and `/hf/.../resolve/...` are anonymously + /// reachable and run the publicity gate plus release lookups before any + /// answer, so an unauthenticated prober costs the node real work per + /// request whether or not anything is served. Keyed on the resolved + /// client IP via `push_limiter_trust`; layered on the HF route group + /// via `rate_limit_by_ip`. + pub hf_read_rate_limiter: RateLimiter, /// The `git` executable the served-git withheld-blob walk spawns. Production is /// `"git"` (resolved via PATH); injectable so a fake `git` can drive the walk's /// process-group teardown in handler tests without mutating the process-global @@ -386,6 +394,14 @@ pub struct AppState { /// Content-addressed model block store. `None` unless model hosting is /// enabled, so every read site must handle the flag-off shape. pub block_store: Option>, + /// Bounds concurrent model `resolve` body streams. A chunked download + /// holds store connections for the life of the response, so a slow + /// reader could otherwise pin every store slot indefinitely; a pool of + /// its own (not `git_read_semaphore`) because model downloads can run + /// for minutes on multi-GiB files and must not starve git reads. + /// Acquirers DEFER (wait) when the pool is full; a download shed at + /// admission would read as a spurious 503 to a resumable fetcher. + pub model_download_semaphore: Arc, } impl AppState { @@ -434,6 +450,7 @@ impl AppState { self.peer_write_rate_limiter.cleanup().await; self.task_read_rate_limiter.cleanup().await; self.federated_rate_limiter.cleanup().await; + self.hf_read_rate_limiter.cleanup().await; } /// Legacy-probe budget wired from the `TWIGPINE_IPFS_MAX_LEGACY_PROBES` operator diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 9032eca0..b7e7d51d 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -236,8 +236,10 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys( 16, ), + hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store, + model_download_semaphore: Arc::new(tokio::sync::Semaphore::new(64)), } } diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 702f2155..680481f9 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -155,8 +155,10 @@ fn build_state(db: Arc, pool: PgPool) -> AppState { 16, ), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), + hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store: None, + model_download_semaphore: Arc::new(tokio::sync::Semaphore::new(64)), } } diff --git a/crates/twigpine-node/tests/deny_harness.rs b/crates/twigpine-node/tests/deny_harness.rs index 76acf4cb..33233bf7 100644 --- a/crates/twigpine-node/tests/deny_harness.rs +++ b/crates/twigpine-node/tests/deny_harness.rs @@ -1447,6 +1447,28 @@ mod completeness { "get_model_reconstruction", NotDrivenReason::ExternalDependencyUnavailable, ), + // The HF-compatible read surface (U9/U10): every handler read-gates + // the repo and fails closed on publicity before any release lookup, + // so the hostile anon/stranger 404 on the private repo is exactly + // what a caller sees. Their 2xx twins need a published release — a + // signed manifest commit in the repo's real git dir plus, for + // hf_resolve, real block-store content — substrate the fixture + // cannot seed through the public API. + ( + "hf_model_info", + NotDrivenReason::ExternalDependencyUnavailable, + ), + ( + "hf_revision_info", + NotDrivenReason::ExternalDependencyUnavailable, + ), + ("hf_tree", NotDrivenReason::ExternalDependencyUnavailable), + ( + "hf_tree_path", + NotDrivenReason::ExternalDependencyUnavailable, + ), + ("hf_refs", NotDrivenReason::ExternalDependencyUnavailable), + ("hf_resolve", NotDrivenReason::ExternalDependencyUnavailable), ]; /// Every `.route("", ()…)` mount in `src`, as diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs new file mode 100644 index 00000000..d30a55ce --- /dev/null +++ b/crates/twigpine-node/tests/hf_api.rs @@ -0,0 +1,917 @@ +//! HTTP-level coverage for the HF-compatible read surface (U9/U10): model +//! info, revision, tree, refs, and the resumable resolve route. Each test +//! seeds a real on-disk release commit (signed manifest plus the git-stored +//! files) and, for chunked files, real blocks in the store through the +//! bearer PUT, so the routes read exactly what a published release would +//! serve. Requires `--features test-harness`. + +#[allow(dead_code)] +mod support; + +use serde_json::Value; +use support::bounded_client; +use support::signing::signed_request; + +use twigpine_core::cid::sha256_hex; +use twigpine_core::identity::Keypair; +use twigpine_core::model::manifest::{ + FileFormat, Manifest, ManifestFile, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{ + BlockEntry, ChunkMeta, FileEntry, Reconstruction, Term, +}; +use twigpine_core::model::RECONSTRUCTION_SCHEMA_V1; +use twigpine_node::test_harness::spawn_node; + +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), + ) +} + +fn run_git(dir: &std::path::Path, args: &[&str]) -> String { + 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() +} + +/// Build a git repo on disk containing one commit with the signed release +/// manifest, its signature, and the git-stored manifest files, returning +/// the release commit sha. +fn make_release_repo( + dir: &std::path::Path, + manifest: &[u8], + sig: &str, + git_files: &[(&str, &[u8])], +) -> String { + run_git(dir, &["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"); + for (path, bytes) in git_files { + let p = dir.join(path); + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent).expect("mkdir file parent"); + } + std::fs::write(&p, bytes).expect("write file"); + } + run_git(dir, &["add", "-A"]); + run_git( + dir, + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "model release 1", + ], + ); + run_git(dir, &["rev-parse", "HEAD"]) +} + +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"); +} + +/// Insert a published release row with the real manifest sha (the seeded +/// row `seed_model_release` pads the commit, which `load_manifest` would +/// correctly refuse). `branch` records which git branch the release came +/// from; `rec_sha` links the reconstruction object. +async fn seed_published_release( + pool: &sqlx::PgPool, + repo_id: &str, + commit: &str, + branch: &str, + publisher_did: &str, + manifest_sha: &str, + rec_sha: Option<&str>, + block_shas: &[String], +) -> i64 { + let now = chrono::Utc::now().to_rfc3339(); + let id: i64 = sqlx::query_scalar( + "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, created_at, published_at) + VALUES ($1,$2,$3,$4,'published',$5,$6,'sig','input','signing',\ + decode('00','hex'),$7,$7) + RETURNING id", + ) + .bind(repo_id) + .bind(commit) + .bind(branch) + .bind(publisher_did) + .bind(manifest_sha) + .bind(rec_sha) + .bind(&now) + .fetch_one(pool) + .await + .expect("seed release"); + for sha in block_shas { + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) + VALUES ($1,$2) ON CONFLICT DO NOTHING", + ) + .bind(id) + .bind(sha) + .execute(pool) + .await + .expect("link release block"); + } + id +} + +/// Everything a test needs to serve one published release. +struct Fixture { + commit: String, +} + +/// Build a repo dir + manifest + release row. `git_files` are committed +/// into the release; `chunked_files` is `(path, bytes)` split into +/// single-chunk blocks of `chunk_len` bytes, stored in the block store via +/// the bearer PUT (seeded session) and mapped by a real reconstruction +/// object. +async fn seed_release( + node: &twigpine_node::test_harness::TestNode, + pool: &sqlx::PgPool, + owner_did: &str, + signing: &ed25519_dalek::SigningKey, + repo_id: &str, + repo_name: &str, + git_files: &[(&str, &[u8])], + chunked_files: &[(&str, &[u8], usize)], + branch: &str, +) -> Fixture { + let client = bounded_client(); + // Upload the chunked blocks first so the reconstruction object can + // name them; the rec object itself is stored as a block too. + let session = "s".repeat(64); + if !chunked_files.is_empty() { + node.seed_model_session(repo_id, &session, owner_did).await; + } + let mut blocks: Vec = Vec::new(); + let mut rec_files: Vec = Vec::new(); + let mut block_shas: Vec = Vec::new(); + let mut files: Vec<(String, Vec, StorageKind, FileFormat)> = Vec::new(); + for (path, data, chunk_len) in chunked_files { + // One chunk per block keeps the fixture simple while still + // exercising multi-block ranges when the file spans blocks. + let mut terms = Vec::new(); + for chunk in data.chunks(*chunk_len) { + let sha = sha256_hex(chunk); + let resp = client + .put(format!( + "{}/api/v1/repos/{}/{}/models/blocks/{}", + node.base_url, owner_did, repo_name, sha + )) + .header("x-twigpine-model-session", &session) + .body(chunk.to_vec()) + .send() + .await + .expect("block put"); + assert_eq!(resp.status().as_u16(), 200, "block put {path}"); + blocks.push(BlockEntry { + sha256: sha.clone(), + size: chunk.len() as u64, + chunks: vec![ChunkMeta { + sha256: sha.clone(), + len: chunk.len() as u64, + }], + }); + block_shas.push(sha.clone()); + terms.push(Term { + block: sha, + chunk_start: 0, + chunk_end: 1, + length: chunk.len() as u64, + }); + } + rec_files.push(FileEntry { + path: path.to_string(), + size: data.len() as u64, + sha256: sha256_hex(data), + terms, + }); + files.push(( + path.to_string(), + data.to_vec(), + StorageKind::Chunked, + FileFormat::Safetensors, + )); + } + let rec_bytes = Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.to_string(), + files: rec_files, + blocks, + } + .to_bytes() + .expect("rec bytes"); + let rec_sha = if chunked_files.is_empty() { + None + } else { + let sha = sha256_hex(&rec_bytes); + let resp = client + .put(format!( + "{}/api/v1/repos/{}/{}/models/blocks/{}", + node.base_url, owner_did, repo_name, sha + )) + .header("x-twigpine-model-session", &session) + .body(rec_bytes.clone()) + .send() + .await + .expect("rec put"); + assert_eq!(resp.status().as_u16(), 200, "rec object put"); + block_shas.push(sha.clone()); + Some(sha) + }; + + for (path, data) in git_files { + files.push(( + path.to_string(), + data.to_vec(), + StorageKind::Git, + FileFormat::Text, + )); + } + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/{repo_name}"), + publisher_did: owner_did.to_string(), + license: "mit".to_string(), + parent: None, + files: files + .iter() + .map(|(path, data, storage, format)| ManifestFile { + path: path.clone(), + size: data.len() as u64, + sha256: sha256_hex(data), + format: *format, + storage: *storage, + }) + .collect(), + reconstruction: rec_sha.as_ref().map(|sha| ReconstructionRef { + sha256: sha.clone(), + size: rec_bytes.len() as u64, + }), + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let manifest_sha = sha256_hex(&manifest_bytes); + let sig = twigpine_core::model::manifest::sign(signing, &manifest_bytes); + + let dir = tempfile::tempdir().expect("tempdir"); + let git_files: Vec<(&str, &[u8])> = files + .iter() + .filter(|(_, _, s, _)| *s == StorageKind::Git) + .map(|(p, d, _, _)| (p.as_str(), d.as_slice())) + .collect(); + let commit = make_release_repo(dir.path(), &manifest_bytes, &sig, &git_files); + set_disk_path(pool, repo_id, dir.path()).await; + // Keep the tempdir alive past this function: the git dir must outlive + // the test's HTTP calls. + let _dir_path = dir.keep(); + + seed_published_release( + pool, + repo_id, + &commit, + branch, + owner_did, + &manifest_sha, + rec_sha.as_deref(), + &block_shas, + ) + .await; + Fixture { commit } +} + +fn info_path(owner: &str, repo: &str) -> String { + format!("/hf/api/models/{owner}/{repo}") +} + +fn rev_path(owner: &str, repo: &str, rev: &str) -> String { + format!("/hf/api/models/{owner}/{repo}/revision/{rev}") +} + +fn tree_path(owner: &str, repo: &str, rev: &str) -> String { + format!("/hf/api/models/{owner}/{repo}/tree/{rev}") +} + +fn refs_path(owner: &str, repo: &str) -> String { + format!("/hf/api/models/{owner}/{repo}/refs") +} + +fn resolve_path(owner: &str, repo: &str, rev: &str, path: &str) -> String { + format!("/hf/{owner}/{repo}/resolve/{rev}/{path}") +} + +const GIT_FILE: &[u8] = b"config: a small git-stored file"; +const CHUNKED_FILE_CONTENTS: &[u8] = b"0123456789abcdef-weights-bytes-across-two-blocks"; + +/// One git-stored file plus one chunked file split at 16 bytes (three +/// blocks), so cross-block ranges are exercised. +#[sqlx::test] +async fn model_info_revision_tree_and_refs(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(21); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let fx = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[("weights.safetensors", CHUNKED_FILE_CONTENTS, 16)], + "main", + ) + .await; + + // Model info: sha is the release commit, siblings carry every manifest + // file. + let resp = client + .get(format!("{}{}", node.base_url, info_path(&owner_did, "m"))) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("model info json"); + assert_eq!(v["sha"].as_str(), Some(fx.commit.as_str())); + assert!(v["lastModified"].as_str().is_some()); + let sibs: Vec<&str> = v["siblings"] + .as_array() + .expect("siblings") + .iter() + .filter_map(|s| s["rfilename"].as_str()) + .collect(); + assert_eq!(sibs.len(), 2); + assert!(sibs.contains(&"config.json")); + assert!(sibs.contains(&"weights.safetensors")); + + // Revision pinned by commit, and `main` resolving to the same release. + for rev in [fx.commit.as_str(), "main"] { + let resp = client + .get(format!( + "{}{}", + node.base_url, + rev_path(&owner_did, "m", rev) + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200, "rev {rev}"); + let v: Value = resp.json().await.expect("rev json"); + assert_eq!(v["sha"].as_str(), Some(fx.commit.as_str())); + } + + // Unknown commit-shaped revision: 404 + X-Error-Code RevisionNotFound. + let resp = client + .get(format!( + "{}{}", + node.base_url, + rev_path(&owner_did, "m", &"9".repeat(40)) + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 404); + assert_eq!( + resp.headers()["x-error-code"].to_str().unwrap(), + "RevisionNotFound" + ); + + // Tree: chunked file carries an lfs block, oid is the file sha256. + let resp = client + .get(format!( + "{}{}", + node.base_url, + tree_path(&owner_did, "m", "main") + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let entries: Vec = resp.json().await.expect("tree json"); + assert_eq!(entries.len(), 2); + let chunked = entries + .iter() + .find(|e| e["path"].as_str() == Some("weights.safetensors")) + .expect("chunked entry"); + assert_eq!( + chunked["oid"].as_str(), + Some(sha256_hex(CHUNKED_FILE_CONTENTS).as_str()) + ); + assert_eq!( + chunked["lfs"]["size"].as_u64(), + Some(CHUNKED_FILE_CONTENTS.len() as u64) + ); + let git_entry = entries + .iter() + .find(|e| e["path"].as_str() == Some("config.json")) + .expect("git entry"); + assert!(git_entry.get("lfs").is_none()); + + // Refs: `main` names the release commit. + let resp = client + .get(format!("{}{}", node.base_url, refs_path(&owner_did, "m"))) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("refs json"); + assert_eq!(v["branches"][0]["name"].as_str(), Some("main")); + assert_eq!( + v["branches"][0]["targetCommit"].as_str(), + Some(fx.commit.as_str()) + ); + + node.shutdown().await; +} + +/// A public repo with no release is RepoNotFound; a private repo is the +/// same 404 to anon and stranger; a bearer token is ignored (never 401). +#[sqlx::test] +async fn no_release_private_repo_and_bearer_token(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).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, "m", true).await; + + for path in [ + info_path(&owner_did, "m"), + refs_path(&owner_did, "m"), + tree_path(&owner_did, "m", "main"), + ] { + let resp = client + .get(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 404, "{path}"); + assert_eq!( + resp.headers()["x-error-code"].to_str().unwrap(), + "RepoNotFound", + "{path}" + ); + } + + // Bearer token is not a signature header: reads as anonymous, 200 or + // the existence-hiding 404, never 401. + let resp = client + .get(format!("{}{}", node.base_url, info_path(&owner_did, "m"))) + .header("authorization", "Bearer hf_faketoken") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 404, "bearer token is ignored"); + + // Private repo: anon and signed stranger get the same 404. + node.seed_repo(&owner_did, "priv", false).await; + for (label, req) in [ + ( + "anon", + client.get(format!( + "{}{}", + node.base_url, + info_path(&owner_did, "priv") + )), + ), + ( + "stranger", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &info_path(&owner_did, "priv"), + Vec::new(), + &stranger, + ), + ), + ] { + let resp = req.send().await.expect("send"); + assert_eq!(resp.status().as_u16(), 404, "{label}"); + } + + node.shutdown().await; +} + +/// Pickle entries carry the unsafe marker in the tree (and siblings). +#[sqlx::test] +async fn pickle_entries_marked_unsafe(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(22); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let pickle = b"pickle bytes".to_vec(); + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/m"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![ManifestFile { + path: "model.pkl".to_string(), + size: pickle.len() as u64, + sha256: sha256_hex(&pickle), + format: FileFormat::Pickle, + storage: StorageKind::Git, + }], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().unwrap(); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + let dir = tempfile::tempdir().unwrap(); + let commit = make_release_repo(dir.path(), &manifest_bytes, &sig, &[("model.pkl", &pickle)]); + set_disk_path(&pool, &repo_id, dir.path()).await; + seed_published_release( + &pool, + &repo_id, + &commit, + "main", + &owner_did, + &sha256_hex(&manifest_bytes), + None, + &[], + ) + .await; + + let resp = client + .get(format!( + "{}{}", + node.base_url, + tree_path(&owner_did, "m", "main") + )) + .send() + .await + .expect("send"); + let entries: Vec = resp.json().await.unwrap(); + assert_eq!(entries[0]["unsafe"].as_bool(), Some(true)); + + node.shutdown().await; +} + +/// A repo whose git default branch is `master` still serves HF `main`: +/// revision `main` resolves to the newest release on `master` and refs +/// reports it under `main`. +#[sqlx::test] +async fn master_default_branch_serves_hf_main(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(23); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + sqlx::query("UPDATE repos SET default_branch = 'master' WHERE id = $1") + .bind(&repo_id) + .execute(&pool) + .await + .unwrap(); + let fx = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[], + "master", + ) + .await; + + let resp = client + .get(format!( + "{}{}", + node.base_url, + rev_path(&owner_did, "m", "main") + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.unwrap(); + assert_eq!(v["sha"].as_str(), Some(fx.commit.as_str())); + + let resp = client + .get(format!("{}{}", node.base_url, refs_path(&owner_did, "m"))) + .send() + .await + .expect("send"); + let v: Value = resp.json().await.unwrap(); + assert_eq!(v["branches"][0]["name"].as_str(), Some("main")); + assert_eq!( + v["branches"][0]["targetCommit"].as_str(), + Some(fx.commit.as_str()) + ); + + node.shutdown().await; +} + +/// A plain git commit after the release does not move HF `main`: refs and +/// model info still name the release commit. +#[sqlx::test] +async fn later_commit_does_not_move_hf_main(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(24); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let fx = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[], + "main", + ) + .await; + + // A second, unrelated commit on the same on-disk repo. + let record = sqlx::query_as::<_, (String,)>("SELECT disk_path FROM repos WHERE id = $1") + .bind(&repo_id) + .fetch_one(&pool) + .await + .unwrap(); + let dir = std::path::PathBuf::from(&record.0); + std::fs::write(dir.join("later.txt"), b"not a release").unwrap(); + run_git(&dir, &["add", "-A"]); + run_git( + &dir, + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "later", + ], + ); + let later = run_git(&dir, &["rev-parse", "HEAD"]); + assert_ne!(later, fx.commit); + + for path in [info_path(&owner_did, "m"), refs_path(&owner_did, "m")] { + let resp = client + .get(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200, "{path}"); + let v: Value = resp.json().await.unwrap(); + let sha = v["sha"] + .as_str() + .or_else(|| v["branches"][0]["targetCommit"].as_str()); + assert_eq!(sha, Some(fx.commit.as_str()), "{path} must pin the release"); + } + + node.shutdown().await; +} + +/// Resolve: byte-exact full and ranged GET on a git-stored file, HEAD +/// headers, 416 bounds, stale If-Range, and the EntryNotFound shape. +#[sqlx::test] +async fn resolve_git_file_ranges_and_headers(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(25); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let fx = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[("weights.safetensors", CHUNKED_FILE_CONTENTS, 16)], + "main", + ) + .await; + let path = resolve_path(&owner_did, "m", "main", "config.json"); + let etag = format!("\"{}\"", sha256_hex(GIT_FILE)); + + // Full GET: exact bytes plus the pinned headers. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + assert_eq!(resp.headers()["x-repo-commit"].to_str().unwrap(), fx.commit); + assert_eq!(resp.headers()["etag"].to_str().unwrap(), etag); + assert_eq!( + resp.headers()["content-length"].to_str().unwrap(), + GIT_FILE.len().to_string() + ); + assert_eq!(resp.headers()["accept-ranges"].to_str().unwrap(), "bytes"); + let body = resp.bytes().await.unwrap(); + assert_eq!(body.as_ref(), GIT_FILE); + + // HEAD: same headers, empty body. + let resp = client + .head(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + assert_eq!( + resp.headers()["content-length"].to_str().unwrap(), + GIT_FILE.len().to_string() + ); + assert_eq!(resp.headers()["x-repo-commit"].to_str().unwrap(), fx.commit); + assert!(resp.bytes().await.unwrap().is_empty()); + + // Open-ended range: 206 with a correct Content-Range and suffix bytes. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("range", "bytes=10-") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 206); + assert_eq!( + resp.headers()["content-range"].to_str().unwrap(), + format!("bytes 10-{}/{}", GIT_FILE.len() - 1, GIT_FILE.len()) + ); + let body = resp.bytes().await.unwrap(); + assert_eq!(body.as_ref(), &GIT_FILE[10..]); + + // Stale If-Range: full 200, not a partial. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("range", "bytes=10-") + .header("if-range", "\"stale\"") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + assert_eq!(resp.bytes().await.unwrap().as_ref(), GIT_FILE); + + // Out of bounds: 416 with `bytes */total`. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("range", "bytes=1000000-") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 416); + assert_eq!( + resp.headers()["content-range"].to_str().unwrap(), + format!("bytes */{}", GIT_FILE.len()) + ); + + // Missing file: 404 EntryNotFound with X-Repo-Commit. + let resp = client + .get(format!( + "{}{}", + node.base_url, + resolve_path(&owner_did, "m", "main", "absent.bin") + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 404); + assert_eq!( + resp.headers()["x-error-code"].to_str().unwrap(), + "EntryNotFound" + ); + assert_eq!(resp.headers()["x-repo-commit"].to_str().unwrap(), fx.commit); + + // A client holding the object gets a 304: etag is the file sha256. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("if-none-match", &etag) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 304); + assert_eq!(resp.headers()["etag"].to_str().unwrap(), etag); + assert_eq!(resp.headers()["x-repo-commit"].to_str().unwrap(), fx.commit); + // A mismatched validator does not short-circuit. + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("if-none-match", "\"stale\"") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + + node.shutdown().await; +} + +/// A chunked file streams exact bytes, and a range spanning its block +/// boundary returns contiguous correct bytes. +#[sqlx::test] +async fn resolve_chunked_file_full_and_cross_block_range(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(26); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[("weights.safetensors", CHUNKED_FILE_CONTENTS, 16)], + "main", + ) + .await; + let path = resolve_path(&owner_did, "m", "main", "weights.safetensors"); + + let resp = client + .get(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let body = resp.bytes().await.unwrap(); + assert_eq!(body.as_ref(), CHUNKED_FILE_CONTENTS); + + // A range spanning the first two 16-byte blocks (bytes 8..24). + let resp = client + .get(format!("{}{}", node.base_url, path)) + .header("range", "bytes=8-23") + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 206); + assert_eq!( + resp.headers()["content-range"].to_str().unwrap(), + format!("bytes 8-23/{}", CHUNKED_FILE_CONTENTS.len()) + ); + let body = resp.bytes().await.unwrap(); + assert_eq!(body.as_ref(), &CHUNKED_FILE_CONTENTS[8..24]); + + node.shutdown().await; +} + +/// After the repo turns private, anonymous HEAD and GET on resolve return +/// the existence-hiding 404. +#[sqlx::test] +async fn resolve_denies_after_repo_turns_private(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(27); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[], + "main", + ) + .await; + sqlx::query("UPDATE repos SET is_public = false WHERE id = $1") + .bind(&repo_id) + .execute(&pool) + .await + .unwrap(); + + let path = resolve_path(&owner_did, "m", "main", "config.json"); + for (label, req) in [ + ("HEAD", client.head(format!("{}{}", node.base_url, path))), + ("GET", client.get(format!("{}{}", node.base_url, path))), + ] { + let resp = req.send().await.expect("send"); + assert_eq!(resp.status().as_u16(), 404, "{label}"); + } + + node.shutdown().await; +} From 7fa4fc29c16168dcecc62ebd8f14680de2121d57 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:16:25 -0600 Subject: [PATCH 02/14] fix(node): pin git-stored model files into the block map Off-node fetch could rebuild chunked files but had no source for the small files the manifest keeps in git. The map job now pins those bytes and indexes them under files, keyed by manifest sha256. --- crates/twigpine-node/src/models/durability.rs | 151 +++++++++++++++++- 1 file changed, 147 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-node/src/models/durability.rs b/crates/twigpine-node/src/models/durability.rs index fc8e8dc4..d953e0ba 100644 --- a/crates/twigpine-node/src/models/durability.rs +++ b/crates/twigpine-node/src/models/durability.rs @@ -283,14 +283,36 @@ async fn execute_job( .db .model_durability_done_cids(job.release_id, KIND_BLOCK) .await?; - let map: serde_json::Map = pairs + let blocks: serde_json::Map = pairs .into_iter() .map(|(sha, cid)| (sha, serde_json::Value::String(cid))) .collect(); + // Git-stored files live in the commit, not the block store, so + // nothing else ever pins them. Pin each here and index it by + // its manifest sha256, or a fetch without this node can rebuild + // every chunked file and still miss config.json. + let manifest_bytes = git_bytes(state, release, MANIFEST_PATH).await?; + let manifest = twigpine_core::model::manifest::Manifest::parse(&manifest_bytes) + .map_err(|e| AppError::Internal(anyhow::anyhow!("manifest parse: {e}")))?; + let mut files = serde_json::Map::new(); + for file in manifest + .files + .iter() + .filter(|f| f.storage == twigpine_core::model::manifest::StorageKind::Git) + { + let data = git_bytes(state, release, &file.path).await?; + match pin_bytes(state, &file.sha256, &data, fence).await? { + JobOutcome::Done(cid) => { + files.insert(file.sha256.clone(), serde_json::Value::String(cid)); + } + JobOutcome::Deferred => return Ok(JobOutcome::Deferred), + } + } let payload = serde_json::json!({ "schema": "gitlawb/model-block-map/v1", "release": release.commit_sha, - "blocks": map, + "blocks": blocks, + "files": files, }); let bytes = serde_json::to_vec(&payload) .map_err(|e| AppError::Internal(anyhow::anyhow!("block map serialize: {e}")))?; @@ -696,7 +718,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let block_dir = tempfile::tempdir().unwrap(); - let manifest = br#"{"schema":"gitlawb/model-release/v1","files":[]}"#.to_vec(); + let manifest = br#"{"schema":"gitlawb/model-release/v1","repo":"did:owner/m","publisher_did":"did:owner","license":"MIT","files":[]}"#.to_vec(); let commit = make_release_git(dir.path(), &manifest, "sig"); let manifest_sha = sha256_hex(&manifest); let block_bytes = b"BLOCKBYTES-durability".to_vec(); @@ -824,6 +846,127 @@ mod tests { map_cid_holder.assert_async().await; } + /// A git-stored file never touches the block store, so only the map + /// job pins it. The map must index it under `files` keyed by the + /// manifest sha256 or an off-node fetch cannot rebuild it. + #[sqlx::test] + async fn block_map_indexes_git_files(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let mut irys = mockito::Server::new_async().await; + + let dir = tempfile::tempdir().unwrap(); + let block_dir = tempfile::tempdir().unwrap(); + let config_bytes = br#"{"arch":"test-GITFILE"}"#.to_vec(); + let config_sha = sha256_hex(&config_bytes); + std::fs::write(dir.path().join("config.json"), &config_bytes).unwrap(); + let manifest = format!( + r#"{{"schema":"gitlawb/model-release/v1","repo":"did:owner/m","publisher_did":"did:owner","license":"MIT","files":[{{"path":"config.json","size":{},"sha256":"{config_sha}","format":"text","storage":"git"}}]}}"#, + config_bytes.len() + ) + .into_bytes(); + let commit = make_release_git(dir.path(), &manifest, "sig"); + let block_bytes = b"BLOCKBYTES-gitfiles".to_vec(); + + let mut state = test_state_with(pool.clone(), |cfg| { + cfg.ipfs_api = kubo.url(); + cfg.irys_url = irys.url(); + }) + .await; + let store: Arc = Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir.path().to_path_buf()).unwrap(), + ); + state.block_store = Some(store.clone()); + + let block_sha = put_block(&store, &block_bytes).await; + seed_block_row(&state.db, &block_sha, block_bytes.len() as u64).await; + seed_repo(&state.db, "r1", true, dir.path()).await; + let release_id = seed_release( + &state.db, + "r1", + &commit, + "published", + &sha256_hex(&manifest), + None, + std::slice::from_ref(&block_sha), + ) + .await; + + for (marker, data) in [ + ("BLOCKBYTES", &block_bytes), + ("model-release/v1", &manifest), + ("GITFILE", &config_bytes), + ] { + kubo.mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex(marker.to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(data) + )) + .create_async() + .await; + } + // Capture the map object the job posts so the `files` index can be + // asserted directly, not through a second read of Kubo. + let captured: std::sync::Arc>> = + std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let captured_in = captured.clone(); + kubo.mock("POST", mockito::Matcher::Regex(r"^/api/v0/add".to_string())) + .match_body(mockito::Matcher::Regex("model-block-map".to_string())) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(move |req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let start = body + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4) + .unwrap_or(0); + let end = body + .windows(2) + .rposition(|w| w == b"\r\n") + .unwrap_or(body.len()); + let object = body[start..end].to_vec(); + *captured_in.lock().unwrap() = object.clone(); + format!( + r#"{{"Hash":"{}"}}"#, + twigpine_core::cid::Cid::from_git_object_bytes(&object) + ) + .into_bytes() + }) + .create_async() + .await; + irys.mock("POST", "/upload") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"TXGIT"}"#) + .create_async() + .await; + + enqueue_for_release(&state, release_id).await.unwrap(); + for _ in 0..4 { + durability_pass(&state).await.unwrap(); + } + + // The captured slice can carry multipart framing after the object; + // parse the first complete JSON value rather than exact bounds. + let map: serde_json::Value = + serde_json::Deserializer::from_slice(&captured.lock().unwrap()) + .into_iter::() + .next() + .expect("map body holds a value") + .expect("map body parses"); + let expected_cid = + twigpine_core::cid::Cid::from_git_object_bytes(&config_bytes).to_string(); + assert_eq!( + map["files"][&config_sha].as_str(), + Some(expected_cid.as_str()), + "git-stored file must index into the map: {map}" + ); + assert!(map["blocks"][&block_sha].is_string(), "blocks kept: {map}"); + } + /// While a pin job is still pending, the map and anchor defer rather /// than posting incomplete addresses; once the object appears the next /// pass completes the chain. @@ -834,7 +977,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let block_dir = tempfile::tempdir().unwrap(); - let manifest = br#"{"schema":"gitlawb/model-release/v1","files":[]}"#.to_vec(); + let manifest = br#"{"schema":"gitlawb/model-release/v1","repo":"did:owner/m","publisher_did":"did:owner","license":"MIT","files":[]}"#.to_vec(); let commit = make_release_git(dir.path(), &manifest, "sig"); let block_bytes = b"BLOCKBYTES-later".to_vec(); let block_sha = sha256_hex(&block_bytes); From e9c83e808d73cd72f1bab6970a4470f3ea02b369 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:21:16 -0600 Subject: [PATCH 03/14] feat(cli): add twigpine model fetch Rebuild a published release from Arweave and IPFS without the origin node: discover release anchors by Irys tags, verify the manifest against the caller-supplied DID, then rebuild every file with sha256 checks under a bounded block cache. The CLI becomes a lib+bin so the node e2e can drive the fetch in-process. --- Cargo.lock | 3 + crates/twigpine-cli/Cargo.toml | 2 + crates/twigpine-cli/src/clone.rs | 20 +- crates/twigpine-cli/src/lib.rs | 43 ++ crates/twigpine-cli/src/main.rs | 39 +- crates/twigpine-cli/src/model.rs | 771 ++++++++++++++++++++++- crates/twigpine-cli/tests/model_fetch.rs | 434 +++++++++++++ 7 files changed, 1265 insertions(+), 47 deletions(-) create mode 100644 crates/twigpine-cli/src/lib.rs create mode 100644 crates/twigpine-cli/tests/model_fetch.rs diff --git a/Cargo.lock b/Cargo.lock index 4dcc8899..6930f863 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7434,6 +7434,7 @@ dependencies = [ "clap", "dirs", "ed25519-dalek 2.2.0", + "hex", "icaptcha-client", "libc", "mockito", @@ -7441,6 +7442,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "thiserror 2.0.18", "tokio", @@ -7536,6 +7538,7 @@ dependencies = [ "tower-http", "tracing", "tracing-subscriber", + "twigpine-cli", "twigpine-core", "unicode-normalization", "url", diff --git a/crates/twigpine-cli/Cargo.toml b/crates/twigpine-cli/Cargo.toml index b844b079..8cba8178 100644 --- a/crates/twigpine-cli/Cargo.toml +++ b/crates/twigpine-cli/Cargo.toml @@ -42,6 +42,8 @@ alloy = { version = "1", default-features = false, features = [ ] } ed25519-dalek = { workspace = true } +sha2 = { workspace = true } +hex = { workspace = true } [dev-dependencies] mockito = "1" diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 24692380..773f80dd 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -476,9 +476,9 @@ struct Manifest { /// case it is the most recent and sorts as newest in the merge tie-break. A mined /// anchor is always `Some(_)` (0 if the gateway reported an unreadable height) so /// a malformed height can never masquerade as pending/newest. -struct TxRef { - id: String, - height: Option, +pub(crate) struct TxRef { + pub(crate) id: String, + pub(crate) height: Option, } /// Edges requested per Arweave GraphQL page (`first:` in the discovery query) and @@ -486,7 +486,7 @@ struct TxRef { /// `ARWEAVE_DISCOVERY_QUERY` MUST equal this constant; `query_first_matches_page_size` /// pins that invariant at test time (the query keeps a literal because `format!`-ing /// the brace-heavy GraphQL body would be error-prone). -const ARWEAVE_PAGE_SIZE: usize = 100; +pub(crate) const ARWEAVE_PAGE_SIZE: usize = 100; /// Paginated discovery query: manifests tagged for this repo, newest first, with /// `pageInfo` for cursor pagination and `block{height}` for the recency tie-break. @@ -496,10 +496,10 @@ const ARWEAVE_DISCOVERY_QUERY: &str = r#"query($repo:String!,$cursor:String){tra /// plus pagination state. `has_next` is `None` when the response omitted /// `pageInfo` entirely (an older or partial gateway), which the discovery loop /// treats as terminal but flags when the page was full (possible truncation). -struct TxPage { - refs: Vec, - has_next: Option, - end_cursor: Option, +pub(crate) struct TxPage { + pub(crate) refs: Vec, + pub(crate) has_next: Option, + pub(crate) end_cursor: Option, } /// Parse one Arweave GraphQL `transactions` page: each edge's tx id and block @@ -514,7 +514,7 @@ struct TxPage { /// (It does not bound the response body itself: `reqwest` buffers and deserializes /// the whole body before this runs — an unbounded-body concern shared by every /// gateway read in this file, addressed separately if it ever matters.) -fn parse_tx_page(v: &serde_json::Value) -> TxPage { +pub(crate) fn parse_tx_page(v: &serde_json::Value) -> TxPage { let txns = v.get("data").and_then(|d| d.get("transactions")); let refs: Vec = txns .and_then(|t| t.get("edges")) @@ -566,7 +566,7 @@ fn parse_tx_page(v: &serde_json::Value) -> TxPage { /// Order a block height so that a not-yet-mined anchor (`None`) sorts above any /// mined one, and mined anchors order by ascending height. Higher rank == newer. -fn height_rank(h: Option) -> (u8, u64) { +pub(crate) fn height_rank(h: Option) -> (u8, u64) { match h { None => (1, 0), // pending anchor: newest Some(v) => (0, v), // mined: by block height diff --git a/crates/twigpine-cli/src/lib.rs b/crates/twigpine-cli/src/lib.rs new file mode 100644 index 00000000..7289fa17 --- /dev/null +++ b/crates/twigpine-cli/src/lib.rs @@ -0,0 +1,43 @@ +//! Library surface of the `twigpine` CLI. +//! +//! `main.rs` is a thin shell over these modules; the lib target exists so the +//! model fetch path is callable in-process (`model::fetch_model`, which the +//! node's end-to-end test drives after the node stops serving) and so command +//! modules can be exercised from integration tests without spawning the +//! binary. +#![recursion_limit = "256"] + +pub mod agent; +pub mod bounty; +pub mod cert; +pub mod changelog; +pub mod clone; +pub mod doctor; +pub mod http; +pub mod identity; +pub mod init; +pub mod ipfs_cmd; +pub mod issue; +pub mod mcp; +pub mod mirror; +pub mod model; +pub mod name; +pub mod node; +pub mod node_stake; +pub mod peer; +pub mod pr; +pub mod profile; +pub mod protect; +pub mod quickstart; +pub mod register; +pub mod repo; +mod secret_file; +pub mod star; +pub mod status; +pub mod sync; +pub mod task; +mod text; +pub mod ucan_cmd; +pub mod visibility; +pub mod webhook; +pub mod whoami; diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index 9f1dc2e0..e362ff17 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -3,40 +3,11 @@ use anyhow::Result; use clap::{Parser, Subcommand}; -mod agent; -mod bounty; -mod cert; -mod changelog; -mod clone; -mod doctor; -mod http; -mod identity; -mod init; -mod ipfs_cmd; -mod issue; -mod mcp; -mod mirror; -mod model; -mod name; -mod node; -mod node_stake; -mod peer; -mod pr; -mod profile; -mod protect; -mod quickstart; -mod register; -mod repo; -mod secret_file; -mod star; -mod status; -mod sync; -mod task; -mod text; -mod ucan_cmd; -mod visibility; -mod webhook; -mod whoami; +use twigpine_cli::{ + agent, bounty, cert, changelog, clone, doctor, identity, init, ipfs_cmd, issue, mcp, mirror, + model, name, node, peer, pr, profile, protect, quickstart, register, repo, star, status, sync, + task, ucan_cmd, visibility, webhook, whoami, +}; #[derive(Parser)] #[command( diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index dd2c2ff1..d7e1fb6a 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -1,4 +1,5 @@ -//! `twigpine model` — open-weight model publishing (KTD14). +//! `twigpine model`: open-weight model publishing (KTD14) and independent +//! release fetching (KTD15). //! //! `twigpine model publish` runs inside a local clone of a fully public //! Twigpine repo: it classifies files by the chunking threshold, packs the @@ -6,11 +7,19 @@ //! 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. +//! +//! `twigpine model fetch` rebuilds a published release without the node: it +//! finds release anchors by Irys tag on an Arweave gateway, pulls the +//! manifest, reconstruction object, and sha256-to-CID block map off an IPFS +//! gateway, verifies the manifest signature against a caller-supplied owner +//! DID (never a DID read out of the anchor), and writes byte-verified files +//! in an HF-snapshot-like layout. use anyhow::{bail, Context, Result}; use clap::{Args, Subcommand}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; +use sha2::Digest as _; use std::collections::{HashMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; @@ -23,11 +32,14 @@ use twigpine_core::model::manifest::{ MANIFEST_SCHEMA_V1, }; use twigpine_core::model::reconstruction::{ - pack_file_with, BlockEntry, DedupIndex, Reconstruction, + pack_file_with, BlockEntry, DedupIndex, FileEntry, Reconstruction, }; -use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; +use crate::http::{ + json_or_denial, read_body_capped_bytes, read_json, sanitize_node_msg, NodeClient, +}; use crate::identity::load_keypair_from_dir; +use twigpine_core::did::Did; const DEFAULT_CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024; const SESSION_HEADER: &str = "x-twigpine-model-session"; @@ -42,10 +54,42 @@ const RECONSTRUCTION_FETCH_CAP: usize = 64 * 1024 * 1024; const POLL_INTERVAL: Duration = Duration::from_secs(3); const POLL_BUDGET: Duration = Duration::from_secs(300); +// ── fetch constants ───────────────────────────────────────────────────────── +/// Cap on one anchor transaction body: the anchor is a few hundred bytes of +/// JSON, so a body past this is not one. +const ANCHOR_BODY_CAP: usize = 1024 * 1024; +/// Cap on a fetched manifest: a 5,000-file manifest is a couple of MiB of +/// JSON; larger is not one. +const MANIFEST_FETCH_CAP: usize = 16 * 1024 * 1024; +/// Cap on the sha256 -> provider-CID block map; thousands of entries fit in +/// a few hundred KiB. +const BLOCK_MAP_FETCH_CAP: usize = 64 * 1024 * 1024; +/// One content block fetched whole: bounded by the node's 128 MiB block cap, +/// so the read cap is one byte past it. +const OBJECT_FETCH_CAP: usize = (128 * 1024 * 1024) + 1; +/// Resident budget for the fetched-block LRU. Blocks are ~64 MiB each, so a +/// few shared blocks stay hot across chunked files without holding the model. +const BLOCK_CACHE_BUDGET: usize = 256 * 1024 * 1024; +/// Anchor candidates tried before giving up; anchors iterate newest first so +/// the cap only binds a repo with an absurd anchor history. +const MAX_ANCHOR_CANDIDATES: usize = 64; + +const ANCHOR_SCHEMA: &str = "gitlawb/model-release-anchor/v1"; +const BLOCK_MAP_SCHEMA: &str = "gitlawb/model-block-map/v1"; + +/// Paginated discovery query for release anchors, mirroring clone.rs's +/// `ARWEAVE_DISCOVERY_QUERY` with the model-release schema tag. Edges come +/// back newest-first (`sort:HEIGHT_DESC`); the refs are re-sorted locally by +/// block height as well so a gateway that ignores `sort` still tries the +/// newest candidates first. +const ANCHOR_DISCOVERY_QUERY: &str = r#"query($repo:String!,$cursor:String){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/model-release-anchor/v1"]},{name:"Repo",values:[$repo]}],first:100,after:$cursor,sort:HEIGHT_DESC){pageInfo{hasNextPage endCursor}edges{cursor node{id block{height}}}}}"#; + #[derive(Subcommand)] pub enum ModelCmd { /// Publish the working tree as a signed model release Publish(PublishArgs), + /// Rebuild a published release from Arweave and IPFS, without the node + Fetch(FetchArgs), } #[derive(Args)] @@ -78,9 +122,41 @@ pub struct PublishArgs { pub dir: Option, } +#[derive(Args)] +pub struct FetchArgs { + /// Repo to fetch: / + pub repo: String, + /// Owner DID the release manifest must verify against. Required: the + /// anchor's own DID fields are untrusted text and are never used as the + /// verifying key. + #[arg(long)] + pub expect_did: String, + /// Release commit to fetch (default: the newest anchor that verifies) + #[arg(long)] + pub revision: Option, + /// Output directory (default: -) + #[arg(long)] + pub output: Option, + /// Arweave gateway for release-anchor discovery and bodies + #[arg( + long, + default_value = "https://arweave.net", + env = "TWIGPINE_ARWEAVE_GATEWAY" + )] + pub arweave_gateway: String, + /// IPFS gateway for the manifest, block map, and content objects + #[arg( + long, + default_value = "https://dweb.link", + env = "TWIGPINE_IPFS_GATEWAY" + )] + pub ipfs_gateway: String, +} + pub async fn run(cmd: ModelCmd) -> Result<()> { match cmd { ModelCmd::Publish(a) => cmd_publish(a).await, + ModelCmd::Fetch(a) => cmd_fetch(a).await, } } @@ -1005,6 +1081,695 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } +// ── fetch ─────────────────────────────────────────────────────────────────── + +/// What a verified fetch produced. Returned by [`fetch_model`] so callers +/// (the CLI wrapper, the node e2e test) can report or assert on the run. +#[derive(Debug)] +pub struct FetchReport { + /// `/` as fetched. + pub repo: String, + /// Release commit the verified anchor named. + pub release_commit: String, + /// Arweave transaction id of the anchor used. + pub anchor_tx: String, + /// Files written under `output_dir`. + pub files: usize, + /// Total bytes written. + pub bytes: u64, + /// Where the release was rebuilt. + pub output_dir: PathBuf, + /// One line per skipped candidate anchor, in the order they were tried. + pub warnings: Vec, +} + +/// The anchor JSON, exactly as `arweave::anchor_model_release` posts it. +/// Identity fields are record-keeping only: `owner_did` is used to SELECT a +/// candidate, never as the verifying key (KTD15). +#[derive(Debug, Deserialize)] +struct ReleaseAnchorBody { + schema: String, + repo: String, + owner_did: String, + release_commit: String, + manifest_sha256: String, + manifest_cid: String, + #[serde(default)] + reconstruction_sha256: Option, + #[serde(default)] + reconstruction_cid: Option, + block_map_cid: String, + claim_signature: String, +} + +/// The sha256 -> provider-CID index pinned by the block-map job. `files` +/// indexes git-stored files by manifest sha256 and may be absent on maps +/// produced before the git-file fix; `blocks` indexes content blocks. +#[derive(Debug, Deserialize)] +struct BlockMapBody { + schema: String, + #[serde(default)] + blocks: HashMap, + #[serde(default)] + files: HashMap, +} + +/// Record one skip reason: sanitized once, then both the terminal and the +/// report get the same line. +fn note_skip(warnings: &mut Vec, msg: String) { + let line = sanitize_node_msg(&msg); + eprintln!("warning: {line}"); + warnings.push(line); +} + +/// The shared client plus the two gateway base URLs, bundled so the helper +/// signatures stay small. +struct Net<'a> { + client: &'a reqwest::Client, + ag: &'a str, + ig: &'a str, +} + +/// GET `url` and return at most `cap` bytes. `what` names the object for the +/// error. A truncated or dead-mid-read body is an error, not a partial object. +async fn get_capped( + client: &reqwest::Client, + url: &str, + cap: usize, + what: &str, +) -> Result> { + let resp = client + .get(url) + .send() + .await + .with_context(|| format!("{what} request failed"))?; + let status = resp.status(); + if !status.is_success() { + bail!("{what} fetch returned {status}"); + } + let capped = read_body_capped_bytes(resp, cap).await; + if capped.truncated { + bail!("{what} body exceeded the {cap}-byte cap"); + } + if capped.read_failed { + bail!("{what} body failed mid-read"); + } + Ok(capped.bytes) +} + +/// Discover release-anchor transactions for `repo` on the Arweave gateway, +/// newest first. Same paginated, bounded loop shape as clone.rs's manifest +/// discovery, sharing its page parser. +async fn discover_release_anchors( + net: &Net<'_>, + repo: &str, + warnings: &mut Vec, +) -> Vec { + const MAX_PAGES: usize = 1000; + const MAX_TX_IDS: usize = 10_000; + let mut after: Option = None; + let mut prev_cursor: Option = None; + let mut seen: HashSet = HashSet::new(); + let mut refs: Vec = Vec::new(); + for page_num in 0..MAX_PAGES { + let gql_body = json!({ + "query": ANCHOR_DISCOVERY_QUERY, + "variables": { "repo": repo, "cursor": after }, + }); + let response = match net + .client + .post(format!("{}/graphql", net.ag)) + .json(&gql_body) + .send() + .await + { + Ok(r) if r.status().is_success() => r.json::().await.ok(), + _ => None, + }; + let value = match response { + Some(v) => v, + None => { + // A failure after discovery began leaves a knowingly partial + // candidate set; a page-1 failure just means no anchors here. + if page_num > 0 { + note_skip( + warnings, + "Arweave anchor discovery was interrupted by a gateway error".to_string(), + ); + } + break; + } + }; + let page = crate::clone::parse_tx_page(&value); + let full = page.refs.len() >= crate::clone::ARWEAVE_PAGE_SIZE; + for r in page.refs { + if seen.insert(r.id.clone()) { + refs.push(r); + } + } + if refs.len() >= MAX_TX_IDS { + note_skip( + warnings, + format!("Arweave anchor discovery hit the {MAX_TX_IDS}-transaction cap"), + ); + break; + } + match page.has_next { + Some(true) => match page.end_cursor { + Some(c) if Some(&c) != prev_cursor.as_ref() => { + prev_cursor = Some(c.clone()); + after = Some(c); + } + _ => break, + }, + Some(false) => break, + // No pageInfo: terminal. A full page without it may be a silently + // truncated gateway, so flag that like clone.rs does. + None => { + if full { + note_skip( + warnings, + "Arweave gateway returned a full page without pagination \ + metadata; anchor discovery may be incomplete" + .to_string(), + ); + } + break; + } + } + } + // The query asks for HEIGHT_DESC; rank locally too so an edge order a + // gateway gets wrong still tries the newest candidate first. Pending + // anchors (no block) rank newest, matching clone.rs's tie-break. + refs.sort_by(|a, b| { + crate::clone::height_rank(b.height).cmp(&crate::clone::height_rank(a.height)) + }); + refs +} + +/// One anchor candidate through its trust gates: fetch the body, parse the +/// anchor JSON, then fetch the manifest and verify it against the expected +/// DID. Returns `Ok(Some(..))` only when the manifest verifies; every failure +/// is a warning plus `Ok(None)` so the next candidate gets tried. +async fn verify_candidate( + net: &Net<'_>, + tx_id: &str, + repo: &str, + expect_did: &Did, + revision: Option<&str>, + warnings: &mut Vec, +) -> Option<(ReleaseAnchorBody, Manifest)> { + let mut skip = |why: String| { + note_skip(warnings, format!("anchor {tx_id}: {why}")); + None + }; + let body = match get_capped( + net.client, + &format!("{}/{tx_id}", net.ag), + ANCHOR_BODY_CAP, + "anchor", + ) + .await + { + Ok(b) => b, + Err(e) => return skip(format!("{e}")), + }; + let anchor: ReleaseAnchorBody = match serde_json::from_slice(&body) { + Ok(a) => a, + Err(e) => return skip(format!("anchor body is not valid JSON: {e}")), + }; + if anchor.schema != ANCHOR_SCHEMA { + return skip(format!("unknown anchor schema {:?}", anchor.schema)); + } + if anchor.repo != repo { + return skip(format!( + "anchor names repo {:?}, expected {repo}", + anchor.repo + )); + } + // The anchor's DID chooses which anchors to try; it is never the + // verifying key. A mismatch here is the strongest possible signal the + // manifest will not verify, so skip without spending the fetch. + if anchor.owner_did != expect_did.to_string() { + return skip(format!( + "anchor names owner {}, expected {}", + anchor.owner_did, expect_did + )); + } + if let Some(want) = revision { + if anchor.release_commit != want { + return skip(format!( + "anchor names commit {}, expected {want}", + anchor.release_commit + )); + } + } + let manifest_bytes = match get_capped( + net.client, + &format!("{}/ipfs/{}", net.ig, anchor.manifest_cid), + MANIFEST_FETCH_CAP, + "manifest", + ) + .await + { + Ok(b) => b, + Err(e) => return skip(format!("{e}")), + }; + let got = sha256_hex(&manifest_bytes); + if got != anchor.manifest_sha256 { + return skip(format!( + "manifest bytes hash to {got}, anchor claims {}", + anchor.manifest_sha256 + )); + } + let manifest = match manifest::verify(&manifest_bytes, &anchor.claim_signature, expect_did) { + Ok(m) => m, + Err(e) => return skip(format!("manifest verification failed: {e}")), + }; + if manifest.repo != repo { + return skip(format!( + "verified manifest names repo {:?}, expected {repo}", + manifest.repo + )); + } + Some((anchor, manifest)) +} + +/// Byte-budgeted LRU over fetched content blocks. A fine-tuned release +/// shares blocks across files, so a small cache saves re-fetches; the model +/// itself never sits resident. +struct BlockCache { + map: HashMap>, + order: std::collections::VecDeque, + used: usize, +} + +impl BlockCache { + fn new() -> Self { + Self { + map: HashMap::new(), + order: std::collections::VecDeque::new(), + used: 0, + } + } + + fn get(&mut self, sha: &str) -> Option<&[u8]> { + if self.map.contains_key(sha) { + self.order.retain(|k| k != sha); + self.order.push_back(sha.to_string()); + return self.map.get(sha).map(|v| v.as_slice()); + } + None + } + + fn insert(&mut self, sha: String, bytes: Vec) { + if bytes.len() > BLOCK_CACHE_BUDGET { + return; + } + while self.used + bytes.len() > BLOCK_CACHE_BUDGET { + match self.order.pop_front() { + Some(old) => { + if let Some(v) = self.map.remove(&old) { + self.used -= v.len(); + } + } + None => break, + } + } + self.used += bytes.len(); + self.map.insert(sha.clone(), bytes); + self.order.push_back(sha); + } +} + +/// What chunked rebuild needs to fetch one content block: the network +/// handle, the untrusted block map, and the shared byte-budgeted cache. +struct BlockSource<'a> { + client: &'a reqwest::Client, + ig: &'a str, + map: &'a BlockMapBody, + cache: &'a mut BlockCache, +} + +impl BlockSource<'_> { + /// Fetch one content block through the block map and hash-check it + /// against its sha256 key. The map is untrusted (it arrived through the + /// anchor), so the hash is what binds bytes to the manifest's claim, not + /// the CID. + async fn block(&mut self, sha: &str) -> Result> { + if let Some(hit) = self.cache.get(sha) { + return Ok(hit.to_vec()); + } + let cid = self + .map + .blocks + .get(sha) + .with_context(|| format!("block map has no CID for block {sha}"))?; + let bytes = get_capped( + self.client, + &format!("{}/ipfs/{cid}", self.ig), + OBJECT_FETCH_CAP, + &format!("block {sha}"), + ) + .await?; + let got = sha256_hex(&bytes); + if got != sha { + bail!("block {sha} content hashes to {got}"); + } + self.cache.insert(sha.to_string(), bytes.clone()); + Ok(bytes) + } +} + +/// Byte offset of each chunk inside a block, the prefix sum over its chunk +/// table (same layout `reconstruction::chunk_offsets` uses). +fn chunk_offsets(block: &BlockEntry) -> Vec { + block + .chunks + .iter() + .scan(0u64, |off, c| { + let start = *off; + *off += c.len; + Some(start) + }) + .collect() +} + +/// Rebuild one chunked file into `out_path` from its terms, streaming to +/// disk. Per-chunk sha256s are verified as slices are consumed and the +/// whole-file digest against the manifest at the end, so at most a handful +/// of blocks are ever resident. +async fn rebuild_chunked( + source: &mut BlockSource<'_>, + rec: &Reconstruction, + file: &FileEntry, + expect_sha: &str, + expect_size: u64, + out_path: &Path, +) -> Result { + let blocks: HashMap<&str, &BlockEntry> = + rec.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect(); + let mut out = std::io::BufWriter::new( + std::fs::File::create(out_path) + .with_context(|| format!("create {}", out_path.display()))?, + ); + let mut hasher = sha2::Sha256::new(); + let mut written = 0u64; + for term in &file.terms { + let block = blocks + .get(term.block.as_str()) + .with_context(|| format!("{}: term names unknown block {}", file.path, term.block))?; + let data = source.block(&term.block).await?; + if data.len() as u64 != block.size { + bail!( + "block {} serves {} bytes, reconstruction declares {}", + term.block, + data.len(), + block.size + ); + } + let offsets = chunk_offsets(block); + let mut rel = offsets.get(term.chunk_start as usize).copied().unwrap_or(0) as usize; + for chunk in &block.chunks[term.chunk_start as usize..term.chunk_end as usize] { + let slice = &data[rel..rel + chunk.len as usize]; + let got = sha256_hex(slice); + if got != chunk.sha256 { + bail!( + "{}: chunk {} in block {} fails its sha256 check", + file.path, + chunk.sha256, + term.block + ); + } + out.write_all(slice) + .with_context(|| format!("write {}", out_path.display()))?; + hasher.update(slice); + written += chunk.len; + rel += chunk.len as usize; + } + } + out.flush() + .with_context(|| format!("write {}", out_path.display()))?; + if written != expect_size { + bail!( + "{}: rebuilt {written} bytes, manifest declares {expect_size}", + file.path + ); + } + let digest = hex::encode(hasher.finalize()); + if digest != expect_sha { + bail!( + "{}: rebuilt bytes hash to {digest}, manifest declares {expect_sha}", + file.path + ); + } + Ok(written) +} + +/// A manifest path must land strictly inside the output dir: relative, all +/// normal components, no traversal. The manifest is signed, but the check is +/// what keeps a signed bad path from writing outside `--output`. +fn safe_output_path(base: &Path, rel: &str) -> Result { + use std::path::Component; + let p = Path::new(rel); + let mut parts = Vec::new(); + for c in p.components() { + match c { + Component::Normal(s) => parts.push(s), + _ => bail!("manifest path {rel:?} is not a plain relative path"), + } + } + if parts.is_empty() { + bail!("manifest path is empty"); + } + Ok(base.join(p)) +} + +/// Rebuild a published release from Arweave and IPFS, without the node +/// (KTD15). Anchors are unsigned JSON anyone can post, so each candidate is +/// tried in turn: the anchor body selects candidates (repo, owner DID, +/// optional commit), then the manifest's signature must verify against +/// `expect_did` or the candidate is skipped with a warning. The first +/// candidate whose manifest verifies is THE release; every object after +/// that (reconstruction, block map, blocks, git files) is sha256-checked +/// against the signed manifest's claims, and a hash failure fails the fetch +/// naming the object. +pub async fn fetch_model(args: &FetchArgs) -> Result { + let (owner, name) = args + .repo + .split_once('/') + .filter(|(o, n)| !o.is_empty() && !n.is_empty() && !n.contains('/')) + .context("repo must be /")?; + let repo = format!("{owner}/{name}"); + let expect_did: Did = args + .expect_did + .parse() + .context("--expect-did is not a valid DID")?; + let ag = args.arweave_gateway.trim_end_matches('/'); + let ig = args.ipfs_gateway.trim_end_matches('/'); + // Blocks can run 128 MiB, so the client budget is generous; small + // objects keep their own shorter reads through the same client. + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(300)) + .build() + .context("failed to build HTTP client")?; + let mut warnings: Vec = Vec::new(); + let net = Net { + client: &client, + ag, + ig, + }; + + let refs = discover_release_anchors(&net, &repo, &mut warnings).await; + let (anchor_tx, anchor, manifest) = { + let mut found = None; + for r in refs.iter().take(MAX_ANCHOR_CANDIDATES) { + if let Some(v) = verify_candidate( + &net, + &r.id, + &repo, + &expect_did, + args.revision.as_deref(), + &mut warnings, + ) + .await + { + found = Some((r.id.clone(), v.0, v.1)); + break; + } + } + match found { + Some(v) => v, + None => bail!( + "no release anchor for {repo} verified against DID {expect_did} \ + ({} candidate(s) tried)", + refs.len().min(MAX_ANCHOR_CANDIDATES) + ), + } + }; + + // The manifest verified: from here a broken object is a fetch failure + // naming the object, not another candidate. + let rec = match &manifest.reconstruction { + None => None, + Some(rec_ref) => { + let rec_cid = anchor.reconstruction_cid.as_deref().with_context(|| { + format!( + "verified anchor names no reconstruction CID but the manifest \ + declares one ({})", + rec_ref.sha256 + ) + })?; + let bytes = get_capped( + &client, + &format!("{ig}/ipfs/{rec_cid}"), + RECONSTRUCTION_FETCH_CAP, + "reconstruction object", + ) + .await?; + let got = sha256_hex(&bytes); + if got != rec_ref.sha256 { + bail!( + "reconstruction object hashes to {got}, manifest declares {}", + rec_ref.sha256 + ); + } + if let Some(claimed) = &anchor.reconstruction_sha256 { + if *claimed != rec_ref.sha256 { + bail!( + "anchor claims reconstruction {claimed}, the signed manifest \ + declares {}", + rec_ref.sha256 + ); + } + } + Some( + Reconstruction::parse(&bytes) + .map_err(|e| anyhow::anyhow!("reconstruction object is invalid: {e}"))?, + ) + } + }; + + let map_bytes = get_capped( + &client, + &format!("{ig}/ipfs/{}", anchor.block_map_cid), + BLOCK_MAP_FETCH_CAP, + "block map", + ) + .await?; + let map: BlockMapBody = + serde_json::from_slice(&map_bytes).context("block map is not valid JSON")?; + if map.schema != BLOCK_MAP_SCHEMA { + bail!("block map has unknown schema {:?}", map.schema); + } + + let out_dir = args.output.clone().unwrap_or_else(|| { + PathBuf::from(format!( + "{name}-{}", + &anchor.release_commit[..anchor.release_commit.len().min(8)] + )) + }); + if out_dir.exists() { + let non_empty = out_dir + .read_dir() + .with_context(|| format!("output path {} is not a directory", out_dir.display()))? + .next() + .is_some(); + if non_empty { + bail!("output directory {} is not empty", out_dir.display()); + } + } + std::fs::create_dir_all(&out_dir).with_context(|| format!("create {}", out_dir.display()))?; + + let rec_by_path: HashMap<&str, &FileEntry> = rec + .as_ref() + .map(|r| r.files.iter().map(|f| (f.path.as_str(), f)).collect()) + .unwrap_or_default(); + let mut cache = BlockCache::new(); + let mut total = 0u64; + for file in &manifest.files { + let out_path = safe_output_path(&out_dir, &file.path)?; + if let Some(parent) = out_path.parent() { + std::fs::create_dir_all(parent)?; + } + match file.storage { + StorageKind::Git => { + // Git-stored bytes are pinned by the block-map job under + // `files` keyed by manifest sha256; `blocks` is the fallback + // for maps written before that index existed. + let cid = map + .files + .get(&file.sha256) + .or_else(|| map.blocks.get(&file.sha256)) + .with_context(|| { + format!( + "{}: block map has no CID for file {}", + file.path, file.sha256 + ) + })?; + let bytes = get_capped( + &client, + &format!("{ig}/ipfs/{cid}"), + OBJECT_FETCH_CAP, + &format!("file {}", file.path), + ) + .await?; + let got = sha256_hex(&bytes); + if got != file.sha256 { + bail!( + "{}: fetched bytes hash to {got}, manifest declares {}", + file.path, + file.sha256 + ); + } + std::fs::write(&out_path, &bytes) + .with_context(|| format!("write {}", out_path.display()))?; + total += bytes.len() as u64; + } + StorageKind::Chunked => { + let entry = rec_by_path.get(file.path.as_str()).with_context(|| { + format!( + "{}: reconstruction object has no entry for a manifest file", + file.path + ) + })?; + let rec = rec.as_ref().expect("chunked file implies reconstruction"); + let mut source = BlockSource { + client: &client, + ig, + map: &map, + cache: &mut cache, + }; + total += + rebuild_chunked(&mut source, rec, entry, &file.sha256, file.size, &out_path) + .await?; + } + } + } + + Ok(FetchReport { + repo, + release_commit: anchor.release_commit, + anchor_tx, + files: manifest.files.len(), + bytes: total, + output_dir: out_dir, + warnings, + }) +} + +async fn cmd_fetch(args: FetchArgs) -> Result<()> { + let report = fetch_model(&args).await?; + println!("fetched {} release {}", report.repo, report.release_commit); + println!(" anchor: {}", report.anchor_tx); + println!( + " verified: {} file(s), {} byte(s)", + report.files, report.bytes + ); + println!(" output: {}", report.output_dir.display()); + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/twigpine-cli/tests/model_fetch.rs b/crates/twigpine-cli/tests/model_fetch.rs new file mode 100644 index 00000000..78a7db7a --- /dev/null +++ b/crates/twigpine-cli/tests/model_fetch.rs @@ -0,0 +1,434 @@ +//! Integration tests for `twigpine model fetch` (KTD15): a mock Arweave +//! gateway serves anchor discovery pages and transaction bodies, a mock IPFS +//! gateway serves the manifest, reconstruction object, block map, and +//! content objects, and `fetch_model` has to rebuild byte-identical files +//! trusting nothing but the caller-supplied owner DID. + +use std::collections::HashMap; + +use serde_json::{json, Value}; +use tempfile::TempDir; +use twigpine_cli::model::{fetch_model, FetchArgs}; +use twigpine_core::cid::sha256_hex; +use twigpine_core::did::Did; +use twigpine_core::identity::Keypair; +use twigpine_core::model::manifest::{ + self, FileFormat, Manifest, ManifestFile, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{ + BlockEntry, ChunkMeta, FileEntry, Reconstruction, Term, +}; + +const COMMIT: &str = "aaaabbbbccccddddeeeeffff00001111"; +const ANCHOR_SCHEMA: &str = "gitlawb/model-release-anchor/v1"; +const BLOCK_MAP_SCHEMA: &str = "gitlawb/model-block-map/v1"; + +/// One whole release, served: a signed manifest over one git-stored file and +/// one chunked file spanning two content blocks. +struct Release { + did: Did, + signing: ed25519_dalek::SigningKey, + manifest_bytes: Vec, + rec_bytes: Vec, + block_map: Value, + /// CID -> bytes, exactly what the IPFS gateway serves. + objects: HashMap>, + /// Expected bytes per manifest path after the fetch. + files: HashMap>, +} + +fn signing_key(kp: &Keypair) -> ed25519_dalek::SigningKey { + ed25519_dalek::SigningKey::from_bytes(&kp.to_seed()) +} + +fn build_release(owner: &Keypair) -> Release { + let repo = format!("{}/my-model", owner.did()); + + let readme = b"# tiny test model\n".to_vec(); + let c1 = b"first weights chunk, pretend safetensors".to_vec(); + let c2 = b"second weights chunk follows it".to_vec(); + let c3 = b"third chunk lives in another block".to_vec(); + let model: Vec = [c1.as_slice(), &c2, &c3].concat(); + + let block1: Vec = [c1.as_slice(), &c2].concat(); + let block2: Vec = c3.clone(); + let block1_sha = sha256_hex(&block1); + let block2_sha = sha256_hex(&block2); + + let rec = Reconstruction { + schema: "gitlawb/model-reconstruction/v1".to_string(), + files: vec![FileEntry { + path: "model.safetensors".to_string(), + size: model.len() as u64, + sha256: sha256_hex(&model), + terms: vec![ + Term { + block: block1_sha.clone(), + chunk_start: 0, + chunk_end: 2, + length: (c1.len() + c2.len()) as u64, + }, + Term { + block: block2_sha.clone(), + chunk_start: 0, + chunk_end: 1, + length: c3.len() as u64, + }, + ], + }], + blocks: vec![ + BlockEntry { + sha256: block1_sha.clone(), + size: block1.len() as u64, + chunks: vec![ + ChunkMeta { + sha256: sha256_hex(&c1), + len: c1.len() as u64, + }, + ChunkMeta { + sha256: sha256_hex(&c2), + len: c2.len() as u64, + }, + ], + }, + BlockEntry { + sha256: block2_sha.clone(), + size: block2.len() as u64, + chunks: vec![ChunkMeta { + sha256: sha256_hex(&c3), + len: c3.len() as u64, + }], + }, + ], + }; + let rec_bytes = rec.to_bytes().unwrap(); + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: repo.clone(), + publisher_did: owner.did().to_string(), + license: "apache-2.0".to_string(), + parent: None, + files: vec![ + ManifestFile { + path: "README.md".to_string(), + size: readme.len() as u64, + sha256: sha256_hex(&readme), + format: FileFormat::Text, + storage: StorageKind::Git, + }, + ManifestFile { + path: "model.safetensors".to_string(), + size: model.len() as u64, + sha256: sha256_hex(&model), + format: FileFormat::Safetensors, + storage: StorageKind::Chunked, + }, + ], + reconstruction: Some(ReconstructionRef { + sha256: sha256_hex(&rec_bytes), + size: rec_bytes.len() as u64, + }), + }; + let manifest_bytes = manifest.to_bytes().unwrap(); + + let block_map = json!({ + "schema": BLOCK_MAP_SCHEMA, + "release": COMMIT, + "blocks": { + block1_sha: "bafy-block-1", + block2_sha: "bafy-block-2", + }, + "files": { + sha256_hex(&readme): "bafy-readme", + }, + }); + + let mut objects = HashMap::new(); + objects.insert("bafy-manifest".to_string(), manifest_bytes.clone()); + objects.insert("bafy-rec".to_string(), rec_bytes.clone()); + objects.insert( + "bafy-blockmap".to_string(), + serde_json::to_vec(&block_map).unwrap(), + ); + objects.insert("bafy-block-1".to_string(), block1); + objects.insert("bafy-block-2".to_string(), block2); + objects.insert("bafy-readme".to_string(), readme.clone()); + + let mut files = HashMap::new(); + files.insert("README.md".to_string(), readme); + files.insert("model.safetensors".to_string(), model); + + Release { + did: owner.did(), + signing: signing_key(owner), + manifest_bytes, + rec_bytes, + block_map, + objects, + files, + } +} + +/// The anchor body as `anchor_model_release` posts it, signed by `signing` +/// and naming `owner_did` (which a hostile anchor can lie about). +fn anchor_json( + release: &Release, + owner_did: &Did, + signing: &ed25519_dalek::SigningKey, + rec_sha: &str, +) -> Value { + json!({ + "schema": ANCHOR_SCHEMA, + "repo": format!("{}/my-model", release.did), + "owner_did": owner_did.to_string(), + "release_commit": COMMIT, + "manifest_sha256": sha256_hex(&release.manifest_bytes), + "manifest_cid": "bafy-manifest", + "reconstruction_sha256": rec_sha, + "reconstruction_cid": "bafy-rec", + "block_map_cid": "bafy-blockmap", + "claim_signature": manifest::sign(signing, &release.manifest_bytes), + "timestamp": "2026-11-19T00:00:00Z", + "node_did": "did:key:z6Mknode", + }) +} + +/// A GraphQL page holding the given (tx id, height) pairs, in edge order. +fn gql_page(edges: &[(&str, u64)]) -> Value { + let edges: Vec = edges + .iter() + .map(|(id, height)| { + json!({ + "cursor": format!("cursor-{id}"), + "node": { "id": id, "block": { "height": height } }, + }) + }) + .collect(); + json!({ + "data": { + "transactions": { + "pageInfo": { "hasNextPage": false, "endCursor": null }, + "edges": edges, + } + } + }) +} + +/// Mock both gateways on one server: `/graphql` + `/{tx}` are Arweave, +/// `/ipfs/{cid}` is IPFS. `anchors` is (tx id, body) in GraphQL edge order; +/// `objects` overrides which release objects actually get served. +async fn serve( + anchors: &[(&str, Value)], + objects: &HashMap>, +) -> mockito::ServerGuard { + let mut server = mockito::Server::new_async().await; + let edges: Vec<(&str, u64)> = anchors + .iter() + .enumerate() + .map(|(i, (id, _))| (*id, 1000 - i as u64)) + .collect(); + server + .mock("POST", "/graphql") + .with_status(200) + .with_body(gql_page(&edges).to_string()) + .create_async() + .await; + for (id, body) in anchors { + server + .mock("GET", format!("/{id}").as_str()) + .with_status(200) + .with_body(body.to_string()) + .create_async() + .await; + } + for (cid, bytes) in objects { + server + .mock("GET", format!("/ipfs/{cid}").as_str()) + .with_status(200) + .with_body(bytes.clone()) + .create_async() + .await; + } + server +} + +fn args(gateway: &str, did: &Did, output: &TempDir) -> FetchArgs { + FetchArgs { + repo: format!("{did}/my-model"), + expect_did: did.to_string(), + revision: None, + output: Some(output.path().join("out")), + arweave_gateway: gateway.to_string(), + ipfs_gateway: gateway.to_string(), + } +} + +#[tokio::test] +async fn fetch_rebuilds_git_and_chunked_files_byte_identically() { + let owner = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + let anchor = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let server = serve(&[("tx-good", anchor)], &release.objects).await; + + let out = TempDir::new().unwrap(); + let mut a = args(&server.url(), &release.did, &out); + a.revision = Some(COMMIT.to_string()); + let report = fetch_model(&a).await.unwrap(); + + assert_eq!(report.files, 2); + assert_eq!(report.release_commit, COMMIT); + assert_eq!(report.anchor_tx, "tx-good"); + for (path, want) in &release.files { + let got = std::fs::read(report.output_dir.join(path)).unwrap(); + assert_eq!(&got, want, "{path} did not rebuild byte-identically"); + } +} + +#[tokio::test] +async fn anchor_naming_a_different_owner_did_is_skipped() { + let owner = Keypair::generate(); + let attacker = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + // The attacker posts a self-signed anchor naming its own DID; fetching + // with the real owner DID must skip it and use the owner's anchor. + let forged = anchor_json(&release, &attacker.did(), &signing_key(&attacker), &rec_sha); + let good = anchor_json(&release, &release.did, &release.signing, &rec_sha); + // The forged anchor sorts newest (first edge). + let server = serve( + &[("tx-forged", forged), ("tx-good", good)], + &release.objects, + ) + .await; + + let out = TempDir::new().unwrap(); + let report = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap(); + assert_eq!(report.anchor_tx, "tx-good"); + assert!( + report.warnings.iter().any(|w| w.contains("tx-forged")), + "the skipped anchor should leave a warning: {:?}", + report.warnings + ); + for (path, want) in &release.files { + assert_eq!( + &std::fs::read(report.output_dir.join(path)).unwrap(), + want, + "{path} did not rebuild byte-identically" + ); + } +} + +#[tokio::test] +async fn anchor_with_bad_manifest_signature_is_skipped() { + let owner = Keypair::generate(); + let attacker = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + // The anchor names the real owner DID (selection passes) but signs the + // manifest with an attacker's key: verification has to reject it. + let mut forged = anchor_json(&release, &release.did, &release.signing, &rec_sha); + forged["claim_signature"] = json!(manifest::sign( + &signing_key(&attacker), + &release.manifest_bytes + )); + let good = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let server = serve( + &[("tx-badsig", forged), ("tx-good", good)], + &release.objects, + ) + .await; + + let out = TempDir::new().unwrap(); + let report = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap(); + assert_eq!(report.anchor_tx, "tx-good"); + assert!( + report + .warnings + .iter() + .any(|w| w.contains("tx-badsig") && w.contains("verification")), + "the signature failure should be reported: {:?}", + report.warnings + ); +} + +#[tokio::test] +async fn no_verifying_anchor_fails_naming_repo_and_did() { + let owner = Keypair::generate(); + let attacker = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + let forged = anchor_json(&release, &attacker.did(), &signing_key(&attacker), &rec_sha); + let server = serve(&[("tx-forged", forged)], &release.objects).await; + + let out = TempDir::new().unwrap(); + let err = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap_err(); + let msg = err.to_string(); + let repo = format!("{}/my-model", release.did); + assert!(msg.contains(&repo), "error should name the repo: {msg}"); + assert!( + msg.contains(&release.did.to_string()), + "error should name the expected DID: {msg}" + ); +} + +#[tokio::test] +async fn tampered_block_content_fails_naming_the_block() { + let owner = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + let anchor = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let mut objects = release.objects.clone(); + objects.insert("bafy-block-1".to_string(), b"tampered bytes".to_vec()); + let server = serve(&[("tx-good", anchor)], &objects).await; + + let out = TempDir::new().unwrap(); + let err = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap_err(); + let block1 = release + .block_map + .pointer("/blocks") + .and_then(|b| b.as_object()) + .and_then(|m| { + m.iter() + .find(|(_, cid)| cid.as_str() == Some("bafy-block-1")) + .map(|(sha, _)| sha.clone()) + }) + .unwrap(); + let msg = err.to_string(); + assert!( + msg.contains(&block1), + "error should name the failing block {block1}: {msg}" + ); +} + +#[tokio::test] +async fn manifest_path_traversal_is_refused() { + let owner = Keypair::generate(); + let mut release = build_release(&owner); + // Re-sign a manifest whose git file escapes the output directory. + let mut manifest: Manifest = serde_json::from_slice(&release.manifest_bytes).unwrap(); + manifest.files[0].path = "../escape.txt".to_string(); + release.manifest_bytes = manifest.to_bytes().unwrap(); + release + .objects + .insert("bafy-manifest".to_string(), release.manifest_bytes.clone()); + let rec_sha = sha256_hex(&release.rec_bytes); + let anchor = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let server = serve(&[("tx-good", anchor)], &release.objects).await; + + let out = TempDir::new().unwrap(); + let err = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap_err(); + assert!(err.to_string().contains("relative path")); + assert!(!out.path().join("escape.txt").exists()); +} From e99749194f6afbe82b501c748faf5c192ab7e845 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:21:16 -0600 Subject: [PATCH 04/14] test(node): add the model hosting end-to-end test Seed a published release against mock Kubo, Irys, and Arweave, drain durability, shut the node down, and rebuild byte-identically through fetch_model: a forged self-signed anchor is skipped and a tampered block fails by name. --- crates/twigpine-node/Cargo.toml | 8 + crates/twigpine-node/src/test_harness.rs | 142 +++++- .../twigpine-node/tests/model_hosting_e2e.rs | 479 ++++++++++++++++++ 3 files changed, 625 insertions(+), 4 deletions(-) create mode 100644 crates/twigpine-node/tests/model_hosting_e2e.rs diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index e66273f4..d592802a 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -38,6 +38,11 @@ name = "hf_api" path = "tests/hf_api.rs" required-features = ["test-harness"] +[[test]] +name = "model_hosting_e2e" +path = "tests/model_hosting_e2e.rs" +required-features = ["test-harness"] + [dependencies] twigpine-core = { path = "../twigpine-core" } async-trait = "0.1" @@ -124,3 +129,6 @@ tokio = { workspace = true, features = ["test-util"] } sqlx = { version = "0.8", features = ["postgres", "runtime-tokio-rustls", "macros", "migrate"] } reqwest = { workspace = true } hex = "0.4" +# The model-hosting e2e drives `twigpine_cli::model::fetch_model` in-process +# after the node stops serving. +twigpine-cli = { path = "../twigpine-cli" } diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index b7e7d51d..d39c68a1 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -42,6 +42,12 @@ pub struct TestNode { pub base_url: String, /// The node's own DID (for building requests that reference it). pub node_did: String, + /// The AppState the router serves from, kept so a test can drive the + /// workers the spawned serve task does not run (the durability worker + /// is never part of `axum::serve`) and inspect config/state directly. + /// The clone shares every `Arc` inside, so calls through it act on the + /// same database, block store, and shutdown signal the node does. + state: AppState, shutdown_tx: watch::Sender, repos_dir: PathBuf, /// Seeding handle over the same pool the node serves from. Kept private so @@ -156,7 +162,12 @@ fn unique_repos_dir() -> PathBuf { /// Build an [`AppState`] over the given migrated pool, mirroring /// `test_support::build_state` but with a real on-disk repository directory so /// git smart-HTTP routes can serve. P2P is always disabled. -fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppState { +fn build_state( + db: Arc, + pool: PgPool, + repos_dir: PathBuf, + extra_config_args: &[&str], +) -> AppState { let keypair = Keypair::generate(); let scan_token_key = crate::state::AppState::derive_scan_token_key(&keypair); let webhook_secret_key = crate::state::AppState::derive_webhook_secret_key(&keypair); @@ -186,7 +197,9 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS crate::blockstore::fs::FsBlockStore::new(block_dir).expect("fs block store"), )); AppState { - config: Arc::new(Config::parse_from(["twigpine-node"])), + config: Arc::new(Config::parse_from( + std::iter::once("twigpine-node").chain(extra_config_args.iter().copied()), + )), db, node_did, node_keypair: Arc::new(keypair), @@ -249,6 +262,13 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS /// connect-info so per-IP layers key on the real peer. Returns once the socket /// is bound and accepting connections. pub async fn spawn_node(pool: PgPool) -> TestNode { + spawn_node_with_args(pool, &[]).await +} + +/// [`spawn_node`] with extra clap args forwarded into `Config` (e.g. +/// `["--irys-url", url, "--ipfs-api", url]` so the durability worker talks +/// to a test's mock providers instead of the disabled defaults). +pub async fn spawn_node_with_args(pool: PgPool, extra_config_args: &[&str]) -> TestNode { let db = Arc::new(crate::db::Db::for_testing(pool.clone())); db.run_migrations() .await @@ -257,12 +277,17 @@ pub async fn spawn_node(pool: PgPool) -> TestNode { let repos_dir = unique_repos_dir(); std::fs::create_dir_all(&repos_dir).expect("create temp repos dir"); - let state = build_state(db.clone(), pool.clone(), repos_dir.clone()); + let state = build_state( + db.clone(), + pool.clone(), + repos_dir.clone(), + extra_config_args, + ); let node_did = state.node_did.to_string(); let shutdown_tx = state.shutdown_tx.clone(); let mut shutdown_rx = shutdown_tx.subscribe(); - let router = crate::server::build_router(state); + let router = crate::server::build_router(state.clone()); let listener = TcpListener::bind(("127.0.0.1", 0)) .await @@ -283,6 +308,7 @@ pub async fn spawn_node(pool: PgPool) -> TestNode { TestNode { base_url: format!("http://{addr}"), node_did, + state, shutdown_tx, repos_dir, db, @@ -404,6 +430,114 @@ impl TestNode { .expect("seed model release"); } + /// The `AppState` the spawned router serves from, so a test can drive + /// the node's own workers in-process (the durability worker is not part + /// of `axum::serve`; `twigpine_node::models::durability::durability_pass` + /// takes this state). + pub fn state(&self) -> &AppState { + &self.state + } + + /// The on-disk path `RepoStore` maps `owner_did`/`name` to, the same + /// location [`Self::seed_bare_repo`] creates. `git show`-based release + /// reads resolve through the repo row's `disk_path`, so seed the row + /// with [`Self::set_repo_disk_path`] after writing objects here. + pub fn repo_git_dir(&self, owner_did: &str, name: &str) -> PathBuf { + let slug = owner_did.replace([':', '/'], "_"); + self.repos_dir.join(&slug).join(format!("{name}.git")) + } + + /// Repoint a repo row's `disk_path` (seeded as a `/tmp` placeholder) at a + /// real on-disk git directory, so `git show`-backed paths like the model + /// durability worker's manifest/sig reads resolve. + pub async fn set_repo_disk_path(&self, repo_id: &str, path: &std::path::Path) { + sqlx::query("UPDATE repos SET disk_path = $1 WHERE id = $2") + .bind(path.to_string_lossy().to_string()) + .bind(repo_id) + .execute(self.db.pool()) + .await + .expect("set repo disk_path"); + } + + /// Seed a published release row with its real pointer fields (unlike + /// [`Self::seed_model_release`], which fills every content column with + /// placeholders). Returns the release id for block linking and + /// durability enqueueing. + pub async fn seed_published_model_release( + &self, + repo_id: &str, + commit_sha: &str, + publisher_did: &str, + manifest_sha256: &str, + reconstruction_sha256: Option<&str>, + claim_signature: &str, + ) -> i64 { + sqlx::query_scalar( + "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, created_at) + VALUES ($1,$2,'main',$3,'published',$4,$5,$6,'input','signing',\ + decode('00','hex'),$7) + RETURNING id", + ) + .bind(repo_id) + .bind(commit_sha) + .bind(publisher_did) + .bind(manifest_sha256) + .bind(reconstruction_sha256) + .bind(claim_signature) + .bind(chrono::Utc::now().to_rfc3339()) + .fetch_one(self.db.pool()) + .await + .expect("seed published model release") + } + + /// Write `bytes` into the node's block store under `sha256` (through the + /// store's own verified-put path, so a mismatching id fails the seed) + /// and record the `model_blocks` row the release-block foreign key needs. + pub async fn seed_model_block(&self, sha256: &str, bytes: &[u8]) { + let store = self + .state + .block_store + .as_ref() + .expect("test node has a block store") + .clone(); + let id = crate::blockstore::BlockId::parse(sha256).expect("valid block sha"); + let body = bytes.to_vec(); + let stream = futures::stream::once(async move { + Ok::(bytes::Bytes::from(body)) + }); + store + .put_verified(&id, Box::pin(stream), bytes.len() as u64) + .await + .expect("seed model block into store"); + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1,$2,$3) + ON CONFLICT (sha256) DO NOTHING", + ) + .bind(sha256) + .bind(bytes.len() as i64) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model_blocks row"); + } + + /// Link a seeded block sha to a release (`model_release_blocks`), the + /// table the durability enqueue expands into pin jobs. + pub async fn link_release_block(&self, release_id: i64, block_sha256: &str) { + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1,$2) + ON CONFLICT DO NOTHING", + ) + .bind(release_id) + .bind(block_sha256) + .execute(self.db.pool()) + .await + .expect("link release block"); + } + /// 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. diff --git a/crates/twigpine-node/tests/model_hosting_e2e.rs b/crates/twigpine-node/tests/model_hosting_e2e.rs new file mode 100644 index 00000000..408f6e71 --- /dev/null +++ b/crates/twigpine-node/tests/model_hosting_e2e.rs @@ -0,0 +1,479 @@ +//! Model-hosting end-to-end (KTD15): a published release must rebuild +//! byte-identically with the node gone. +//! +//! The release is seeded honestly (git objects, block store, published +//! release row) rather than driven through the upload-session/claim/verify +//! pipeline, then the node's OWN durability worker is drained in-process +//! against an in-memory Kubo (`/api/v0/add`, `/ipfs/{cid}`) and an +//! in-memory Irys+Arweave (`/upload`, `/graphql`, `/{tx}`) on the same test +//! server. After the node is shut down, `twigpine_cli::model::fetch_model` +//! rebuilds the release from the providers alone, verifying the manifest +//! signature against the owner DID the test supplies out of band. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::{Path, State}; +use axum::http::{header::CONTENT_TYPE, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::Router; +use serde_json::{json, Value}; +use tokio::net::TcpListener; + +use twigpine_cli::model::{fetch_model, FetchArgs}; +use twigpine_core::cid::sha256_hex; +use twigpine_core::identity::Keypair; +use twigpine_core::model::manifest::{ + self, FileFormat, Manifest, ManifestFile, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{ + BlockEntry, ChunkMeta, FileEntry, Reconstruction, Term, +}; +use twigpine_node::models::durability::durability_pass; +use twigpine_node::test_harness::{spawn_node_with_args, TestNode}; + +// ── fake providers ───────────────────────────────────────────────────────── + +/// One store serving three provider roles: Kubo (`POST /api/v0/add`, +/// `GET /ipfs/{cid}`), Irys (`POST /upload`), and the Arweave gateway +/// (`POST /graphql`, `GET /{tx}`). Objects are content-addressed the way the +/// node computes them, so a fetch reads back exactly what the durability +/// worker pinned. +#[derive(Clone, Default)] +struct Providers { + ipfs: Arc>>>, + arweave: Arc)>>>, +} + +fn cid_of(bytes: &[u8]) -> String { + twigpine_core::cid::Cid::from_git_object_bytes(bytes).to_string() +} + +/// Pull the single file part out of a reqwest multipart/form-data body: one +/// part, its bytes bracketed by the header separator and the closing +/// boundary marker. +fn multipart_file(content_type: &str, body: &[u8]) -> Option> { + let boundary = content_type.split("boundary=").nth(1)?.trim(); + let start = body + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4)?; + let mut marker = Vec::with_capacity(boundary.len() + 4); + marker.extend_from_slice(b"\r\n--"); + marker.extend_from_slice(boundary.as_bytes()); + let end = body[start..] + .windows(marker.len()) + .position(|w| w == marker.as_slice()) + .map(|i| start + i)?; + Some(body[start..end].to_vec()) +} + +async fn kubo_add( + State(p): State, + headers: HeaderMap, + body: Bytes, +) -> Result { + let ct = headers + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let bytes = multipart_file(ct, &body).ok_or(StatusCode::BAD_REQUEST)?; + let cid = cid_of(&bytes); + p.ipfs.lock().unwrap().insert(cid.clone(), bytes); + // Kubo answers newline-delimited JSON; only `Hash` is read. + Ok(format!("{{\"Hash\":\"{cid}\"}}\n").into_response()) +} + +async fn ipfs_get( + State(p): State, + Path(cid): Path, +) -> Result { + match p.ipfs.lock().unwrap().get(&cid) { + Some(bytes) => Ok(bytes.clone().into_response()), + None => Err(StatusCode::NOT_FOUND), + } +} + +async fn irys_upload(State(p): State, body: Bytes) -> Response { + let tx = format!("tx-{}", p.arweave.lock().unwrap().len() + 1); + p.arweave.lock().unwrap().push((tx.clone(), body.to_vec())); + json!({ "id": tx }).to_string().into_response() +} + +async fn arweave_graphql(State(p): State) -> Response { + let edges: Vec = p + .arweave + .lock() + .unwrap() + .iter() + .enumerate() + .map(|(i, (id, _))| { + json!({ + "cursor": format!("cursor-{id}"), + "node": { "id": id, "block": { "height": (i + 1) as u64 } }, + }) + }) + .collect(); + json!({ + "data": { "transactions": { + "pageInfo": { "hasNextPage": false, "endCursor": null }, + "edges": edges, + } } + }) + .to_string() + .into_response() +} + +async fn arweave_tx( + State(p): State, + Path(tx): Path, +) -> Result { + match p + .arweave + .lock() + .unwrap() + .iter() + .find(|(id, _)| *id == tx) + .map(|(_, b)| b.clone()) + { + Some(bytes) => Ok(bytes.into_response()), + None => Err(StatusCode::NOT_FOUND), + } +} + +/// Bound URL of the running fake-provider server. +async fn spawn_providers() -> (Providers, String) { + let p = Providers::default(); + let app = Router::new() + .route("/api/v0/add", post(kubo_add)) + .route("/ipfs/{cid}", get(ipfs_get)) + .route("/upload", post(irys_upload)) + .route("/graphql", post(arweave_graphql)) + .route("/{tx}", get(arweave_tx)) + .with_state(p.clone()); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let addr: SocketAddr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await }); + (p, format!("http://{addr}")) +} + +// ── release fixture ──────────────────────────────────────────────────────── + +const REPO_NAME: &str = "tiny-weights"; + +struct ReleaseContent { + commit: String, + manifest_bytes: Vec, + manifest_sha: String, + rec_bytes: Vec, + rec_sha: String, + signature: String, + /// block sha -> block bytes (data blocks only; the reconstruction + /// object is a block too but seeded separately below). + blocks: Vec<(String, Vec)>, + /// manifest path -> expected bytes. + files: Vec<(String, Vec)>, +} + +fn build_release(owner: &Keypair, repo: &str) -> ReleaseContent { + let readme = b"# tiny weights\n".to_vec(); + let c1 = b"chunk one of the weights".to_vec(); + let c2 = b"chunk two of the weights".to_vec(); + let c3 = b"chunk three lives in block two".to_vec(); + let model: Vec = [c1.as_slice(), &c2, &c3].concat(); + + let block1: Vec = [c1.as_slice(), &c2].concat(); + let block2: Vec = c3.clone(); + let b1sha = sha256_hex(&block1); + let b2sha = sha256_hex(&block2); + + let rec = Reconstruction { + schema: "gitlawb/model-reconstruction/v1".to_string(), + files: vec![FileEntry { + path: "model.safetensors".to_string(), + size: model.len() as u64, + sha256: sha256_hex(&model), + terms: vec![ + Term { + block: b1sha.clone(), + chunk_start: 0, + chunk_end: 2, + length: (c1.len() + c2.len()) as u64, + }, + Term { + block: b2sha.clone(), + chunk_start: 0, + chunk_end: 1, + length: c3.len() as u64, + }, + ], + }], + blocks: vec![ + BlockEntry { + sha256: b1sha.clone(), + size: block1.len() as u64, + chunks: vec![ + ChunkMeta { + sha256: sha256_hex(&c1), + len: c1.len() as u64, + }, + ChunkMeta { + sha256: sha256_hex(&c2), + len: c2.len() as u64, + }, + ], + }, + BlockEntry { + sha256: b2sha.clone(), + size: block2.len() as u64, + chunks: vec![ChunkMeta { + sha256: sha256_hex(&c3), + len: c3.len() as u64, + }], + }, + ], + }; + let rec_bytes = rec.to_bytes().unwrap(); + let rec_sha = sha256_hex(&rec_bytes); + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: repo.to_string(), + publisher_did: owner.did().to_string(), + license: "apache-2.0".to_string(), + parent: None, + files: vec![ + ManifestFile { + path: "README.md".to_string(), + size: readme.len() as u64, + sha256: sha256_hex(&readme), + format: FileFormat::Text, + storage: StorageKind::Git, + }, + ManifestFile { + path: "model.safetensors".to_string(), + size: model.len() as u64, + sha256: sha256_hex(&model), + format: FileFormat::Safetensors, + storage: StorageKind::Chunked, + }, + ], + reconstruction: Some(ReconstructionRef { + sha256: rec_sha.clone(), + size: rec_bytes.len() as u64, + }), + }; + let manifest_bytes = manifest.to_bytes().unwrap(); + let signing = ed25519_dalek::SigningKey::from_bytes(&owner.to_seed()); + let signature = manifest::sign(&signing, &manifest_bytes); + + ReleaseContent { + commit: String::new(), + manifest_sha: sha256_hex(&manifest_bytes), + manifest_bytes, + rec_bytes, + rec_sha, + signature, + blocks: vec![(b1sha, block1), (b2sha, block2)], + files: vec![ + ("README.md".to_string(), readme), + ("model.safetensors".to_string(), model), + ], + } +} + +/// Seed a published release honestly: git objects (manifest, signature, +/// git-stored files), block-store blocks, the published release row, and +/// release-block links. The claim/verify pipeline is bypassed; the +/// durability worker then does the real outbound work. +async fn seed_release(node: &TestNode, owner: &Keypair) -> (String, String, ReleaseContent) { + let owner_did = owner.did().to_string(); + let repo = format!("{owner_did}/{REPO_NAME}"); + let repo_id = node.seed_repo(&owner_did, REPO_NAME, true).await; + + let mut rel = build_release(owner, &repo); + let manifest_text = String::from_utf8(rel.manifest_bytes.clone()).unwrap(); + let files: Vec<(&str, &str)> = vec![ + (".twigpine/model-release.json", manifest_text.as_str()), + (".twigpine/model-release.sig", rel.signature.as_str()), + ("README.md", "# tiny weights\n"), + ]; + let oids = node.seed_bare_repo(&owner_did, REPO_NAME, &files, "sha256"); + rel.commit = oids["HEAD"].clone(); + let git_dir = node.repo_git_dir(&owner_did, REPO_NAME); + node.set_repo_disk_path(&repo_id, &git_dir).await; + + // The claim path links the reconstruction object sha alongside the data + // blocks (models::referenced_blocks), so seed the same set. + node.seed_model_block(&rel.rec_sha, &rel.rec_bytes).await; + let release_id = node + .seed_published_model_release( + &repo_id, + &rel.commit, + &owner_did, + &rel.manifest_sha, + Some(&rel.rec_sha), + &rel.signature, + ) + .await; + node.link_release_block(release_id, &rel.rec_sha).await; + for (sha, bytes) in &rel.blocks { + node.seed_model_block(sha, bytes).await; + node.link_release_block(release_id, sha).await; + } + (repo, format!("{release_id}"), rel) +} + +/// Drain the durability worker until no job is pending or failed. +async fn drain_durability(node: &TestNode) { + for _ in 0..8 { + durability_pass(node.state()).await.unwrap(); + let open: i64 = + sqlx::query_scalar("SELECT count(*) FROM model_durability_jobs WHERE state <> 'done'") + .fetch_one(node.state().db.pool()) + .await + .unwrap(); + if open == 0 { + return; + } + } + let rows: Vec<(String, String, Option)> = + sqlx::query_as("SELECT kind, state, last_error FROM model_durability_jobs ORDER BY id") + .fetch_all(node.state().db.pool()) + .await + .unwrap(); + panic!("durability jobs did not drain: {rows:?}"); +} + +fn fetch_args(repo: &str, owner_did: &str, gateway: &str, out: &std::path::Path) -> FetchArgs { + FetchArgs { + repo: repo.to_string(), + expect_did: owner_did.to_string(), + revision: None, + output: Some(out.to_path_buf()), + arweave_gateway: gateway.to_string(), + ipfs_gateway: gateway.to_string(), + } +} + +#[sqlx::test] +async fn published_release_rebuilds_without_the_node(pool: sqlx::PgPool) { + let (providers, gateway) = spawn_providers().await; + let node = spawn_node_with_args( + pool, + &[ + "--model-hosting-enabled", + "--ipfs-api", + gateway.as_str(), + "--irys-url", + gateway.as_str(), + ], + ) + .await; + + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let (repo, _release_id, rel) = seed_release(&node, &owner).await; + drain_durability(&node).await; + + // The node's own work is done; the rest of this test must not consult it. + node.shutdown().await; + + let out = tempfile::tempdir().unwrap(); + let report = fetch_model(&fetch_args( + &repo, + &owner_did, + &gateway, + &out.path().join("one"), + )) + .await + .unwrap(); + assert_eq!(report.files, rel.files.len()); + assert_eq!(report.release_commit, rel.commit); + assert_eq!(report.anchor_tx, "tx-1"); + for (path, want) in &rel.files { + let got = std::fs::read(report.output_dir.join(path)).unwrap(); + assert_eq!(&got, want, "{path} did not rebuild byte-identically"); + } + + // A second self-signed anchor by an attacker keypair names its own DID: + // it sorts newest but must be skipped when fetching with the real owner + // DID (the anchor's own DID fields are never the verifying key). + let attacker = Keypair::generate(); + let forged_manifest = Manifest { + publisher_did: attacker.did().to_string(), + ..serde_json::from_slice::(&rel.manifest_bytes).unwrap() + }; + let forged_bytes = forged_manifest.to_bytes().unwrap(); + let forged_sig = manifest::sign( + &ed25519_dalek::SigningKey::from_bytes(&attacker.to_seed()), + &forged_bytes, + ); + let forged_anchor = json!({ + "schema": "gitlawb/model-release-anchor/v1", + "repo": repo, + "owner_did": attacker.did().to_string(), + "release_commit": rel.commit, + "manifest_sha256": sha256_hex(&forged_bytes), + "manifest_cid": cid_of(&forged_bytes), + "reconstruction_sha256": rel.rec_sha, + "reconstruction_cid": cid_of(&rel.rec_bytes), + "block_map_cid": "bafy-anything", + "claim_signature": forged_sig, + "timestamp": "2026-11-19T00:00:00Z", + "node_did": "did:key:z6Mkattacker-node", + }); + providers + .ipfs + .lock() + .unwrap() + .insert(cid_of(&forged_bytes), forged_bytes); + reqwest::Client::new() + .post(format!("{gateway}/upload")) + .body(forged_anchor.to_string()) + .send() + .await + .unwrap(); + + let report = fetch_model(&fetch_args( + &repo, + &owner_did, + &gateway, + &out.path().join("two"), + )) + .await + .unwrap(); + assert_eq!( + report.anchor_tx, "tx-1", + "the newer self-signed anchor must be skipped for the real one" + ); + assert!( + report.warnings.iter().any(|w| w.contains("tx-2")), + "the skipped forged anchor should leave a warning: {:?}", + report.warnings + ); + + // Tampered provider bytes must fail the fetch naming the block sha. + let (block_sha, block_bytes) = &rel.blocks[0]; + let block_cid = cid_of(block_bytes); + providers + .ipfs + .lock() + .unwrap() + .insert(block_cid, b"tampered block bytes".to_vec()); + let err = fetch_model(&fetch_args( + &repo, + &owner_did, + &gateway, + &out.path().join("three"), + )) + .await + .unwrap_err(); + assert!( + err.to_string().contains(block_sha), + "the tamper error should name block {block_sha}: {err}" + ); +} From 1847bfe7367fc5e687ea0ce67630cb2633bcf4c4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:21:16 -0600 Subject: [PATCH 05/14] docs: document model hosting Operator enablement, quotas, durability tiers, the HF read surface, independent fetch, and the smoke check. README and the run/storage docs point at the new page. --- README.md | 2 +- docs/MODEL-HOSTING.md | 130 ++++++++++++++++++++++++++++++++++++ docs/RUN-A-NODE.md | 15 +++-- docs/STORAGE-AND-PINNING.md | 11 +++ 4 files changed, 152 insertions(+), 6 deletions(-) create mode 100644 docs/MODEL-HOSTING.md diff --git a/README.md b/README.md index 16508f96..01b3b6fb 100644 --- a/README.md +++ b/README.md @@ -431,7 +431,7 @@ Important node settings: | `TWIGPINE_AUTO_SYNC` | Enable automatic sync from known peers. | | `TWIGPINE_RECONCILIATION_SWEEP` | Enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend (IPFS, Pinata, or both). Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. | | `TWIGPINE_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. | -| `TWIGPINE_MODEL_HOSTING_ENABLED` | Enable experimental model hosting (signed releases, block storage). Off by default; see `docs/RUN-A-NODE.md` for the quota and block-store knobs. | +| `TWIGPINE_MODEL_HOSTING_ENABLED` | Enable model hosting (signed releases, block storage, HF-compatible reads, independent fetch). Off by default; see [docs/MODEL-HOSTING.md](docs/MODEL-HOSTING.md) for the quota, block-store, and durability knobs. | | `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | | `TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | | `TWIGPINE_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | diff --git a/docs/MODEL-HOSTING.md b/docs/MODEL-HOSTING.md new file mode 100644 index 00000000..a7f674f0 --- /dev/null +++ b/docs/MODEL-HOSTING.md @@ -0,0 +1,130 @@ +# Model hosting + +A node can host open-weight models: a model is a **fully public** repository +whose releases are signed manifests, with large files stored as +content-addressed blocks outside git. This page covers what ships today: +publishing and reading through the node, and independent consumer fetch from +Arweave and IPFS with no node in the loop. + +## What a release is + +`twigpine model publish` runs inside a local clone and: + +1. Classifies files by the chunking threshold (10 MiB): smaller files stay + ordinary git blobs, larger ones are packed into content blocks (up to + 128 MiB each) uploaded out of band under an upload session. +2. Commits `.twigpine/model-release.json` (the signed manifest) and + `.twigpine/model-release.sig` (a detached Ed25519 signature over the exact + manifest bytes), pushes, and posts a release claim to the node. +3. The node verifies the claim, marks the release `published`, and the + durability worker then: + - pins every content block, the reconstruction object, the manifest, each + git-stored file, and a sha256-to-CID block map to the configured IPFS + tiers, and + - posts one compact anchor record to Arweave via Irys, carrying the + manifest CID + sha256, reconstruction and block-map pointers, and the + publisher's claim signature. + +## Enabling it (operator) + +Model hosting is off by default and the node behaves exactly as before +without it. + +| Env var | Default | Meaning | +|---------|---------|---------| +| `TWIGPINE_MODEL_HOSTING_ENABLED` | `false` | Master switch; mounts the session/block/claim/read routes. | +| `TWIGPINE_MODEL_QUOTA_BYTES` | `274877906944` (256 GiB) | Per-identity quota for claimed blocks. | +| `TWIGPINE_MODEL_NODE_QUOTA_BYTES` | `1099511627776` (1 TiB) | Total model bytes the node will hold, open sessions included. | +| `TWIGPINE_MODEL_SESSION_TTL_SECS` | `43200` | Base upload-session lifetime; each accepted block renews it. | +| `TWIGPINE_MODEL_UNCLAIMED_TTL_SECS` | `86400` | Grace before blocks no release references are swept. Must exceed the session TTL. | +| `TWIGPINE_MODEL_MAX_SESSION_BYTES` | unset (uses the identity quota) | Optional cap on one identity's open sessions. | +| `TWIGPINE_BLOCKSTORE_DIR` | `./data/model-blocks` | Where blocks live with the filesystem backend. | +| `TWIGPINE_BLOCKSTORE_S3_BUCKET` | unset | Store blocks in S3 instead; reuses the `AWS_*` endpoint and credentials of the Tigris backend. | + +## Off-node durability (the tiers that matter) + +A published release only survives the node disappearing if its objects are +pinned somewhere off the node. The durability worker writes to every +configured tier: + +- **Hot tier**: local Kubo daemon, `TWIGPINE_IPFS_API` (e.g. + `http://127.0.0.1:5001`). Good for serving; a node-local daemon alone does + not survive the host. +- **Warm tier**: Pinata or another pinning service, `TWIGPINE_PINATA_JWT` + (and `TWIGPINE_PINATA_UPLOAD_URL`). This is what puts the objects on the + public IPFS network where an independent consumer's gateway can read them. +- **Anchor tier**: Arweave via Irys, `TWIGPINE_IRYS_URL` + (`https://devnet.irys.xyz` for devnet). The anchor is the discovery record + `model fetch` searches for; without it there is nothing to find. + +For a release you expect consumers to fetch without you, configure a warm +tier AND Irys. With neither, the release still serves through the node's own +APIs but nothing leaves the box. + +Publishing is permanent: the anchor and pins are outbound records that +outlive the node and cannot be taken back. `twigpine model publish` asks for +confirmation before it claims. + +## Reading + +### HF-compatible API + +A `huggingface_hub` client pointed at the node reads a published release like +an HF repo. The repo id is `/` (the owner segment carries +the DID literally, colons and all): + +```python +from huggingface_hub import snapshot_download +# HF_ENDPOINT=https:///hf +snapshot_download(repo_id="did:key:z6Mk.../my-model") +``` + +Mounted routes: `GET /hf/api/models/{owner}/{repo}`, +`.../revision/{rev}`, `.../tree/{rev}[/{path}]`, `.../refs`, and +`/hf/{owner}/{repo}/resolve/{rev}/{path}` (resumable, range-aware). +Anonymous reads work on fully public repos; HF bearer tokens carry no +signature and read as anonymous. + +One size limit to know: huggingface_hub 2.x refuses plain downloads of a +single file over 50 GiB, so `model publish` warns when a chunked file passes +that line. + +### Independent fetch (no node) + +`twigpine model fetch` rebuilds a release from Arweave and IPFS alone: + +``` +twigpine model fetch / --expect-did \ + [--revision ] [--output ] \ + [--arweave-gateway https://arweave.net] [--ipfs-gateway https://dweb.link] +``` + +The fetch searches the Arweave gateway's GraphQL for release anchors tagged +to the repo (newest first), then for each candidate downloads the manifest +and verifies the embedded signature **against the DID you pass in +`--expect-did`**, never a DID read out of the anchor, which is untrusted +text anyone can post. Anchors that fail selection (wrong repo, wrong owner +DID, wrong commit) or verification are skipped with a warning; the first +candidate whose manifest verifies is the release. Every object after that +(manifest, reconstruction, block map, content blocks, git files) is fetched +by CID and sha256-checked against the signed manifest's claims; a hash +failure stops the fetch naming the object. + +The result is a directory laid out by manifest path (an HF-snapshot-like +tree), default `-` under the current directory. The only +thing you must trust out of band is the publisher's DID; everything else is +verified content. + +## Smoke check + +With a node running the feature and both providers configured: + +1. `twigpine model publish` from a small repo with one file over 10 MiB; + confirm and wait for the release to reach `published` + (`GET /api/v1/repos/{owner}/{repo}/models/releases/{commit}`). +2. Confirm the durability jobs drained: the release's pin rows land on the + configured IPFS tiers and one anchor tx posts to Irys. +3. `HF_ENDPOINT=http://localhost:PORT/hf python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='/')"`. +4. Stop the node, then + `twigpine model fetch / --expect-did --output /tmp/m` + and diff the result against the original files. diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 60792c8e..47443506 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -282,12 +282,16 @@ short lifetimes reissued often are safer than one long-lived grant. --- -## Model hosting (experimental) +## Model hosting -Off by default and not yet usable end to end: the node ships the storage and -schema only, with no publish or read routes mounted yet. When it lands, a model -is a public repo whose releases are signed manifests, and weights are stored as -content-addressed blocks outside git. +A node can host open-weight models: a model is a fully public repo whose +releases are signed manifests, with weights stored as content-addressed +blocks outside git. Off by default. Enabling it also mounts an +HF-compatible read surface and, once a release's durability jobs pin and +anchor it, independent consumer fetch from Arweave and IPFS with no node in +the loop. The full operator and consumer guide, including the warm +tier/Irys configuration off-node fetch needs, is +[docs/MODEL-HOSTING.md](MODEL-HOSTING.md); the knob summary: - `TWIGPINE_MODEL_HOSTING_ENABLED=false` - the master switch. - `TWIGPINE_MODEL_QUOTA_BYTES` - per-identity quota for claimed blocks (default 256 GiB). @@ -297,6 +301,7 @@ content-addressed blocks outside git. - `TWIGPINE_MODEL_MAX_SESSION_BYTES` - optional cap on one identity's open sessions (defaults to the quota). - `TWIGPINE_BLOCKSTORE_DIR` - where blocks live on disk (default `./data/model-blocks`). - `TWIGPINE_BLOCKSTORE_S3_BUCKET` - set to store blocks in S3 instead; reuses the same `AWS_*` endpoint and credentials as the Tigris repo backend. +- `TWIGPINE_IRYS_URL` - Irys endpoint for the Arweave release anchor consumers discover with `twigpine model fetch` (empty disables anchoring; `https://devnet.irys.xyz` for devnet). --- diff --git a/docs/STORAGE-AND-PINNING.md b/docs/STORAGE-AND-PINNING.md index df9ede4e..9be9309d 100644 --- a/docs/STORAGE-AND-PINNING.md +++ b/docs/STORAGE-AND-PINNING.md @@ -117,8 +117,19 @@ successful upload, can still cause a repeat upload attempt. > Filecoin deals or self-hosted clusters without touching push logic) is tracked > separately. +## Model releases + +Published model releases reuse the same two tiers: the model durability +worker pins each release's content blocks, manifest, reconstruction object, +git-stored files, and block map through `pin_model_object` on the configured +sinks (`crates/twigpine-node/src/models/durability.rs`), then posts one +Arweave anchor through Irys. A warm tier plus Irys is what makes +`twigpine model fetch` work with the node gone; see +[MODEL-HOSTING.md](MODEL-HOSTING.md). + ## See also - [RUN-A-NODE.md](RUN-A-NODE.md): provisioning and running a node +- [MODEL-HOSTING.md](MODEL-HOSTING.md): model release publishing, reading, and independent fetch - `crates/twigpine-node/src/ipfs_pin.rs`: hot-tier implementation - `crates/twigpine-node/src/pinata.rs`: warm-tier implementation From 9431675878a715798598967007d9e2aca3ad35aa Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:33:59 -0600 Subject: [PATCH 06/14] refactor(node): simplify the model read and durability surface Review pass on the PR3 diff: - Fetch the repo row once per durability job and share it with the publicity gate, git blob reads, and the anchor post instead of re-fetching it per call. - still_publishable now delegates to require_fully_public so the canonical publicity predicate (public, no rules, canonical row) has one definition. - Merge the near-identical durability count queries and take borrowed job tuples so enqueue stops allocating String for static kind names. - Centralize the release manifest and signature paths in models:: so the claim reader, HF surface, and durability jobs share them. - Drop the pin_model_object pass-through; callers use pin_git_object. - Fix a panic: the fetch output dir sliced untrusted anchor text by bytes; it now truncates by chars so a multi-byte boundary is safe. - Emit HF's real LFS pointerSize (the pointer file size, not the object size) in tree entries. - Coverage: /tree/{rev}/{path} slash-boundary filtering, all six HF routes denying private and visibility-ruled repos for anon and signed stranger, pickle unsafe markers on model-info siblings, and lastModified proven to report published_at rather than created_at. - Docs: the HF repo id uses the bare DID key (huggingface_hub rejects the did:key: colons client-side), the at-or-above threshold wording, current huggingface_hub wording, and the HF read/download knobs in .env.example and MODEL-HOSTING.md. --- .env.example | 9 +- crates/twigpine-cli/src/main.rs | 2 +- crates/twigpine-cli/src/model.rs | 20 +-- crates/twigpine-node/src/api/hf.rs | 11 +- crates/twigpine-node/src/db/model_queries.rs | 57 +++---- crates/twigpine-node/src/ipfs_pin.rs | 18 --- crates/twigpine-node/src/lib.rs | 12 +- crates/twigpine-node/src/models/claim.rs | 13 +- crates/twigpine-node/src/models/durability.rs | 119 +++++++------- crates/twigpine-node/src/models/mod.rs | 7 + crates/twigpine-node/src/models/verify.rs | 2 - crates/twigpine-node/tests/hf_api.rs | 151 +++++++++++++++++- docs/MODEL-HOSTING.md | 24 +-- 13 files changed, 287 insertions(+), 158 deletions(-) diff --git a/.env.example b/.env.example index 67d62708..ef53bd9b 100644 --- a/.env.example +++ b/.env.example @@ -467,8 +467,9 @@ ICAPTCHA_URL=https://icaptcha.gitlawb.com # ── Model hosting (experimental, off by default) ────────────────────────── # Signed model releases on public repos, with weights stored as -# content-addressed blocks outside git. Off by default; not yet usable end to -# end: this ships the storage and schema only, no publish or read routes yet. +# content-addressed blocks outside git. Enables the publish routes, the +# HF-compatible read surface under /hf, and the IPFS/Arweave durability +# worker. See docs/MODEL-HOSTING.md. TWIGPINE_MODEL_HOSTING_ENABLED=false # Per-identity quota for claimed model blocks, in bytes (default 256 GiB). TWIGPINE_MODEL_QUOTA_BYTES=274877906944 @@ -478,6 +479,10 @@ TWIGPINE_MODEL_NODE_QUOTA_BYTES=1099511627776 TWIGPINE_MODEL_UNCLAIMED_TTL_SECS=86400 # Base lifetime of an upload session; each accepted block renews it. TWIGPINE_MODEL_SESSION_TTL_SECS=43200 +# Per-IP request limit for the /hf read surface, per hour. +TWIGPINE_HF_READ_RATE_LIMIT=600 +# Concurrent model downloads the resolve route will stream. +TWIGPINE_MODEL_DOWNLOAD_PERMITS=16 # Optional cap on the sum of one identity's open upload sessions, in bytes. # Unset means "use TWIGPINE_MODEL_QUOTA_BYTES". #TWIGPINE_MODEL_MAX_SESSION_BYTES= diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index e362ff17..74303179 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -113,7 +113,7 @@ enum Commands { /// Print your current identity (DID) and optional node info Whoami(whoami::WhoamiArgs), - /// Publish open-weight model releases + /// Publish and fetch open-weight model releases Model { #[command(subcommand)] cmd: model::ModelCmd, diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index d7e1fb6a..bd67b158 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -350,8 +350,6 @@ fn tracked_paths(root: &Path) -> Result> { Ok(out) } -/// 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 { @@ -385,6 +383,8 @@ fn unescape_gitignore_path(line: &str) -> String { 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(); @@ -1269,8 +1269,8 @@ async fn discover_release_anchors( /// One anchor candidate through its trust gates: fetch the body, parse the /// anchor JSON, then fetch the manifest and verify it against the expected -/// DID. Returns `Ok(Some(..))` only when the manifest verifies; every failure -/// is a warning plus `Ok(None)` so the next candidate gets tried. +/// DID. Returns `Some(..)` only when the manifest verifies; every failure is +/// a warning plus `None` so the next candidate gets tried. async fn verify_candidate( net: &Net<'_>, tx_id: &str, @@ -1457,8 +1457,8 @@ fn chunk_offsets(block: &BlockEntry) -> Vec { /// Rebuild one chunked file into `out_path` from its terms, streaming to /// disk. Per-chunk sha256s are verified as slices are consumed and the -/// whole-file digest against the manifest at the end, so at most a handful -/// of blocks are ever resident. +/// whole-file digest is checked against the manifest at the end, so at most +/// a handful of blocks are ever resident. async fn rebuild_chunked( source: &mut BlockSource<'_>, rec: &Reconstruction, @@ -1664,10 +1664,10 @@ pub async fn fetch_model(args: &FetchArgs) -> Result { } let out_dir = args.output.clone().unwrap_or_else(|| { - PathBuf::from(format!( - "{name}-{}", - &anchor.release_commit[..anchor.release_commit.len().min(8)] - )) + // `release_commit` is untrusted anchor text: truncate by chars so a + // multi-byte boundary cannot panic, like a raw byte slice would. + let short: String = anchor.release_commit.chars().take(8).collect(); + PathBuf::from(format!("{name}-{short}")) }); if out_dir.exists() { let non_empty = out_dir diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs index 56decd1e..15630f69 100644 --- a/crates/twigpine-node/src/api/hf.rs +++ b/crates/twigpine-node/src/api/hf.rs @@ -42,7 +42,7 @@ use crate::state::AppState; /// Manifest and signature paths inside the release commit (the same paths /// `models::claim` reads at claim time). -const MANIFEST_PATH: &str = ".twigpine/model-release.json"; +use crate::models::RELEASE_MANIFEST_PATH as MANIFEST_PATH; const X_REPO_COMMIT: HeaderName = HeaderName::from_static("x-repo-commit"); const X_ERROR_CODE: HeaderName = HeaderName::from_static("x-error-code"); @@ -225,7 +225,9 @@ fn tree_entries(manifest: &Manifest, prefix: &str) -> Vec { e["lfs"] = json!({ "oid": f.sha256, "size": f.size, - "pointerSize": f.size, + // HF's pointerSize is the pointer file's byte size + // (a fixed ~130), not the object's. + "pointerSize": 130, }); } if f.format == FileFormat::Pickle { @@ -346,8 +348,9 @@ pub async fn hf_refs( } /// `HEAD|GET /hf/{owner}/{repo}/resolve/{rev}/{*path}`, byte-exact, -/// resumable file bytes (KTD9). `X-Repo-Commit` is on every answer, -/// including `EntryNotFound`, so a client can always pin what it read. +/// resumable file bytes (KTD9). `X-Repo-Commit` rides every answer that +/// resolved a release (200/206/304/416/`EntryNotFound`), so a client can +/// always pin what it read. pub async fn hf_resolve( State(state): State, Path((owner, name, rev, path)): Path<(String, String, String, String)>, diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c478f529..c8ce6856 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -833,22 +833,6 @@ impl Db { Ok(row.map(Into::into)) } - /// The reconstruction object's sha for a release, when the manifest - /// declared one (all-git releases have none). `ModelRelease` does not - /// carry the column; the durability enqueue needs it directly. - pub async fn model_release_reconstruction_sha( - &self, - release_id: i64, - ) -> Result> { - Ok( - sqlx::query_scalar("SELECT reconstruction_sha256 FROM model_releases WHERE id = $1") - .bind(release_id) - .fetch_optional(&self.pool) - .await? - .flatten(), - ) - } - /// Every block a release references, in stable order. The /// `pin_block` job material and (after the pins land) the block-CID /// map's key set. @@ -871,13 +855,13 @@ impl Db { pub async fn model_durability_enqueue( &self, release_id: i64, - jobs: &[(String, String)], + jobs: &[(&str, &str)], ) -> Result { if jobs.is_empty() { return Ok(0); } - let kinds: Vec<&str> = jobs.iter().map(|(k, _)| k.as_str()).collect(); - let keys: Vec<&str> = jobs.iter().map(|(_, o)| o.as_str()).collect(); + let kinds: Vec<&str> = jobs.iter().map(|(k, _)| *k).collect(); + let keys: Vec<&str> = jobs.iter().map(|(_, o)| *o).collect(); let now = ts_now(); let inserted = sqlx::query( "INSERT INTO model_durability_jobs @@ -1000,19 +984,20 @@ impl Db { .rows_affected()) } - /// (pending, failed) counts for a release's jobs of `kind`, the - /// `pin_block_map` gate (`pin_block`) and the anchor gate. - pub async fn model_durability_kind_counts( + /// (pending, failed) counts for a release's jobs matching `pred` + /// (`kind = $2` or `kind <> $2`), the job-gate inputs. + async fn model_durability_counts( &self, release_id: i64, kind: &str, + pred: &str, ) -> Result<(i64, i64)> { - let (pending, failed): (Option, Option) = sqlx::query_as( + let (pending, failed): (Option, Option) = sqlx::query_as(&format!( "SELECT COUNT(*) FILTER (WHERE state = 'pending'), COUNT(*) FILTER (WHERE state = 'failed') FROM model_durability_jobs - WHERE release_id = $1 AND kind = $2", - ) + WHERE release_id = $1 AND kind {pred} $2", + )) .bind(release_id) .bind(kind) .fetch_one(&self.pool) @@ -1020,6 +1005,16 @@ impl Db { Ok((pending.unwrap_or(0), failed.unwrap_or(0))) } + /// (pending, failed) counts for a release's jobs of `kind`, the + /// `pin_block_map` gate (`pin_block`) and the anchor gate. + pub async fn model_durability_kind_counts( + &self, + release_id: i64, + kind: &str, + ) -> Result<(i64, i64)> { + self.model_durability_counts(release_id, kind, "=").await + } + /// (pending, failed) counts for a release's jobs of every kind EXCEPT /// `kind`, the anchor gate ("only after all pin jobs are done"). pub async fn model_durability_other_counts( @@ -1027,17 +1022,7 @@ impl Db { release_id: i64, kind: &str, ) -> Result<(i64, i64)> { - let (pending, failed): (Option, Option) = sqlx::query_as( - "SELECT COUNT(*) FILTER (WHERE state = 'pending'), - COUNT(*) FILTER (WHERE state = 'failed') - FROM model_durability_jobs - WHERE release_id = $1 AND kind <> $2", - ) - .bind(release_id) - .bind(kind) - .fetch_one(&self.pool) - .await?; - Ok((pending.unwrap_or(0), failed.unwrap_or(0))) + self.model_durability_counts(release_id, kind, "<>").await } /// (object_key, provider_cid) pairs for done jobs of `kind`, keyed so diff --git a/crates/twigpine-node/src/ipfs_pin.rs b/crates/twigpine-node/src/ipfs_pin.rs index 848fecb9..8490baaa 100644 --- a/crates/twigpine-node/src/ipfs_pin.rs +++ b/crates/twigpine-node/src/ipfs_pin.rs @@ -1707,24 +1707,6 @@ pub async fn pin_git_object( Ok(cid) } -/// Pin one model content object's bytes on the local Kubo node. -/// -/// This is [`pin_git_object`] under a name that says what the durability -/// worker is doing: the bytes are arbitrary content, the add goes in with -/// `raw-leaves=true&cid-version=1&pin=true`, and the returned `Hash` is a -/// PROVIDER CID recorded next to (never instead of) the sha256 that keys -/// the object. For objects over Kubo's chunk threshold the returned CID is -/// the dag-pb root rather than the raw-leaf CID the small-object case -/// computes locally. -pub async fn pin_model_object( - ipfs_api: &str, - sha256_hex: &str, - data: &[u8], - request_timeout: Option, -) -> Result { - pin_git_object(ipfs_api, sha256_hex, data, request_timeout).await -} - /// Fetch raw bytes for a CID from the local Kubo node (`/api/v0/cat`). pub async fn cat(ipfs_api: &str, cid: &str) -> Result> { if ipfs_api.is_empty() { diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 6a2a133f..52fd7070 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -928,15 +928,11 @@ pub async fn run() -> Result<()> { // 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()))); - model_workers.push(tokio::spawn(models::durability::run_durability_worker( - state.clone(), - ))); + let _model_verify_worker = tokio::spawn(models::verify::run_verify_worker(state.clone())); + let _model_sweep_worker = tokio::spawn(models::sweep::run_sweep_worker(state.clone())); + let _model_durability_worker = + tokio::spawn(models::durability::run_durability_worker(state.clone())); } // `into_make_service_with_connect_info` exposes the socket peer address as diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 1d06e483..4e31f167 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -85,10 +85,15 @@ pub(crate) async fn read_verified_manifest( 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") + let manifest_bytes = git_show( + git_bin, + disk_path, + commit, + crate::models::RELEASE_MANIFEST_PATH, + ) + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.json"))?; + let sig_text = git_show(git_bin, disk_path, commit, crate::models::RELEASE_SIG_PATH) .await? .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; let sig_text = diff --git a/crates/twigpine-node/src/models/durability.rs b/crates/twigpine-node/src/models/durability.rs index d953e0ba..93a9ad1a 100644 --- a/crates/twigpine-node/src/models/durability.rs +++ b/crates/twigpine-node/src/models/durability.rs @@ -22,6 +22,7 @@ use std::time::Duration; use crate::db::model_queries::DurabilityJob; +use crate::db::RepoRecord; use crate::error::AppError; use crate::ipfs_pin::PolicyFence; use crate::models::claim::git_show; @@ -43,8 +44,7 @@ const BACKFILL_BATCH: i64 = 64; /// enough that an empty drain is cheap. const TICK_SECS: u64 = 30; -const MANIFEST_PATH: &str = ".twigpine/model-release.json"; -const SIG_PATH: &str = ".twigpine/model-release.sig"; +use crate::models::{RELEASE_MANIFEST_PATH as MANIFEST_PATH, RELEASE_SIG_PATH as SIG_PATH}; /// Enqueue the full job set for one published release. Idempotent: the /// `(release, kind, object)` unique key makes a second call insert @@ -57,25 +57,20 @@ pub async fn enqueue_for_release(state: &AppState, release_id: i64) -> Result<() if release.state != "published" { return Ok(()); } - let mut jobs: Vec<(String, String)> = state - .db - .model_release_blocks(release_id) - .await? - .into_iter() - .map(|sha| (KIND_BLOCK.to_string(), sha)) + let block_shas = state.db.model_release_blocks(release_id).await?; + let mut jobs: Vec<(&str, &str)> = block_shas + .iter() + .map(|sha| (KIND_BLOCK, sha.as_str())) .collect(); - jobs.push((KIND_MANIFEST.to_string(), release.manifest_sha256.clone())); - if let Some(rec_sha) = state - .db - .model_release_reconstruction_sha(release_id) - .await? - { - jobs.push((KIND_RECONSTRUCTION.to_string(), rec_sha)); + jobs.push((KIND_MANIFEST, release.manifest_sha256.as_str())); + let rec_sha = state.db.model_reconstruction_sha(release_id).await?; + if let Some(sha) = rec_sha.as_deref() { + jobs.push((KIND_RECONSTRUCTION, sha)); } // Release-level jobs key on the commit: it scopes the row, nothing // resolves object bytes through it. - jobs.push((KIND_BLOCK_MAP.to_string(), release.commit_sha.clone())); - jobs.push((KIND_ANCHOR.to_string(), release.commit_sha)); + jobs.push((KIND_BLOCK_MAP, release.commit_sha.as_str())); + jobs.push((KIND_ANCHOR, release.commit_sha.as_str())); state.db.model_durability_enqueue(release_id, &jobs).await?; Ok(()) } @@ -120,20 +115,15 @@ pub async fn run_durability_worker(state: AppState) { } /// Whether the repo a release belongs to may still be published outbound: -/// fully public, no visibility rules, no mirror row, not quarantined. A -/// `false` means every pending job for the release stops and the anchor -/// must never post (KTD10: pins stop when publicity changes). -async fn still_publishable(state: &AppState, repo_id: &str) -> Result { - let Some(record) = state.db.get_repo_by_id(repo_id).await? else { - return Ok(false); - }; - if !record.is_public || record.id.contains('/') { - return Ok(false); - } +/// fully public on the canonical predicate, and not quarantined. A `false` +/// means every pending job for the release stops and the anchor must never +/// post (KTD10: pins stop when publicity changes). +async fn still_publishable(state: &AppState, record: &RepoRecord) -> Result { if state.db.is_repo_quarantined(&record.id).await? { return Ok(false); } - Ok(state.db.list_visibility_rules(&record.id).await?.is_empty()) + let rules = state.db.list_visibility_rules(&record.id).await?; + Ok(crate::api::models::require_fully_public(record, &rules).is_ok()) } /// Process one pending job. Errors are recorded (attempts bumped, failed @@ -199,7 +189,14 @@ async fn process_job(state: &AppState, job: &DurabilityJob) -> Result<(), AppErr _ => {} } - if !still_publishable(state, &release.repo_id).await? { + let Some(record) = state.db.get_repo_by_id(&release.repo_id).await? else { + state + .db + .model_durability_mark_failed(job.id, "repo row is gone") + .await?; + return Ok(()); + }; + if !still_publishable(state, &record).await? { state .db .model_durability_fail_pending(job.release_id, "repository is no longer fully public") @@ -212,7 +209,7 @@ async fn process_job(state: &AppState, job: &DurabilityJob) -> Result<(), AppErr // assuming the bump was publicity-shaped. let fence = PolicyFence::capture(&state.db, &release.repo_id).await; - let result = execute_job(state, &release, job, fence.as_ref()).await; + let result = execute_job(state, &release, job, fence.as_ref(), &record).await; match result { Ok(JobOutcome::Deferred) => Ok(()), Ok(JobOutcome::Done(cid)) => { @@ -243,6 +240,15 @@ enum JobOutcome { Done(String), } +/// The policy epoch is still good; a stale one defers the job so the +/// publicity check re-runs before the provider call. +async fn fence_current(fence: Option<&PolicyFence>) -> bool { + match fence { + Some(f) => f.is_current().await, + None => true, + } +} + /// Run the job's own work. `fence` is the captured policy epoch, checked /// right before each provider call. async fn execute_job( @@ -250,6 +256,7 @@ async fn execute_job( release: &crate::models::ReleaseRow, job: &DurabilityJob, fence: Option<&PolicyFence>, + record: &RepoRecord, ) -> Result { match job.kind.as_str() { KIND_BLOCK | KIND_RECONSTRUCTION => { @@ -275,7 +282,7 @@ async fn execute_job( pin_bytes(state, &job.object_key, &bytes, fence).await } KIND_MANIFEST => { - let bytes = git_bytes(state, release, MANIFEST_PATH).await?; + let bytes = git_bytes(&state.git_bin, record, release, MANIFEST_PATH).await?; pin_bytes(state, &job.object_key, &bytes, fence).await } KIND_BLOCK_MAP => { @@ -291,7 +298,7 @@ async fn execute_job( // nothing else ever pins them. Pin each here and index it by // its manifest sha256, or a fetch without this node can rebuild // every chunked file and still miss config.json. - let manifest_bytes = git_bytes(state, release, MANIFEST_PATH).await?; + let manifest_bytes = git_bytes(&state.git_bin, record, release, MANIFEST_PATH).await?; let manifest = twigpine_core::model::manifest::Manifest::parse(&manifest_bytes) .map_err(|e| AppError::Internal(anyhow::anyhow!("manifest parse: {e}")))?; let mut files = serde_json::Map::new(); @@ -300,7 +307,7 @@ async fn execute_job( .iter() .filter(|f| f.storage == twigpine_core::model::manifest::StorageKind::Git) { - let data = git_bytes(state, release, &file.path).await?; + let data = git_bytes(&state.git_bin, record, release, &file.path).await?; match pin_bytes(state, &file.sha256, &data, fence).await? { JobOutcome::Done(cid) => { files.insert(file.sha256.clone(), serde_json::Value::String(cid)); @@ -318,7 +325,7 @@ async fn execute_job( .map_err(|e| AppError::Internal(anyhow::anyhow!("block map serialize: {e}")))?; pin_bytes(state, &job.object_key, &bytes, fence).await } - KIND_ANCHOR => post_anchor(state, release, job, fence).await, + KIND_ANCHOR => post_anchor(state, release, job, fence, record).await, other => Err(AppError::Internal(anyhow::anyhow!( "unknown durability job kind {other}" ))), @@ -329,17 +336,13 @@ async fn execute_job( /// object is a job error like a missing store block: retry until the /// attempt budget fails it. async fn git_bytes( - state: &AppState, + git_bin: &str, + record: &RepoRecord, release: &crate::models::ReleaseRow, path: &str, ) -> Result, AppError> { - let record = state - .db - .get_repo_by_id(&release.repo_id) - .await? - .ok_or_else(|| AppError::Internal(anyhow::anyhow!("repo row gone")))?; git_show( - &state.git_bin, + git_bin, std::path::Path::new(&record.disk_path), &release.commit_sha, path, @@ -363,12 +366,10 @@ async fn pin_bytes( data: &[u8], fence: Option<&PolicyFence>, ) -> Result { - if let Some(f) = fence { - if !f.is_current().await { - return Ok(JobOutcome::Deferred); - } + if !fence_current(fence).await { + return Ok(JobOutcome::Deferred); } - let kubo = crate::ipfs_pin::pin_model_object( + let kubo = crate::ipfs_pin::pin_git_object( &state.config.ipfs_api, object_key, data, @@ -376,6 +377,12 @@ async fn pin_bytes( ) .await .map_err(AppError::Internal)?; + // Pinata is the off-node copy: check the epoch again between providers + // so a publicity flip mid-job cannot push content outbound that a flip + // one second earlier would have stopped entirely. + if !fence_current(fence).await { + return Ok(JobOutcome::Deferred); + } let pinata = crate::pinata::pin_model_object( &state.http_client, &state.config.pinata_upload_url, @@ -407,6 +414,7 @@ async fn post_anchor( release: &crate::models::ReleaseRow, job: &DurabilityJob, fence: Option<&PolicyFence>, + record: &RepoRecord, ) -> Result { if state.config.irys_url.is_empty() { return Ok(JobOutcome::Done(String::new())); @@ -421,11 +429,7 @@ async fn post_anchor( .model_durability_done_cid(job.release_id, KIND_BLOCK_MAP) .await? .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block map pin has no provider CID")))?; - let (rec_sha, rec_cid) = match state - .db - .model_release_reconstruction_sha(job.release_id) - .await? - { + let (rec_sha, rec_cid) = match state.db.model_reconstruction_sha(job.release_id).await? { Some(sha) => { let cid = state .db @@ -438,18 +442,11 @@ async fn post_anchor( } None => (None, None), }; - let signature = String::from_utf8(git_bytes(state, release, SIG_PATH).await?) + let signature = String::from_utf8(git_bytes(&state.git_bin, record, release, SIG_PATH).await?) .map_err(|_| AppError::Internal(anyhow::anyhow!("model-release.sig is not utf-8")))?; - let record = state - .db - .get_repo_by_id(&release.repo_id) - .await? - .ok_or_else(|| AppError::Internal(anyhow::anyhow!("repo row gone")))?; - if let Some(f) = fence { - if !f.is_current().await { - return Ok(JobOutcome::Deferred); - } + if !fence_current(fence).await { + return Ok(JobOutcome::Deferred); } let anchor = crate::arweave::ReleaseAnchor { repo: format!("{}/{}", record.owner_did, record.name), diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index 4486b145..681ed3ec 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -29,6 +29,13 @@ 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" +/// Paths inside a release commit: the signed manifest and its detached +/// signature. One definition shared by the claim reader, the HF surface, +/// and the durability jobs so a path change cannot split writers from +/// readers. +pub(crate) const RELEASE_MANIFEST_PATH: &str = ".twigpine/model-release.json"; +pub(crate) const RELEASE_SIG_PATH: &str = ".twigpine/model-release.sig"; + pub type ReleaseRow = ModelRelease; pub async fn read_range( diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 91f7bcf2..9738db1a 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -202,8 +202,6 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App hasher: sha2::Sha256::new(), head: Vec::new(), }; - // Ordered prefetch: `buffered` preserves order while - // overlapping the store's per-slice round trips. let store = state .block_store .clone() diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs index d30a55ce..9ae44b45 100644 --- a/crates/twigpine-node/tests/hf_api.rs +++ b/crates/twigpine-node/tests/hf_api.rs @@ -106,13 +106,16 @@ async fn seed_published_release( block_shas: &[String], ) -> i64 { let now = chrono::Utc::now().to_rfc3339(); + // created_at predates published_at so a test can tell which timestamp + // the surface reports. + let created = "2000-01-01T00:00:00Z".to_string(); let id: i64 = sqlx::query_scalar( "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, created_at, published_at) VALUES ($1,$2,$3,$4,'published',$5,$6,'sig','input','signing',\ - decode('00','hex'),$7,$7) + decode('00','hex'),$7,$8) RETURNING id", ) .bind(repo_id) @@ -121,6 +124,7 @@ async fn seed_published_release( .bind(publisher_did) .bind(manifest_sha) .bind(rec_sha) + .bind(&created) .bind(&now) .fetch_one(pool) .await @@ -358,7 +362,13 @@ async fn model_info_revision_tree_and_refs(pool: sqlx::PgPool) { assert_eq!(resp.status().as_u16(), 200); let v: Value = resp.json().await.expect("model info json"); assert_eq!(v["sha"].as_str(), Some(fx.commit.as_str())); - assert!(v["lastModified"].as_str().is_some()); + let published_at: String = + sqlx::query_scalar("SELECT published_at FROM model_releases WHERE repo_id = $1") + .bind(&repo_id) + .fetch_one(&pool) + .await + .expect("read published_at"); + assert_eq!(v["lastModified"].as_str(), Some(published_at.as_str())); let sibs: Vec<&str> = v["siblings"] .as_array() .expect("siblings") @@ -571,6 +581,15 @@ async fn pickle_entries_marked_unsafe(pool: sqlx::PgPool) { let entries: Vec = resp.json().await.unwrap(); assert_eq!(entries[0]["unsafe"].as_bool(), Some(true)); + // Model info marks the same file unsafe in siblings. + let resp = client + .get(format!("{}{}", node.base_url, info_path(&owner_did, "m"))) + .send() + .await + .expect("send"); + let v: Value = resp.json().await.unwrap(); + assert_eq!(v["siblings"][0]["unsafe"].as_bool(), Some(true)); + node.shutdown().await; } @@ -915,3 +934,131 @@ async fn resolve_denies_after_repo_turns_private(pool: sqlx::PgPool) { node.shutdown().await; } + +/// `/tree/{rev}/{path}` treats `path` as a directory prefix on a slash +/// boundary: `sub` lists `sub/*` and must not leak a sibling-prefix +/// `subdir/*` entry. +#[sqlx::test] +async fn tree_path_filters_on_slash_boundary(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(23); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[ + ("sub/a.txt", b"a".as_ref()), + ("sub/b.txt", b"b".as_ref()), + ("subdir/c.txt", b"c".as_ref()), + ], + &[], + "main", + ) + .await; + + for suffix in ["sub", "sub/"] { + let resp = client + .get(format!( + "{}{}/{}", + node.base_url, + tree_path(&owner_did, "m", "main"), + suffix + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200, "{suffix}"); + let entries: Vec = resp.json().await.expect("tree json"); + let paths: Vec<&str> = entries.iter().filter_map(|e| e["path"].as_str()).collect(); + assert_eq!(paths, ["sub/a.txt", "sub/b.txt"], "{suffix}"); + } + + // The unprefixed tree still lists every file. + let resp = client + .get(format!( + "{}{}", + node.base_url, + tree_path(&owner_did, "m", "main") + )) + .send() + .await + .expect("send"); + let entries: Vec = resp.json().await.expect("tree json"); + assert_eq!(entries.len(), 3); + + node.shutdown().await; +} + +/// Every HF route answers the same existence-hiding 404 for a repo that is +/// private or carries visibility rules, anonymous or signed-stranger. +#[sqlx::test] +async fn all_routes_deny_private_and_ruled_repos(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, _signing) = owner_with_signing(24); + let owner_did = owner.did().to_string(); + let (stranger, _) = owner_with_signing(25); + + node.seed_repo(&owner_did, "priv", false).await; + let ruled_id = node.seed_repo(&owner_did, "ruled", true).await; + sqlx::query( + "INSERT INTO visibility_rules + (id, repo_id, path_glob, mode, reader_dids, created_by, created_at) + VALUES ('r1', $1, '/withheld/**', 'b', '[]', $2, '2000-01-01T00:00:00Z')", + ) + .bind(&ruled_id) + .bind(&owner_did) + .execute(&pool) + .await + .expect("seed rule"); + + for repo in ["priv", "ruled"] { + let routes = [ + info_path(&owner_did, repo), + rev_path(&owner_did, repo, "main"), + tree_path(&owner_did, repo, "main"), + format!("{}/sub", tree_path(&owner_did, repo, "main")), + refs_path(&owner_did, repo), + resolve_path(&owner_did, repo, "main", "config.json"), + ]; + for route in routes { + for (label, req) in [ + ("anon", client.get(format!("{}{}", node.base_url, route))), + ( + "stranger", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &route, + Vec::new(), + &stranger, + ), + ), + ] { + let resp = req.send().await.expect("send"); + assert_eq!(resp.status().as_u16(), 404, "{repo} {route} {label}"); + // Denial must not echo whether a repo or release exists: + // the body is the same not-found shape a missing repo gets. + let body: Value = resp.json().await.expect("denial body"); + let text = body.to_string(); + assert!( + text.contains("repo_not_found") || text.contains("not_found"), + "{repo} {route} {label}: {body}" + ); + assert!( + !text.contains("private") && !text.contains("forbidden"), + "{repo} {route} {label} leaked: {body}" + ); + } + } + } + + node.shutdown().await; +} diff --git a/docs/MODEL-HOSTING.md b/docs/MODEL-HOSTING.md index a7f674f0..9134ddd7 100644 --- a/docs/MODEL-HOSTING.md +++ b/docs/MODEL-HOSTING.md @@ -10,9 +10,9 @@ Arweave and IPFS with no node in the loop. `twigpine model publish` runs inside a local clone and: -1. Classifies files by the chunking threshold (10 MiB): smaller files stay - ordinary git blobs, larger ones are packed into content blocks (up to - 128 MiB each) uploaded out of band under an upload session. +1. Classifies files by the chunking threshold (10 MiB): files below it stay + ordinary git blobs, files at or above it are packed into content blocks + (up to 128 MiB each) uploaded out of band under an upload session. 2. Commits `.twigpine/model-release.json` (the signed manifest) and `.twigpine/model-release.sig` (a detached Ed25519 signature over the exact manifest bytes), pushes, and posts a release claim to the node. @@ -37,6 +37,8 @@ without it. | `TWIGPINE_MODEL_NODE_QUOTA_BYTES` | `1099511627776` (1 TiB) | Total model bytes the node will hold, open sessions included. | | `TWIGPINE_MODEL_SESSION_TTL_SECS` | `43200` | Base upload-session lifetime; each accepted block renews it. | | `TWIGPINE_MODEL_UNCLAIMED_TTL_SECS` | `86400` | Grace before blocks no release references are swept. Must exceed the session TTL. | +| `TWIGPINE_HF_READ_RATE_LIMIT` | `600` | Per-IP request limit for the `/hf` read surface, per hour. | +| `TWIGPINE_MODEL_DOWNLOAD_PERMITS` | `16` | Concurrent model downloads the resolve route will stream. | | `TWIGPINE_MODEL_MAX_SESSION_BYTES` | unset (uses the identity quota) | Optional cap on one identity's open sessions. | | `TWIGPINE_BLOCKSTORE_DIR` | `./data/model-blocks` | Where blocks live with the filesystem backend. | | `TWIGPINE_BLOCKSTORE_S3_BUCKET` | unset | Store blocks in S3 instead; reuses the `AWS_*` endpoint and credentials of the Tigris backend. | @@ -70,13 +72,15 @@ confirmation before it claims. ### HF-compatible API A `huggingface_hub` client pointed at the node reads a published release like -an HF repo. The repo id is `/` (the owner segment carries -the DID literally, colons and all): +an HF repo. The repo id is `/` where `` is the bare DID +key: `huggingface_hub` validates `repo_id` client-side and rejects the +colons in a full `did:key:` string, so pass the key without the `did:key:` +prefix. The node normalizes it back to the full DID. ```python from huggingface_hub import snapshot_download # HF_ENDPOINT=https:///hf -snapshot_download(repo_id="did:key:z6Mk.../my-model") +snapshot_download(repo_id="z6Mk.../my-model") ``` Mounted routes: `GET /hf/api/models/{owner}/{repo}`, @@ -85,9 +89,9 @@ Mounted routes: `GET /hf/api/models/{owner}/{repo}`, Anonymous reads work on fully public repos; HF bearer tokens carry no signature and read as anonymous. -One size limit to know: huggingface_hub 2.x refuses plain downloads of a -single file over 50 GiB, so `model publish` warns when a chunked file passes -that line. +One size limit to know: current `huggingface_hub` releases refuse plain +downloads of a single file over 50 GiB, so `model publish` warns when a +chunked file passes that line. ### Independent fetch (no node) @@ -124,7 +128,7 @@ With a node running the feature and both providers configured: (`GET /api/v1/repos/{owner}/{repo}/models/releases/{commit}`). 2. Confirm the durability jobs drained: the release's pin rows land on the configured IPFS tiers and one anchor tx posts to Irys. -3. `HF_ENDPOINT=http://localhost:PORT/hf python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='/')"`. +3. `HF_ENDPOINT=http://localhost:PORT/hf python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='/')"` (`` is the bare DID key, no `did:key:` prefix). 4. Stop the node, then `twigpine model fetch / --expect-did --output /tmp/m` and diff the result against the original files. From 26901c9f645dfdb4e58687365a3384217561c74a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:36:34 -0600 Subject: [PATCH 07/14] fix(node,cli): harden HF denials, durability errors, and anchor validation - Echo the requested owner/name in existence-hiding HF denials instead of internal storage identifiers, and assert the body leaks neither. - Validate anchor release_commit as a real hex commit (40 for sha1 repos, 64 for sha256 repos) before it shapes the output dir or fetch URLs, and keep CID path interpolation behind URL-safe checks. - Bound download concurrency with the configured semaphore type and resolve refs through published releases only. - Bound durability retry error recording; leave non-pending jobs alone. - Cover traversal-shaped release commits and 64-hex commits in the fetch suite; keep the node-down e2e honest. --- crates/twigpine-cli/src/model.rs | 60 ++++++++++++++++++- crates/twigpine-cli/tests/model_fetch.rs | 33 +++++++++- crates/twigpine-node/src/api/hf.rs | 54 ++++++++++++----- crates/twigpine-node/src/db/model_queries.rs | 7 ++- crates/twigpine-node/src/models/durability.rs | 19 ++++-- crates/twigpine-node/tests/hf_api.rs | 15 +++-- 6 files changed, 158 insertions(+), 30 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index bd67b158..b9fac517 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -1267,6 +1267,18 @@ async fn discover_release_anchors( refs } +/// Whether an untrusted id (anchor tx, provider CID) is safe to interpolate +/// as one path segment of a gateway URL. Alnum plus the base32/base64url +/// punctuation CIDs and tx ids actually use; `/`, `?`, `#`, and `..` would +/// rewrite the request path on the gateway host. +fn url_path_safe(id: &str) -> bool { + !id.is_empty() + && !id.contains("..") + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'=')) +} + /// One anchor candidate through its trust gates: fetch the body, parse the /// anchor JSON, then fetch the manifest and verify it against the expected /// DID. Returns `Some(..)` only when the manifest verifies; every failure is @@ -1279,6 +1291,10 @@ async fn verify_candidate( revision: Option<&str>, warnings: &mut Vec, ) -> Option<(ReleaseAnchorBody, Manifest)> { + if !url_path_safe(tx_id) { + note_skip(warnings, "anchor tx id is not URL-safe".to_string()); + return None; + } let mut skip = |why: String| { note_skip(warnings, format!("anchor {tx_id}: {why}")); None @@ -1301,6 +1317,26 @@ async fn verify_candidate( if anchor.schema != ANCHOR_SCHEMA { return skip(format!("unknown anchor schema {:?}", anchor.schema)); } + // release_commit is unsigned anchor text that lands in the default + // output directory name: require a real hex commit shape (40 for sha1 + // repos, 64 for sha256 repos), never a path fragment. + let commit = &anchor.release_commit; + if !(commit.len() == 40 || commit.len() == 64) + || !commit + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return skip("release_commit is not a hex commit".to_string()); + } + if !url_path_safe(&anchor.manifest_cid) + || !url_path_safe(&anchor.block_map_cid) + || anchor + .reconstruction_cid + .as_deref() + .is_some_and(|c| !url_path_safe(c)) + { + return skip("anchor names a CID that is not URL-safe".to_string()); + } if anchor.repo != repo { return skip(format!( "anchor names repo {:?}, expected {repo}", @@ -1425,6 +1461,9 @@ impl BlockSource<'_> { .blocks .get(sha) .with_context(|| format!("block map has no CID for block {sha}"))?; + if !url_path_safe(cid) { + bail!("block {sha} maps to a CID that is not URL-safe"); + } let bytes = get_capped( self.client, &format!("{}/ipfs/{cid}", self.ig), @@ -1560,6 +1599,13 @@ pub async fn fetch_model(args: &FetchArgs) -> Result { .split_once('/') .filter(|(o, n)| !o.is_empty() && !n.is_empty() && !n.contains('/')) .context("repo must be /")?; + // Anchors tag the full DID; accept the bare DID key (the HF-safe form) + // by normalizing to did:key, matching the node's repo lookup. + let owner = if owner.starts_with("did:") { + owner.to_string() + } else { + format!("did:key:{owner}") + }; let repo = format!("{owner}/{name}"); let expect_did: Did = args .expect_did @@ -1620,6 +1666,9 @@ pub async fn fetch_model(args: &FetchArgs) -> Result { rec_ref.sha256 ) })?; + if !url_path_safe(rec_cid) { + bail!("reconstruction CID {rec_cid:?} is not URL-safe"); + } let bytes = get_capped( &client, &format!("{ig}/ipfs/{rec_cid}"), @@ -1707,6 +1756,9 @@ pub async fn fetch_model(args: &FetchArgs) -> Result { file.path, file.sha256 ) })?; + if !url_path_safe(cid) { + bail!("{}: block map CID is not URL-safe", file.path); + } let bytes = get_capped( &client, &format!("{ig}/ipfs/{cid}"), @@ -1760,8 +1812,12 @@ pub async fn fetch_model(args: &FetchArgs) -> Result { async fn cmd_fetch(args: FetchArgs) -> Result<()> { let report = fetch_model(&args).await?; - println!("fetched {} release {}", report.repo, report.release_commit); - println!(" anchor: {}", report.anchor_tx); + println!( + "fetched {} release {}", + sanitize_node_msg(&report.repo), + sanitize_node_msg(&report.release_commit) + ); + println!(" anchor: {}", sanitize_node_msg(&report.anchor_tx)); println!( " verified: {} file(s), {} byte(s)", report.files, report.bytes diff --git a/crates/twigpine-cli/tests/model_fetch.rs b/crates/twigpine-cli/tests/model_fetch.rs index 78a7db7a..b47d7bca 100644 --- a/crates/twigpine-cli/tests/model_fetch.rs +++ b/crates/twigpine-cli/tests/model_fetch.rs @@ -19,7 +19,7 @@ use twigpine_core::model::reconstruction::{ BlockEntry, ChunkMeta, FileEntry, Reconstruction, Term, }; -const COMMIT: &str = "aaaabbbbccccddddeeeeffff00001111"; +const COMMIT: &str = "aaaabbbbccccddddeeeeffff0000111122223333"; const ANCHOR_SCHEMA: &str = "gitlawb/model-release-anchor/v1"; const BLOCK_MAP_SCHEMA: &str = "gitlawb/model-block-map/v1"; @@ -432,3 +432,34 @@ async fn manifest_path_traversal_is_refused() { assert!(err.to_string().contains("relative path")); assert!(!out.path().join("escape.txt").exists()); } + +#[tokio::test] +async fn anchor_with_traversal_release_commit_is_skipped() { + let owner = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + // release_commit is unsigned anchor text that shapes the default output + // dir: a traversal-shaped value must be refused, not followed. + let mut hostile = anchor_json(&release, &release.did, &release.signing, &rec_sha); + hostile["release_commit"] = json!("a/../escape"); + let good = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let server = serve( + &[("tx-hostile", hostile), ("tx-good", good)], + &release.objects, + ) + .await; + + let out = TempDir::new().unwrap(); + let report = fetch_model(&args(&server.url(), &release.did, &out)) + .await + .unwrap(); + assert_eq!(report.anchor_tx, "tx-good"); + assert!( + report + .warnings + .iter() + .any(|w| w.contains("tx-hostile") && w.contains("hex commit")), + "the malformed commit should be reported: {:?}", + report.warnings + ); +} diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs index 15630f69..573546c4 100644 --- a/crates/twigpine-node/src/api/hf.rs +++ b/crates/twigpine-node/src/api/hf.rs @@ -75,9 +75,16 @@ fn caller_did(auth: &Option>) -> Option<&str> { /// egress guard sees it): model hosting serves only a fully public repo, /// and anything else answers the same bare 404 so release existence cannot /// be inferred through the model surface. -fn require_fully_public_404(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<(), AppError> { +fn require_fully_public_404( + record: &RepoRecord, + rules: &[VisibilityRule], + owner: &str, + name: &str, +) -> Result<(), AppError> { if require_fully_public(record, rules).is_err() { - return Err(AppError::RepoNotFound(record.id.clone())); + // The caller's spelling, byte-matching authorize_repo_read's + // missing-repo body: the internal id never leaves the node. + return Err(AppError::RepoNotFound(format!("{owner}/{name}"))); } Ok(()) } @@ -94,7 +101,11 @@ async fn release_for_rev( rev: &str, ) -> Result, AppError> { let rev = rev.trim(); - if rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()) { + if rev.len() == 40 + && rev + .bytes() + .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase() && (b'a'..=b'f').contains(&b)) + { let rel = state .db .model_release_by_commit(&record.id, rev) @@ -249,7 +260,7 @@ pub async fn hf_model_info( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; + require_fully_public_404(&record, &rules, &owner, &name)?; let Some(release) = state.db.model_release_newest(&record.id).await? else { return Ok(hf_deny(StatusCode::NOT_FOUND, "RepoNotFound")); }; @@ -267,7 +278,7 @@ pub async fn hf_revision_info( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; + require_fully_public_404(&record, &rules, &owner, &name)?; let Some(release) = release_for_rev(&state, &record, &rev).await? else { return revision_or_repo_not_found(&state, &record).await; }; @@ -285,7 +296,7 @@ pub async fn hf_tree( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; + require_fully_public_404(&record, &rules, &owner, &name)?; tree_response(&state, &record, &rev, "").await } @@ -300,7 +311,7 @@ pub async fn hf_tree_path( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; + require_fully_public_404(&record, &rules, &owner, &name)?; let prefix = if path.ends_with('/') { path } else { @@ -334,8 +345,11 @@ pub async fn hf_refs( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; - let Some(release) = state.db.model_release_newest(&record.id).await? else { + require_fully_public_404(&record, &rules, &owner, &name)?; + // `main` names exactly the release `revision/main` resolves: newest on + // main, then the git default branch. Advertising any other release + // would promise a commit the revision route does not serve. + let Some(release) = release_for_rev(&state, &record, "main").await? else { return Ok(hf_deny(StatusCode::NOT_FOUND, "RepoNotFound")); }; let branches = vec![json!({"name": "main", "targetCommit": release.commit_sha})]; @@ -361,7 +375,7 @@ pub async fn hf_resolve( hosting_enabled(&state)?; let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; - require_fully_public_404(&record, &rules)?; + require_fully_public_404(&record, &rules, &owner, &name)?; let Some(release) = release_for_rev(&state, &record, &rev).await? else { return revision_or_repo_not_found(&state, &record).await; }; @@ -390,7 +404,10 @@ pub async fn hf_resolve( let t = t.trim(); // If-None-Match compares weakly: strip an optional `W/`. let t = t.strip_prefix("W/").unwrap_or(t); - t.trim_matches('"') == file.sha256 + t.strip_prefix('"') + .and_then(|x| x.strip_suffix('"')) + .unwrap_or(t) + == file.sha256 }); if hit { let mut resp = Response::new(Body::empty()); @@ -469,10 +486,13 @@ pub async fn hf_resolve( .clone() .ok_or_else(|| AppError::NotFound("model hosting not enabled".into()))?; // Bound concurrent model downloads: a stalled reader upstream must not - // starve every other consumer of the node. - let _permit = state + // starve every other consumer of the node. Owned so the permit can ride + // the response stream: a chunked body pulls blocks after this handler + // returns, long past a borrowed permit's drop. + let permit = state .model_download_semaphore - .acquire() + .clone() + .acquire_owned() .await .map_err(|_| AppError::Internal(anyhow::anyhow!("download semaphore closed")))?; @@ -535,7 +555,11 @@ pub async fn hf_resolve( entry, &rec, want_start, want_end, ) .map_err(|e| AppError::Internal(anyhow::anyhow!("range map: {e}")))?; - Body::from_stream(serve::slices_stream(store, slices)) + let stream = serve::slices_stream(store, slices); + Body::from_stream(futures::StreamExt::map(stream, move |item| { + let _held = &permit; + item + })) } }; diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c8ce6856..c53208e9 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -937,14 +937,15 @@ impl Db { Ok(sqlx::query_scalar( "UPDATE model_durability_jobs SET attempts = attempts + 1, last_error = $2, updated_at = $3 - WHERE id = $1 + WHERE id = $1 AND state = 'pending' RETURNING attempts", ) .bind(id) .bind(err) .bind(ts_now()) - .fetch_one(&self.pool) - .await?) + .fetch_optional(&self.pool) + .await? + .unwrap_or(0)) } /// Terminal failure: the job leaves the drain set until an operator diff --git a/crates/twigpine-node/src/models/durability.rs b/crates/twigpine-node/src/models/durability.rs index 93a9ad1a..dfdad6db 100644 --- a/crates/twigpine-node/src/models/durability.rs +++ b/crates/twigpine-node/src/models/durability.rs @@ -1,9 +1,10 @@ //! Durability outbox for published releases (KTD10, KTD13). //! //! Publishing a release enqueues one job per content object: -//! `pin_block` for every block the release references, `pin_manifest` and -//! `pin_reconstruction` for the git-resident objects, `pin_block_map` for -//! the sha256-to-provider-CID map, and `anchor` for the Irys release root. +//! `pin_block` for every block the release references, `pin_manifest` for +//! the git-resident manifest, `pin_reconstruction` for the block-store +//! reconstruction object, `pin_block_map` for the sha256-to-provider-CID +//! map, and `anchor` for the Irys release root. //! Jobs are keyed `(release, kind, object)` so re-enqueueing is a no-op, //! and the startup backfill inserts missing sets atomically. //! @@ -57,13 +58,16 @@ pub async fn enqueue_for_release(state: &AppState, release_id: i64) -> Result<() if release.state != "published" { return Ok(()); } + let rec_sha = state.db.model_reconstruction_sha(release_id).await?; let block_shas = state.db.model_release_blocks(release_id).await?; let mut jobs: Vec<(&str, &str)> = block_shas .iter() + // The claim links the reconstruction object as a referenced block; + // its dedicated job pins it, so skip the duplicate pin_block row. + .filter(|sha| Some(sha.as_str()) != rec_sha.as_deref()) .map(|sha| (KIND_BLOCK, sha.as_str())) .collect(); jobs.push((KIND_MANIFEST, release.manifest_sha256.as_str())); - let rec_sha = state.db.model_reconstruction_sha(release_id).await?; if let Some(sha) = rec_sha.as_deref() { jobs.push((KIND_RECONSTRUCTION, sha)); } @@ -122,6 +126,9 @@ async fn still_publishable(state: &AppState, record: &RepoRecord) -> Result) -> bool { match fence { Some(f) => f.is_current().await, - None => true, + // `capture` yields None only when the epoch read failed; fail + // closed like `is_current` does on a read failure. + None => false, } } diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs index 9ae44b45..475c3eeb 100644 --- a/crates/twigpine-node/tests/hf_api.rs +++ b/crates/twigpine-node/tests/hf_api.rs @@ -1005,7 +1005,7 @@ async fn all_routes_deny_private_and_ruled_repos(pool: sqlx::PgPool) { let owner_did = owner.did().to_string(); let (stranger, _) = owner_with_signing(25); - node.seed_repo(&owner_did, "priv", false).await; + let priv_id = node.seed_repo(&owner_did, "priv", false).await; let ruled_id = node.seed_repo(&owner_did, "ruled", true).await; sqlx::query( "INSERT INTO visibility_rules @@ -1018,7 +1018,7 @@ async fn all_routes_deny_private_and_ruled_repos(pool: sqlx::PgPool) { .await .expect("seed rule"); - for repo in ["priv", "ruled"] { + for (repo, repo_id) in [("priv", &priv_id), ("ruled", &ruled_id)] { let routes = [ info_path(&owner_did, repo), rev_path(&owner_did, repo, "main"), @@ -1045,7 +1045,8 @@ async fn all_routes_deny_private_and_ruled_repos(pool: sqlx::PgPool) { let resp = req.send().await.expect("send"); assert_eq!(resp.status().as_u16(), 404, "{repo} {route} {label}"); // Denial must not echo whether a repo or release exists: - // the body is the same not-found shape a missing repo gets. + // the body is the same not-found shape a missing repo gets, + // {owner}/{name} exactly as spelled, never the internal id. let body: Value = resp.json().await.expect("denial body"); let text = body.to_string(); assert!( @@ -1053,7 +1054,13 @@ async fn all_routes_deny_private_and_ruled_repos(pool: sqlx::PgPool) { "{repo} {route} {label}: {body}" ); assert!( - !text.contains("private") && !text.contains("forbidden"), + text.contains(&format!("'{owner_did}/{repo}'")), + "{repo} {route} {label} wrong shape: {body}" + ); + assert!( + !text.contains(repo_id.as_str()) + && !text.contains("private") + && !text.contains("forbidden"), "{repo} {route} {label} leaked: {body}" ); } From d647cc7780fa70834966744e5dc03e9bd12022c0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:27:18 -0600 Subject: [PATCH 08/14] fix(node,cli): accept sha256-length commits on the model surface A sha256-format repo's commit ids are 64 hex, and three gates still required exactly 40: the release claim rejected the commit outright, the HF revision resolver never treated a 64-hex rev as commit-shaped, and the CLI --parent parser rejected the same input. Centralize the check as twigpine_core::cid::is_hex_oid so the next commit-shaped gate cannot reintroduce a sha1-only assumption. --- crates/twigpine-cli/src/model.rs | 13 ++++--------- crates/twigpine-core/src/cid.rs | 26 ++++++++++++++++++++++++++ crates/twigpine-node/src/api/hf.rs | 15 ++++++--------- crates/twigpine-node/src/api/models.rs | 4 ++-- 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index b9fac517..7eb47dd8 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -528,7 +528,7 @@ fn save_state(path: &Path, state: &PublishState) -> Result<()> { // ── misc ──────────────────────────────────────────────────────────────────── -/// `/@<40-hex commit>` -> ((owner, name), commit). +/// `/@` -> ((owner, name), commit). fn parse_parent(spec: &str) -> Result<((String, String), String)> { let (repo, commit) = spec .rsplit_once('@') @@ -539,8 +539,8 @@ fn parse_parent(spec: &str) -> Result<((String, String), String)> { 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"); + if !twigpine_core::cid::is_hex_oid(commit) { + bail!("parent commit must be a hex sha"); } Ok(((owner.to_string(), name.to_string()), commit.to_string())) } @@ -1320,12 +1320,7 @@ async fn verify_candidate( // release_commit is unsigned anchor text that lands in the default // output directory name: require a real hex commit shape (40 for sha1 // repos, 64 for sha256 repos), never a path fragment. - let commit = &anchor.release_commit; - if !(commit.len() == 40 || commit.len() == 64) - || !commit - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) - { + if !twigpine_core::cid::is_hex_oid(&anchor.release_commit) { return skip("release_commit is not a hex commit".to_string()); } if !url_path_safe(&anchor.manifest_cid) diff --git a/crates/twigpine-core/src/cid.rs b/crates/twigpine-core/src/cid.rs index 2071d478..daf58bcf 100644 --- a/crates/twigpine-core/src/cid.rs +++ b/crates/twigpine-core/src/cid.rs @@ -98,6 +98,15 @@ pub fn sha256_bytes(bytes: &[u8]) -> [u8; 32] { hasher.finalize().into() } +/// Whether `s` has the shape of a git object id in either object format this +/// node supports: 40 lowercase hex (sha1) or 64 lowercase hex (sha256). +/// Accepts upper-case hex too, matching the other commit-shape gates. +/// Commit-shaped validation anywhere in the tree must use this rather than a +/// bare 40-length check, which silently rejects sha256-format repos. +pub fn is_hex_oid(s: &str) -> bool { + (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + /// Parse a 64-character hex SHA-256 string into raw bytes. pub fn sha256_hex_to_bytes(hex_str: &str) -> Result<[u8; 32]> { let bytes = hex::decode(hex_str).map_err(|e| Error::InvalidCid(format!("invalid hex: {e}")))?; @@ -135,6 +144,23 @@ mod tests { assert_eq!(h.len(), 64); } + #[test] + fn is_hex_oid_accepts_both_object_formats() { + let sha1 = "a".repeat(40); + let sha256 = "b".repeat(64); + assert!(is_hex_oid(&sha1)); + assert!(is_hex_oid(&sha256)); + for bad in [ + "", + "a/../escape", + &"a".repeat(39), + &"a".repeat(41), + &"z".repeat(40), + ] { + assert!(!is_hex_oid(bad), "{bad:?} must not pass the oid gate"); + } + } + #[test] fn sha256_round_trip() { let data = b"git object content"; diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs index 573546c4..263e36df 100644 --- a/crates/twigpine-node/src/api/hf.rs +++ b/crates/twigpine-node/src/api/hf.rs @@ -91,21 +91,18 @@ fn require_fully_public_404( /// Resolve the HF revision to a published release row. /// -/// A 40-hex rev is a commit pin. `main` resolves to the newest published -/// release recorded on `main`, then on the repo's git default branch (a -/// `master` default still serves HF `main`). Any other string is a branch -/// name resolving to its newest published release. +/// A hex rev is a commit pin (40 for sha1 repos, 64 for sha256). `main` +/// resolves to the newest published release recorded on `main`, then on the +/// repo's git default branch (a `master` default still serves HF `main`). +/// Any other string is a branch name resolving to its newest published +/// release. async fn release_for_rev( state: &AppState, record: &RepoRecord, rev: &str, ) -> Result, AppError> { let rev = rev.trim(); - if rev.len() == 40 - && rev - .bytes() - .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase() && (b'a'..=b'f').contains(&b)) - { + if twigpine_core::cid::is_hex_oid(rev) { let rel = state .db .model_release_by_commit(&record.id, rev) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index a53afa69..9a3a410e 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -304,8 +304,8 @@ pub async fn claim_model_release( ))); }; 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())); + if !twigpine_core::cid::is_hex_oid(&body.commit) { + return Err(AppError::BadRequest("commit must be a hex sha".into())); } let material = models::claim::ClaimMaterial { request_digest: crate::api::status::request_digest(&material, &body_bytes), From d28b926a660e64b3e9fec6e04b34f413d5ca75a3 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:00:43 -0600 Subject: [PATCH 09/14] fix(node,ci): one default release across HF routes, surface fixtures cover node fan-out Model info now resolves the default release the way refs and revision/main do (newest on main, then the git default branch) instead of the repo-wide newest. A two-branch test pins all three routes to one commit, and the module doc, query doc and MODEL-HOSTING.md state the single rule. twigpine-node dev-depends on twigpine-cli, so the surface mapper adds -p twigpine-node for CLI paths. The seven pinned fixture rows in test-ci-surfaces.sh now expect it. --- crates/twigpine-node/src/api/hf.rs | 15 ++-- crates/twigpine-node/src/db/model_queries.rs | 5 +- crates/twigpine-node/tests/hf_api.rs | 73 ++++++++++++++++++++ docs/MODEL-HOSTING.md | 5 ++ scripts/test-ci-surfaces.sh | 8 +-- 5 files changed, 93 insertions(+), 13 deletions(-) diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs index 263e36df..d00e16cb 100644 --- a/crates/twigpine-node/src/api/hf.rs +++ b/crates/twigpine-node/src/api/hf.rs @@ -7,9 +7,10 @@ //! GET /hf/api/models/{owner}/{repo}/refs branch refs //! HEAD|GET /hf/{owner}/{repo}/resolve/{rev}/{*path} file bytes //! -//! Metadata comes from the newest published release row and its manifest, -//! never from arbitrary git history: a plain push after a release does not -//! move HF `main`. Publicity is checked before any release lookup, so a +//! Metadata comes from published release rows and their manifests, never +//! from arbitrary git history: a plain push after a release does not move +//! HF `main`. Model info, `refs` and `revision/main` all name the same +//! default release: the newest on `main`, then on the git default branch. Publicity is checked before any release lookup, so a //! private, mirrored, or rule-bearing repo answers the same 404 as a //! missing one and releases never leak existence. //! @@ -246,9 +247,9 @@ fn tree_entries(manifest: &Manifest, prefix: &str) -> Vec { out } -/// `GET /hf/api/models/{owner}/{repo}`, model info for the newest -/// published release (`sha` is the release commit, `siblings` the manifest -/// file list). +/// `GET /hf/api/models/{owner}/{repo}`, model info for the default release, +/// the same one `refs` and `revision/main` name (`sha` is the release +/// commit, `siblings` the manifest file list). pub async fn hf_model_info( State(state): State, Path((owner, name)): Path<(String, String)>, @@ -258,7 +259,7 @@ pub async fn hf_model_info( let caller = caller_did(&auth); let (record, rules) = authorize_repo_read(&state, &owner, &name, caller, "/").await?; require_fully_public_404(&record, &rules, &owner, &name)?; - let Some(release) = state.db.model_release_newest(&record.id).await? else { + let Some(release) = release_for_rev(&state, &record, "main").await? else { return Ok(hf_deny(StatusCode::NOT_FOUND, "RepoNotFound")); }; let manifest = load_manifest(&state, &record, &release).await?; diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c53208e9..fa42a003 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -819,8 +819,9 @@ impl Db { Ok(row.map(Into::into)) } - /// The newest published release on the repo, whatever branch recorded it - /// (the `refs` endpoint's default target). + /// The newest published release on the repo, whatever branch recorded it. + /// Only an existence check: HF default-release resolution is + /// `release_for_rev(.., "main")`, which is branch-scoped. pub async fn model_release_newest(&self, repo_id: &str) -> Result> { let row = sqlx::query_as::<_, ReleaseTuple>(&format!( "SELECT {RELEASE_COLS} FROM model_releases diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs index 475c3eeb..c36414df 100644 --- a/crates/twigpine-node/tests/hf_api.rs +++ b/crates/twigpine-node/tests/hf_api.rs @@ -649,6 +649,79 @@ async fn master_default_branch_serves_hf_main(pool: sqlx::PgPool) { node.shutdown().await; } +/// With releases on two branches, model info, `revision/main` and `refs` +/// all name the newest release on `main`, not the repo-wide newest, so a +/// `huggingface_hub` client sees one commit on every surface. +#[sqlx::test] +async fn model_info_follows_main_not_repo_wide_newest(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(25); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let on_main = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[], + "main", + ) + .await; + let dir_main: (String,) = sqlx::query_as("SELECT disk_path FROM repos WHERE id = $1") + .bind(&repo_id) + .fetch_one(&pool) + .await + .unwrap(); + // A later release on another branch gets the higher row id. + let on_dev = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE), ("extra.json", GIT_FILE)], + &[], + "dev", + ) + .await; + assert_ne!(on_main.commit, on_dev.commit); + // Serve both commits from the one on-disk repo. + let dir_dev: (String,) = sqlx::query_as("SELECT disk_path FROM repos WHERE id = $1") + .bind(&repo_id) + .fetch_one(&pool) + .await + .unwrap(); + run_git( + std::path::Path::new(&dir_dev.0), + &["fetch", "-q", &dir_main.0, "main"], + ); + + for path in [ + info_path(&owner_did, "m"), + rev_path(&owner_did, "m", "main"), + refs_path(&owner_did, "m"), + ] { + let resp = client + .get(format!("{}{}", node.base_url, path)) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200, "{path}"); + let v: Value = resp.json().await.unwrap(); + let sha = v["sha"] + .as_str() + .or_else(|| v["branches"][0]["targetCommit"].as_str()); + assert_eq!(sha, Some(on_main.commit.as_str()), "{path} must follow main"); + } + + node.shutdown().await; +} + /// A plain git commit after the release does not move HF `main`: refs and /// model info still name the release commit. #[sqlx::test] diff --git a/docs/MODEL-HOSTING.md b/docs/MODEL-HOSTING.md index 9134ddd7..6f34b454 100644 --- a/docs/MODEL-HOSTING.md +++ b/docs/MODEL-HOSTING.md @@ -89,6 +89,11 @@ Mounted routes: `GET /hf/api/models/{owner}/{repo}`, Anonymous reads work on fully public repos; HF bearer tokens carry no signature and read as anonymous. +The default release is the same on every route: model info, `refs` and +`revision/main` all name the newest published release on `main`, then on the +repo's git default branch. A release published from any other branch is +reachable by its branch name or commit, never as the default. + One size limit to know: current `huggingface_hub` releases refuse plain downloads of a single file over 50 GiB, so `model publish` warns when a chunked file passes that line. diff --git a/scripts/test-ci-surfaces.sh b/scripts/test-ci-surfaces.sh index aad3c5f8..f358b5c9 100755 --- a/scripts/test-ci-surfaces.sh +++ b/scripts/test-ci-surfaces.sh @@ -56,7 +56,7 @@ check "empty input" "$(map)" "${nothing[@]}" # A crate change tests that crate and its reverse deps, nothing else. check "twigpine source" "$(map crates/twigpine-cli/src/main.rs)" \ - rust=true 'rust_packages=-p twigpine-cli' windows=true 'windows_packages=-p twigpine-cli' \ + rust=true 'rust_packages=-p twigpine-cli -p twigpine-node' windows=true 'windows_packages=-p twigpine-cli' \ docker=false audit=false "$rust_only" out="$(map crates/twigpine-core/src/lib.rs)" check "twigpine-core source" "$out" rust=true windows=true \ @@ -64,7 +64,7 @@ check "twigpine-core source" "$out" rust=true windows=true \ has_packages "twigpine-core fan-out" "$out" twigpine-core icaptcha-client \ twigpine-attest git-remote-twigpine twigpine-cli twigpine-node check "icaptcha-client source" "$(map crates/icaptcha-client/src/lib.rs)" \ - 'rust_packages=-p icaptcha-client -p twigpine-cli' 'windows_packages=-p twigpine-cli' + 'rust_packages=-p icaptcha-client -p twigpine-cli -p twigpine-node' 'windows_packages=-p twigpine-cli' # Anything the Rust surface cannot attribute to known crates widens. check "unknown crate dir" "$(map crates/no-such-crate/src/lib.rs)" \ @@ -81,7 +81,7 @@ check "bootstrap-peers.json" "$(map bootstrap-peers.json)" \ # One must-not-skip trigger per non-Rust row. check "Dockerfile" "$(map Dockerfile)" docker=true rust=false check "crate manifest" "$(map crates/twigpine-cli/Cargo.toml)" \ - docker=true release_versioning=true 'rust_packages=-p twigpine-cli' + docker=true release_versioning=true 'rust_packages=-p twigpine-cli -p twigpine-node' check "audit config" "$(map .cargo/audit.toml)" audit=true rust_packages=--workspace check "core allowlist" "$(map ci/twigpine-core-allowed-deps.txt)" core_deps=true rust=false check "release-please config" "$(map release-please-config.json)" \ @@ -103,7 +103,7 @@ check "--all" "$("$mapper" --all Date: Sat, 21 Nov 2026 01:16:08 -0600 Subject: [PATCH 10/14] style(node): rustfmt the two-branch HF test --- crates/twigpine-node/tests/hf_api.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs index c36414df..fe7fd851 100644 --- a/crates/twigpine-node/tests/hf_api.rs +++ b/crates/twigpine-node/tests/hf_api.rs @@ -716,7 +716,11 @@ async fn model_info_follows_main_not_repo_wide_newest(pool: sqlx::PgPool) { let sha = v["sha"] .as_str() .or_else(|| v["branches"][0]["targetCommit"].as_str()); - assert_eq!(sha, Some(on_main.commit.as_str()), "{path} must follow main"); + assert_eq!( + sha, + Some(on_main.commit.as_str()), + "{path} must follow main" + ); } node.shutdown().await; From d7ab37f624a2d60d52da674c8024d6a12996468e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:17:27 -0600 Subject: [PATCH 11/14] fix(cli): read the Arweave anchor-discovery reply through read_json model fetch parsed the gateway's GraphQL page with r.json() after a status check, which the no_parse_before_status gate rejects and which left the body uncapped. The read now goes through read_json (status-first, capped, sanitized); a failed page still ends discovery as before. --- crates/twigpine-cli/src/model.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 4f02343c..ff10478a 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -1197,15 +1197,16 @@ async fn discover_release_anchors( "query": ANCHOR_DISCOVERY_QUERY, "variables": { "repo": repo, "cursor": after }, }); - let response = match net + let response: Option = match net .client .post(format!("{}/graphql", net.ag)) .json(&gql_body) .send() .await { - Ok(r) if r.status().is_success() => r.json::().await.ok(), - _ => None, + // Status-first, capped, sanitized: the gateway is untrusted text. + Ok(r) => read_json(r, "anchor discovery").await.ok(), + Err(_) => None, }; let value = match response { Some(v) => v, From 9f2839ee28db37ca1f29489667c9e3f432f5a868 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:04:43 -0600 Subject: [PATCH 12/14] fix(cli): state the durability behavior in the publish confirm text The sibling publish branch reworded this prompt to say nothing is pinned or anchored, which is true there. Here the durability pipeline exists, so say it is permanent where IPFS and Irys are configured and node-only otherwise. --- crates/twigpine-cli/src/model.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 44033a96..38149d61 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -702,10 +702,10 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } eprintln!( - "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" + "publishing is permanent where the node has durability configured: blocks are pinned \ + to IPFS and the release anchor is posted to Arweave, and neither can be taken back. \ + With no IPFS tier and no Irys configured, the bytes stay on this node only and stay \ + available only while it keeps them" ); if !args.yes && !confirm_publish()? { println!("aborted"); From 32bc4b8323e1214ff2c4113e806e1c23414b33ce Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:28:54 -0600 Subject: [PATCH 13/14] fix(node): lowercase commit pins on HF revision lookup and correct the hf_refs doc --- crates/twigpine-node/src/api/hf.rs | 4 +-- crates/twigpine-node/tests/hf_api.rs | 40 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-node/src/api/hf.rs b/crates/twigpine-node/src/api/hf.rs index d00e16cb..ec7cbd15 100644 --- a/crates/twigpine-node/src/api/hf.rs +++ b/crates/twigpine-node/src/api/hf.rs @@ -106,7 +106,7 @@ async fn release_for_rev( if twigpine_core::cid::is_hex_oid(rev) { let rel = state .db - .model_release_by_commit(&record.id, rev) + .model_release_by_commit(&record.id, &rev.to_ascii_lowercase()) .await? .filter(|r| r.state == "published"); return Ok(rel); @@ -332,7 +332,7 @@ async fn tree_response( } /// `GET /hf/api/models/{owner}/{repo}/refs`: `main` names the newest -/// published release's commit regardless of the repo's git default branch. +/// published release on `main`, then on the repo's git default branch. /// The HF surface is defined by releases, so a repo with none answers the /// same RepoNotFound as every other endpoint. pub async fn hf_refs( diff --git a/crates/twigpine-node/tests/hf_api.rs b/crates/twigpine-node/tests/hf_api.rs index fe7fd851..5e66d53d 100644 --- a/crates/twigpine-node/tests/hf_api.rs +++ b/crates/twigpine-node/tests/hf_api.rs @@ -726,6 +726,46 @@ async fn model_info_follows_main_not_repo_wide_newest(pool: sqlx::PgPool) { node.shutdown().await; } +/// A commit pin spelled in uppercase hex resolves to the same release: +/// stored shas are lowercase, so the pin is lowercased before lookup. +#[sqlx::test] +async fn revision_accepts_uppercase_commit_pin(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(28); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "m", true).await; + let fx = seed_release( + &node, + &pool, + &owner_did, + &signing, + &repo_id, + "m", + &[("config.json", GIT_FILE)], + &[], + "main", + ) + .await; + + let upper = fx.commit.to_ascii_uppercase(); + assert_ne!(upper, fx.commit, "fixture commit has no a-f letters"); + let resp = client + .get(format!( + "{}{}", + node.base_url, + rev_path(&owner_did, "m", &upper) + )) + .send() + .await + .expect("send"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("rev json"); + assert_eq!(v["sha"].as_str(), Some(fx.commit.as_str())); + + node.shutdown().await; +} + /// A plain git commit after the release does not move HF `main`: refs and /// model info still name the release commit. #[sqlx::test] From df3799b135989e2322eb99a6ae43f135d0acd39e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:54:48 -0600 Subject: [PATCH 14/14] fix(cli): accept uppercase hex in model fetch --revision --- crates/twigpine-cli/src/model.rs | 2 +- crates/twigpine-cli/tests/model_fetch.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 38149d61..153fae80 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -1355,7 +1355,7 @@ async fn verify_candidate( )); } if let Some(want) = revision { - if anchor.release_commit != want { + if !anchor.release_commit.eq_ignore_ascii_case(want) { return skip(format!( "anchor names commit {}, expected {want}", anchor.release_commit diff --git a/crates/twigpine-cli/tests/model_fetch.rs b/crates/twigpine-cli/tests/model_fetch.rs index b47d7bca..97913905 100644 --- a/crates/twigpine-cli/tests/model_fetch.rs +++ b/crates/twigpine-cli/tests/model_fetch.rs @@ -286,6 +286,23 @@ async fn fetch_rebuilds_git_and_chunked_files_byte_identically() { } } +#[tokio::test] +async fn fetch_revision_pin_is_case_insensitive() { + let owner = Keypair::generate(); + let release = build_release(&owner); + let rec_sha = sha256_hex(&release.rec_bytes); + let anchor = anchor_json(&release, &release.did, &release.signing, &rec_sha); + let server = serve(&[("tx-good", anchor)], &release.objects).await; + + let out = TempDir::new().unwrap(); + let mut a = args(&server.url(), &release.did, &out); + a.revision = Some(COMMIT.to_uppercase()); + let report = fetch_model(&a).await.unwrap(); + + assert_eq!(report.release_commit, COMMIT); + assert_eq!(report.anchor_tx, "tx-good"); +} + #[tokio::test] async fn anchor_naming_a_different_owner_did_is_skipped() { let owner = Keypair::generate();