diff --git a/.env.example b/.env.example index 17a96959..8956926c 100644 --- a/.env.example +++ b/.env.example @@ -488,8 +488,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 @@ -499,6 +500,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/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/README.md b/README.md index 33eea9bb..db277983 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_WRITE_LOCK_HOLD_TIMEOUT_SECS` | Max seconds a repo write guard may hold its advisory-lock pool connection, measured from lock-take. One deadline covers every phase under the lock: the under-lock refresh, the caller's under-lock work (for a push, the whole `receive-pack` subprocess, clamped to the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), and the release-side upload/unlock. It bounds the lock-pool slot's hold, so a slow push cannot starve other writers for the sum of every per-phase bound. It does not bound the acquire-side lock wait (`TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS`), post-git outcome bookkeeping, the few seconds the detached reaper holds the session while the git process group dies, or merge writes, which take their guards without this deadline: their git runs unbounded under the lock, and their refresh, publish and unlock keep their own bounds, so a slow merge is never rolled back for overrunning it. Issue writes keep the deadline: an expired one refuses the write before the ref is touched, and a create's git is clamped to it, but a close's git runs unbounded once started. Unset, the effective bound is `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` itself (600 by default), tracking the git budget; set it only to tighten the hold below the git budget. An explicit value above `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` is rejected at boot. | 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..74303179 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( @@ -142,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 4ad197db..153fae80 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, } } @@ -274,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 { @@ -309,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(); @@ -456,7 +532,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('@') @@ -467,8 +543,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())) } @@ -626,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"); @@ -1011,6 +1087,747 @@ 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: Option = match net + .client + .post(format!("{}/graphql", net.ag)) + .json(&gql_body) + .send() + .await + { + // 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, + 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 +} + +/// 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 +/// a warning plus `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)> { + 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 + }; + 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)); + } + // 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. + 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) + || !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}", + 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.eq_ignore_ascii_case(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}"))?; + 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), + 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 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, + 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 /")?; + // 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 + .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 + ) + })?; + 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}"), + 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(|| { + // `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 + .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 + ) + })?; + if !url_path_safe(cid) { + bail!("{}: block map CID is not URL-safe", file.path); + } + 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 {}", + 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 + ); + 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..97913905 --- /dev/null +++ b/crates/twigpine-cli/tests/model_fetch.rs @@ -0,0 +1,482 @@ +//! 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 = "aaaabbbbccccddddeeeeffff0000111122223333"; +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 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(); + 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()); +} + +#[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-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/Cargo.toml b/crates/twigpine-node/Cargo.toml index acf6097c..d592802a 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -33,6 +33,16 @@ 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"] + +[[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" @@ -119,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/api/hf.rs b/crates/twigpine-node/src/api/hf.rs new file mode 100644 index 00000000..ec7cbd15 --- /dev/null +++ b/crates/twigpine-node/src/api/hf.rs @@ -0,0 +1,568 @@ +//! 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 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. +//! +//! 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). +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"); + +/// 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], + owner: &str, + name: &str, +) -> Result<(), AppError> { + if require_fully_public(record, rules).is_err() { + // 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(()) +} + +/// Resolve the HF revision to a published release row. +/// +/// 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 twigpine_core::cid::is_hex_oid(rev) { + let rel = state + .db + .model_release_by_commit(&record.id, &rev.to_ascii_lowercase()) + .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, + // HF's pointerSize is the pointer file's byte size + // (a fixed ~130), not the object's. + "pointerSize": 130, + }); + } + if f.format == FileFormat::Pickle { + e["unsafe"] = json!(true); + } + out.push(e); + } + out +} + +/// `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)>, + 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, &owner, &name)?; + 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?; + 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, &owner, &name)?; + 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, &owner, &name)?; + 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, &owner, &name)?; + 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 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( + 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, &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})]; + 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` 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)>, + 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, &owner, &name)?; + 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.strip_prefix('"') + .and_then(|x| x.strip_suffix('"')) + .unwrap_or(t) + == 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. 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 + .clone() + .acquire_owned() + .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}")))?; + let stream = serve::slices_stream(store, slices); + Body::from_stream(futures::StreamExt::map(stream, move |item| { + let _held = &permit; + item + })) + } + }; + + 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 d7db08a1..9315ab95 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 @@ -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), 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 59084b4f..bbaad0fa 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1052,6 +1052,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 4779b787..e0ab94f2 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -824,6 +824,300 @@ 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. + /// 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 + 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)) + } + + /// 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: &[(&str, &str)], + ) -> Result { + if jobs.is_empty() { + return Ok(0); + } + 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 + (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 AND state = 'pending' + RETURNING attempts", + ) + .bind(id) + .bind(err) + .bind(ts_now()) + .fetch_optional(&self.pool) + .await? + .unwrap_or(0)) + } + + /// 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 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(&format!( + "SELECT COUNT(*) FILTER (WHERE state = 'pending'), + COUNT(*) FILTER (WHERE state = 'failed') + FROM model_durability_jobs + WHERE release_id = $1 AND kind {pred} $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 `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( + &self, + release_id: i64, + kind: &str, + ) -> Result<(i64, i64)> { + self.model_durability_counts(release_id, kind, "<>").await + } + + /// (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/lib.rs b/crates/twigpine-node/src/lib.rs index d9cc9243..a017646d 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -638,8 +638,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 @@ -664,6 +672,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". @@ -922,12 +933,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()))); + 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 @@ -1788,6 +1798,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| { [ @@ -1802,6 +1813,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/claim.rs b/crates/twigpine-node/src/models/claim.rs index 45abb9c2..74aacfa6 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 new file mode 100644 index 00000000..dfdad6db --- /dev/null +++ b/crates/twigpine-node/src/models/durability.rs @@ -0,0 +1,1143 @@ +//! 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` 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. +//! +//! 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::db::RepoRecord; +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; + +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 +/// 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 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())); + 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, release.commit_sha.as_str())); + jobs.push((KIND_ANCHOR, release.commit_sha.as_str())); + 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 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); + } + // mirror-rows-handled: require_fully_public fails closed on slash-form + // (mirror) ids, whose publicity pair is vacuous, so a mirror row stops + // its own jobs the same way a private canonical repo does. + 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 +/// 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(()); + } + } + _ => {} + } + + 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") + .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(), &record).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), +} + +/// 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, + // `capture` yields None only when the epoch read failed; fail + // closed like `is_current` does on a read failure. + None => false, + } +} + +/// 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>, + record: &RepoRecord, +) -> 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.git_bin, record, 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 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.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(); + for file in manifest + .files + .iter() + .filter(|f| f.storage == twigpine_core::model::manifest::StorageKind::Git) + { + 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)); + } + JobOutcome::Deferred => return Ok(JobOutcome::Deferred), + } + } + let payload = serde_json::json!({ + "schema": "gitlawb/model-block-map/v1", + "release": release.commit_sha, + "blocks": blocks, + "files": files, + }); + 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, record).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( + git_bin: &str, + record: &RepoRecord, + release: &crate::models::ReleaseRow, + path: &str, +) -> Result, AppError> { + git_show( + 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 !fence_current(fence).await { + return Ok(JobOutcome::Deferred); + } + let kubo = crate::ipfs_pin::pin_git_object( + &state.config.ipfs_api, + object_key, + data, + Some(Duration::from_secs(120)), + ) + .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, + &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>, + record: &RepoRecord, +) -> 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_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.git_bin, record, release, SIG_PATH).await?) + .map_err(|_| AppError::Internal(anyhow::anyhow!("model-release.sig is not utf-8")))?; + + if !fence_current(fence).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","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(); + + 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; + } + + /// 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. + #[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","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); + + 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..681ed3ec 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; @@ -27,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/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..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() @@ -323,7 +321,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..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), @@ -236,8 +249,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)), } } @@ -247,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 @@ -255,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 @@ -281,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, @@ -402,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/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 0d8cb5db..885669e2 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..5e66d53d --- /dev/null +++ b/crates/twigpine-node/tests/hf_api.rs @@ -0,0 +1,1188 @@ +//! 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(); + // 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,$8) + RETURNING id", + ) + .bind(repo_id) + .bind(commit) + .bind(branch) + .bind(publisher_did) + .bind(manifest_sha) + .bind(rec_sha) + .bind(&created) + .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())); + 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") + .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)); + + // 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; +} + +/// 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; +} + +/// 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 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] +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; +} + +/// `/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); + + 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 + (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, repo_id) in [("priv", &priv_id), ("ruled", &ruled_id)] { + 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, + // {owner}/{name} exactly as spelled, never the internal id. + 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(&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}" + ); + } + } + } + + node.shutdown().await; +} 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}" + ); +} diff --git a/docs/MODEL-HOSTING.md b/docs/MODEL-HOSTING.md new file mode 100644 index 00000000..6f34b454 --- /dev/null +++ b/docs/MODEL-HOSTING.md @@ -0,0 +1,139 @@ +# 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): 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. +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_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. | + +## 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 `/` 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="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. + +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. + +### 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='/')"` (`` 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. diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 0a23de3e..06769812 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -286,12 +286,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). @@ -301,6 +305,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 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