diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 4000275d..82cb35d3 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -236,7 +236,7 @@ jobs: - name: cargo test (real-node deny harness) env: DATABASE_URL: postgres://postgres:postgres@localhost:5432/gitlawb_test - run: cargo test --locked -p twigpine-node --features test-harness --lib --test deny_harness + run: cargo test --locked -p twigpine-node --features test-harness --lib --test deny_harness --test models_api build-release: name: build --release diff --git a/crates/twigpine-cli/Cargo.toml b/crates/twigpine-cli/Cargo.toml index d39d025e..b844b079 100644 --- a/crates/twigpine-cli/Cargo.toml +++ b/crates/twigpine-cli/Cargo.toml @@ -41,8 +41,9 @@ alloy = { version = "1", default-features = false, features = [ "rpc-types-eth", ] } +ed25519-dalek = { workspace = true } + [dev-dependencies] mockito = "1" tempfile = "3" tokio = { workspace = true } -ed25519-dalek = { workspace = true } diff --git a/crates/twigpine-cli/src/http.rs b/crates/twigpine-cli/src/http.rs index 309b0d10..a2dda070 100644 --- a/crates/twigpine-cli/src/http.rs +++ b/crates/twigpine-cli/src/http.rs @@ -314,6 +314,25 @@ impl NodeClient { self.send_signed("PUT", path, body).await } + /// PUT raw bytes with no signature and caller-supplied extra headers. + /// Used only for the model block upload, where the session id IS the + /// bearer credential and the body is too large to buffer for signing. + /// Content-Length is set by reqwest from the body, which the route + /// requires. Every other write goes through `put`/`post`/`delete`. + pub async fn put_unsigned( + &self, + path: &str, + body: Vec, + headers: &[(&str, &str)], + ) -> Result { + let url = format!("{}{}", self.node_url, path); + let mut req = self.inner.put(&url).body(body); + for (name, value) in headers { + req = req.header(*name, *value); + } + req.send().await.with_context(|| format!("PUT {url}")) + } + /// DELETE with RFC 9421 signing + transparent iCaptcha solve/retry. pub async fn delete(&self, path: &str, body: &[u8]) -> Result { self.send_signed("DELETE", path, body).await diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index 13696231..9f1dc2e0 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -16,6 +16,7 @@ mod ipfs_cmd; mod issue; mod mcp; mod mirror; +mod model; mod name; mod node; mod node_stake; @@ -140,6 +141,12 @@ enum Commands { /// Print your current identity (DID) and optional node info Whoami(whoami::WhoamiArgs), + + /// Publish open-weight model releases + Model { + #[command(subcommand)] + cmd: model::ModelCmd, + }, } /// The command was `gl` before the rename and still answers to it. Say so @@ -236,6 +243,7 @@ async fn run() -> Result<()> { Commands::Bounty(args) => bounty::run(args).await, Commands::Ucan(args) => ucan_cmd::run(args).await, Commands::Whoami(args) => whoami::run(args).await, + Commands::Model { cmd } => model::run(cmd).await, } } diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs new file mode 100644 index 00000000..2db52e96 --- /dev/null +++ b/crates/twigpine-cli/src/model.rs @@ -0,0 +1,1626 @@ +//! `twigpine model` — open-weight model publishing (KTD14). +//! +//! `twigpine model publish` runs inside a local clone of a fully public +//! Twigpine repo: it classifies files by the chunking threshold, packs the +//! large ones into content blocks with cross-release dedup, uploads the new +//! blocks under an upload session (resuming from a `.git` state file after an +//! interruption), commits the signed manifest, pushes, claims the release, +//! and polls until the node's verification publishes or rejects it. If the +//! release is still verifying when the poll budget expires, the command +//! exits non-zero with the status URL to check later. + +use anyhow::{bail, Context, Result}; +use clap::{Args, Subcommand}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Output; +use std::time::{Duration, Instant}; + +use twigpine_core::cid::sha256_hex; +use twigpine_core::model::manifest::{ + self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, + MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{ + pack_file_with, BlockEntry, DedupIndex, Reconstruction, +}; + +use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; +use crate::identity::load_keypair_from_dir; + +const DEFAULT_CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024; +const SESSION_HEADER: &str = "x-twigpine-model-session"; +const STATE_FILE_NAME: &str = "twigpine-model-publish.json"; +const GITIGNORE_BEGIN: &str = "# >>> twigpine-model-publish >>>"; +const GITIGNORE_END: &str = "# <<< twigpine-model-publish <<<"; +/// huggingface_hub 2.x refuses plain downloads of a single file past this. +const SINGLE_FILE_WARN_BYTES: u64 = 50 << 30; +/// Bound on a fetched prior reconstruction object: big models name thousands +/// of blocks but the object is small JSON; a runaway body is not one. +const RECONSTRUCTION_FETCH_CAP: usize = 64 * 1024 * 1024; +const POLL_INTERVAL: Duration = Duration::from_secs(3); +const POLL_BUDGET: Duration = Duration::from_secs(300); + +#[derive(Subcommand)] +pub enum ModelCmd { + /// Publish the working tree as a signed model release; polls until the + /// release publishes or is rejected, exiting non-zero when it is still + /// verifying after the poll budget + Publish(PublishArgs), +} + +#[derive(Args)] +pub struct PublishArgs { + /// Node base URL (or set TWIGPINE_NODE) + #[arg( + long, + default_value = "https://node.twigpine.com", + env = "TWIGPINE_NODE" + )] + pub node: String, + /// Skip the permanence confirmation (for scripts) + #[arg(long)] + pub yes: bool, + /// Declare a parent release: /@ + #[arg(long)] + pub parent: Option, + /// License identifier recorded in the manifest + #[arg(long, default_value = "")] + pub license: String, + /// Branch to push the release commit to (default: current branch) + #[arg(long)] + pub branch: Option, + /// Chunking threshold in bytes; files at or above it are stored as + /// content blocks instead of git blobs + #[arg(long, hide = true, default_value_t = DEFAULT_CHUNK_THRESHOLD)] + pub chunk_threshold_bytes: u64, + /// Identity directory override + #[arg(long)] + pub dir: Option, +} + +pub async fn run(cmd: ModelCmd) -> Result<()> { + match cmd { + ModelCmd::Publish(a) => cmd_publish(a).await, + } +} + +// ── git helpers ───────────────────────────────────────────────────────────── + +fn git(root: &Path, args: &[&str]) -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. + let out = std::process::Command::new("git") + .args(args) + .current_dir(root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(out) +} + +fn git_lines(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect()) +} + +/// `git` with `GIT_INDEX_FILE` pointed at a dedicated index, so the release +/// commit is built from an index the user's own staging never touches. +fn git_index(root: &Path, index: &Path, args: &[&str]) -> Result { + let out = std::process::Command::new("git") + .args(args) + .current_dir(root) + .env("GIT_INDEX_FILE", index) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(out) +} + +fn git_nul(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .split('\0') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect()) +} + +/// `git log` for the release-marker path, newest first; an unborn HEAD just +/// has none. Capped: each commit costs one reconstruction fetch for dedup. +fn release_commits(root: &Path) -> Vec { + git_lines( + root, + &[ + "log", + "--format=%H", + "-n", + "8", + "--", + ".twigpine/model-release.json", + ], + ) + .unwrap_or_default() +} + +fn repo_root() -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. + let out = std::process::Command::new("git") + .args(["rev-parse", "--show-toplevel"]) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("not inside a git repository"); + } + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(PathBuf::from(text.trim())) +} + +fn git_dir(root: &Path) -> Result { + let lines = git_lines(root, &["rev-parse", "--git-dir"])?; + let dir = PathBuf::from(lines.first().context("no git dir")?); + Ok(if dir.is_absolute() { + dir + } else { + root.join(dir) + }) +} + +/// Parse a `twigpine:///` (or `gitlawb://`) remote URL. +fn parse_remote_url(url: &str) -> Option<(String, String)> { + let rest = twigpine_core::url_scheme::strip_scheme(url.trim())?; + let slash = rest.rfind('/')?; + let did = rest[..slash].to_string(); + let repo = twigpine_core::ucan::push::canonical_repo_name(&rest[slash + 1..]).to_string(); + if did.is_empty() || repo.is_empty() { + return None; + } + Some((did, repo)) +} + +/// The remote name plus (owner did, repo) of the first remote carrying a +/// twigpine URL: origin first, then twigpine/gitlawb, then any other. +fn detect_remote(root: &Path) -> Result<(String, String, String)> { + let names = git_lines(root, &["remote"])?; + let preferred = ["origin", "twigpine", "gitlawb"]; + let ordered = preferred + .iter() + .filter(|p| names.iter().any(|n| n == *p)) + .map(|p| p.to_string()) + .chain( + names + .iter() + .filter(|n| !preferred.contains(&n.as_str())) + .cloned(), + ); + for name in ordered { + for extra in [&["--all"][..], &["--push", "--all"][..]] { + let mut args = vec!["remote", "get-url"]; + args.extend_from_slice(extra); + args.push(&name); + let Ok(urls) = git_lines(root, &args) else { + continue; + }; + if let Some((did, repo)) = urls.iter().find_map(|u| parse_remote_url(u)) { + // The push must land on the repo the session and claim calls + // use: a push URL naming a different twigpine repo is an + // ambiguous destination, not a slow failure after upload. + let push_urls = git_lines(root, &["remote", "get-url", "--push", "--all", &name]) + .unwrap_or_default(); + for u in &push_urls { + if let Some((pdid, prepo)) = parse_remote_url(u) { + if pdid != did || prepo != repo { + bail!( + "remote {name} pushes to {pdid}/{prepo} but fetches from \ + {did}/{repo}; fix the remote's push URL and retry" + ); + } + } + } + return Ok((name, did, repo)); + } + } + } + bail!("no twigpine:// (or gitlawb://) remote found; run inside a clone of the repo") +} + +// ── file classification ───────────────────────────────────────────────────── + +#[derive(Debug, PartialEq, Eq)] +enum Class { + /// Listed in the manifest with `storage: "git"` and committed. + Git, + /// Listed with `storage: "chunked"`, packed into blocks, gitignored. + Chunked, + /// At or over the threshold but git-tracked: refused (weights live + /// outside git). + LargeTracked, + /// Untracked and ignored, so not part of the publishable set. + Ignored, +} + +/// The publishable set is git's own view of the tree: tracked files plus +/// untracked files that are not ignored. An ignored file only comes back in +/// at threshold size and only while it sits inside the managed .gitignore +/// block, which is how previously published chunked paths stay findable on +/// re-publish without sweeping ignored junk (a `target/` dir) into a release. +fn classify(size: u64, tracked: bool, ignored: bool, managed: bool, threshold: u64) -> Class { + if size >= threshold { + if tracked { + Class::LargeTracked + } else if ignored && !managed { + Class::Ignored + } else { + Class::Chunked + } + } else if ignored { + Class::Ignored + } else { + Class::Git + } +} + +struct Scan { + /// Repo-relative paths committed as git blobs. + git_files: Vec, + /// Repo-relative paths packed as content blocks. + chunked_files: Vec, + /// Tracked files at or over the threshold: the refusal list. + refused: Vec, + /// Ignored files at or over the threshold that are not managed: warned + /// and skipped (see [`classify`]). + skipped_ignored: Vec, + /// Tracked paths gone from the worktree but not staged for deletion: + /// staged into the release commit without entering the manifest. + deleted: Vec, +} + +/// Tracked paths from `git ls-files -s`, minus submodule gitlinks (mode +/// 160000): a gitlink has no blob to hash and is not a manifest file. +fn tracked_paths(root: &Path) -> Result> { + let entries = git_nul(root, &["ls-files", "-s", "-z"])?; + let mut out = HashSet::new(); + for e in entries { + let Some((meta, name)) = e.split_once('\t') else { + continue; + }; + if meta.starts_with("160000 ") { + continue; + } + out.insert(name.to_string()); + } + Ok(out) +} + +/// Paths listed inside the managed .gitignore block (empty when there is no +/// block): previously published chunked files. +/// One repo-relative path as a gitignore pattern line: anchored at the repo +/// root so it matches only this path, with pattern metacharacters and a +/// trailing space backslash-escaped. +fn escape_gitignore_path(p: &str) -> String { + let mut out = String::from("/"); + let mut chars = p.chars().peekable(); + while let Some(c) = chars.next() { + if matches!(c, '\\' | '!' | '#' | '[' | ']' | '*' | '?') { + out.push('\\'); + } + if c == ' ' && chars.peek().is_none() { + out.push('\\'); + } + out.push(c); + } + out +} + +fn unescape_gitignore_path(line: &str) -> String { + // Generated patterns are root-anchored; older unanchored blocks decode + // unchanged either way. + let line = line.strip_prefix('/').unwrap_or(line); + let mut out = String::new(); + let mut escaped = false; + for c in line.chars() { + if escaped { + out.push(c); + escaped = false; + } else if c == '\\' { + escaped = true; + } else { + out.push(c); + } + } + out +} + +fn managed_block_paths(gitignore: &str) -> Vec { + let mut inside = false; + let mut out = Vec::new(); + for line in gitignore.lines() { + let t = line.trim_end(); + if t == GITIGNORE_BEGIN { + inside = true; + continue; + } + if t == GITIGNORE_END { + break; + } + if inside && !t.is_empty() { + out.push(unescape_gitignore_path(t)); + } + } + out +} + +fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { + let tracked = tracked_paths(root)?; + let others = git_nul(root, &["ls-files", "--others", "-z"])?; + let unignored: HashSet = + git_nul(root, &["ls-files", "--others", "--exclude-standard", "-z"])? + .into_iter() + .collect(); + let managed: HashSet = managed_block_paths(gitignore).into_iter().collect(); + + let mut scan = Scan { + git_files: Vec::new(), + chunked_files: Vec::new(), + refused: Vec::new(), + skipped_ignored: Vec::new(), + deleted: Vec::new(), + }; + let mut consider = |path: &str, is_tracked: bool| { + if path.starts_with(".twigpine/") { + return; // release metadata is never a manifest file + } + // A path that vanished between listing and stat is not publishable; + // a tracked one records an unstaged deletion the commit must carry + // so the released tree drops the file too. + let meta = match std::fs::symlink_metadata(root.join(path)) { + Ok(m) => m, + Err(_) => { + if is_tracked { + scan.deleted.push(path.to_string()); + } + return; + } + }; + if !meta.is_file() && !meta.file_type().is_symlink() { + return; + } + let ignored = !is_tracked && !unignored.contains(path); + match classify( + meta.len(), + is_tracked, + ignored, + managed.contains(path), + threshold, + ) { + Class::Git => scan.git_files.push(path.to_string()), + Class::Chunked => scan.chunked_files.push(path.to_string()), + Class::LargeTracked => scan.refused.push(path.to_string()), + Class::Ignored => { + if meta.len() >= threshold { + scan.skipped_ignored.push(path.to_string()); + } + } + } + }; + + for p in &tracked { + consider(p, true); + } + for p in &others { + if tracked.contains(p) { + continue; + } + consider(p, false); + } + scan.git_files.sort(); + scan.chunked_files.sort(); + scan.refused.sort(); + scan.skipped_ignored.sort(); + scan.deleted.sort(); + Ok(scan) +} + +// ── .gitignore managed block ──────────────────────────────────────────────── + +/// Insert or replace the managed block so it lists exactly `paths`; an empty +/// list removes the block. Idempotent: rewriting the same list yields the +/// same file content. +fn upsert_managed_block(existing: &str, paths: &[String]) -> String { + let mut out: Vec = existing.lines().map(str::to_string).collect(); + if let Some(b) = out.iter().position(|l| l.trim_end() == GITIGNORE_BEGIN) { + let end = out[b + 1..] + .iter() + .position(|l| l.trim_end() == GITIGNORE_END) + .map(|e| b + 1 + e) + .unwrap_or(out.len() - 1); + out.drain(b..=end); + // The blank line we insert before the block goes with it. + if b > 0 && out.get(b - 1).is_some_and(|l| l.is_empty()) { + out.remove(b - 1); + } + } + if !paths.is_empty() { + if !out.is_empty() && !out.last().is_some_and(|l| l.is_empty()) { + out.push(String::new()); + } + out.push(GITIGNORE_BEGIN.to_string()); + out.extend(paths.iter().map(|p| escape_gitignore_path(p))); + out.push(GITIGNORE_END.to_string()); + } + let mut s = out.join("\n"); + if !s.is_empty() { + s.push('\n'); + } + s +} + +// ── resume state ──────────────────────────────────────────────────────────── + +#[derive(Debug, Default, Serialize, Deserialize, PartialEq)] +struct PublishState { + session_id: String, + uploaded: Vec, +} + +fn load_state(path: &Path) -> PublishState { + let Ok(text) = std::fs::read_to_string(path) else { + return PublishState::default(); + }; + serde_json::from_str(&text).unwrap_or_default() +} + +/// Rewrite the state file after each uploaded block: the file carries the +/// resume set, so it is written and fsync'd rather than left in page cache. +fn save_state(path: &Path, state: &PublishState) -> Result<()> { + let bytes = serde_json::to_vec(state)?; + // The file holds the session bearer, so it goes through the owner-only + // writer, then is fsync'd (the helper does not sync). + crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; + std::fs::OpenOptions::new() + .write(true) + .open(path)? + .sync_all()?; + Ok(()) +} + +// ── misc ──────────────────────────────────────────────────────────────────── + +/// `/@<40-hex commit>` -> ((owner, name), commit). +fn parse_parent(spec: &str) -> Result<((String, String), String)> { + let (repo, commit) = spec + .rsplit_once('@') + .context("parent must be /@")?; + let (owner, name) = repo + .split_once('/') + .context("parent must be /@")?; + if owner.is_empty() || name.is_empty() || name.contains('/') { + bail!("parent must be /@"); + } + if commit.len() != 40 || !commit.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("parent commit must be a 40-hex sha"); + } + Ok(((owner.to_string(), name.to_string()), commit.to_string())) +} + +fn read_head(path: &Path, n: u64) -> Result> { + let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; + let mut buf = Vec::new(); + f.take(n).read_to_end(&mut buf)?; + Ok(buf) +} + +/// Point the real index's entries for the released paths back at HEAD. The +/// release commit is built under a dedicated index, so without this the +/// user's index still holds the old HEAD tree and every released path shows +/// as a staged reversion the next plain commit would apply. Entries for +/// paths not listed are untouched. +fn sync_index_to_head(root: &Path, git_dir: &Path, paths: &[String]) -> Result<()> { + if paths.is_empty() { + return Ok(()); + } + let spec_path = git_dir.join("twigpine-model-reset-pathspec"); + { + let mut spec = Vec::new(); + for p in paths { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + std::fs::write(&spec_path, spec)?; + } + let res = git( + root, + &[ + "--literal-pathspecs", + "reset", + "-q", + "HEAD", + &format!("--pathspec-from-file={}", spec_path.display()), + "--pathspec-file-nul", + ], + ); + let _ = std::fs::remove_file(&spec_path); + res.map(|_| ()) +} + +/// Bytes of the blob staged for `path` in the dedicated release index: +/// exactly what the release commit will store, filters and symlink handling +/// included. +fn staged_blob(root: &Path, index: &Path, path: &str) -> Result> { + // Resolve the blob sha through the index rather than `:{path}` revspec + // syntax: a path that opens with magic characters is parsed as revspec + // there, not as a filename. Literal pathspecs keep a path that LOOKS + // like magic from resolving to a different entry. + let out = git_index( + root, + index, + &["--literal-pathspecs", "ls-files", "-s", "-z", "--", path], + )?; + let stdout = String::from_utf8(out.stdout).context("ls-files output was not utf-8")?; + // ` \t`: require the returned entry to name the + // exact path asked for, so a resolution surprise fails loudly. + let (meta, name) = stdout + .trim_end_matches('\0') + .split_once('\t') + .with_context(|| format!("{path} is not staged in the index"))?; + if name != path { + bail!("{path} resolved to a different index path: {name}"); + } + let sha = meta + .split(' ') + .nth(1) + .filter(|s| !s.is_empty()) + .with_context(|| format!("{path} is not staged in the index"))?; + Ok(git(root, &["cat-file", "blob", sha])?.stdout) +} + +/// Fetch a prior release's reconstruction object for dedup. A 404 means the +/// commit never became a published release (or its repo stopped serving); +/// any other non-2xx surfaces the node's own body. +async fn fetch_reconstruction( + client: &NodeClient, + owner: &str, + name: &str, + commit: &str, +) -> Result> { + let path = format!("/api/v1/repos/{owner}/{name}/models/releases/{commit}/reconstruction"); + let resp = client + .get_signed(&path) + .await + .context("reconstruction fetch failed")?; + let status = resp.status(); + if status == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !status.is_success() { + let capped = read_body_capped_bytes(resp, 8 * 1024).await; + bail!( + "reconstruction fetch for {commit} failed ({status}): {}", + crate::http::sanitize_node_msg(&String::from_utf8_lossy(&capped.bytes)) + ); + } + let capped = read_body_capped_bytes(resp, RECONSTRUCTION_FETCH_CAP).await; + if capped.truncated || capped.read_failed { + bail!("reconstruction object for {commit} was oversized or truncated"); + } + let rec = Reconstruction::parse(&capped.bytes) + .map_err(|e| anyhow::anyhow!("reconstruction object for {commit} is invalid: {e}"))?; + Ok(Some(rec)) +} + +/// Send one content block to the session. Unsigned by protocol: the session +/// id is the bearer credential. A non-2xx body is surfaced through +/// `read_json`'s denial path. +async fn upload_block( + client: &NodeClient, + base: &str, + session_id: &str, + sha: &str, + data: Vec, +) -> Result<()> { + let resp = client + .put_unsigned( + &format!("{base}/models/blocks/{sha}"), + data, + &[(SESSION_HEADER, session_id)], + ) + .await?; + let _: Value = read_json(resp, "block upload").await?; + Ok(()) +} + +/// The failure `cmd_publish` returns when the release is still `verifying` +/// at the poll budget: a non-zero exit that keeps the status URL visible. +fn still_verifying_error(release_id: i64, budget_secs: u64, release_path: &str) -> anyhow::Error { + anyhow::anyhow!( + "release {release_id} is still verifying after {budget_secs}s; its status is at\n \ + GET {release_path}" + ) +} + +/// Without `--yes`, publishing requires an explicit "yes" on stdin. Any +/// other answer, including EOF on a pipe, declines. +fn confirm_publish() -> Result { + eprint!("type 'yes' to publish: "); + let _ = std::io::stderr().flush(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line)?; + Ok(line.trim().eq_ignore_ascii_case("yes")) +} + +// ── publish ───────────────────────────────────────────────────────────────── + +async fn cmd_publish(args: PublishArgs) -> Result<()> { + let kp = load_keypair_from_dir(args.dir.as_deref())?; + let root = repo_root()?; + let git_dir = git_dir(&root)?; + let (remote_name, owner, name) = detect_remote(&root)?; + let branch = match &args.branch { + Some(b) => b.clone(), + None => { + // allow-unbounded-git: short-lived CLI process; there is no + // request permit to hold or client disconnect to outlive. + let out = std::process::Command::new("git") + .args(["symbolic-ref", "--short", "-q", "HEAD"]) + .current_dir(&root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("detached HEAD: pass --branch to name the release branch"); + } + String::from_utf8(out.stdout) + .context("branch name was not utf-8")? + .trim() + .to_string() + } + }; + + // 1. Scan and refuse tracked large files before anything else happens. + let gitignore_path = root.join(".gitignore"); + let existing_gitignore = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); + let scan = scan_files(&root, &existing_gitignore, args.chunk_threshold_bytes)?; + if !scan.refused.is_empty() { + bail!( + "these files are {} bytes or larger but tracked in git; weights must live \ + outside git. Remove them from the index first (git rm --cached):\n {}", + args.chunk_threshold_bytes, + scan.refused.join("\n ") + ); + } + for p in &scan.skipped_ignored { + eprintln!( + "warning: {p} is at or over the chunk threshold but gitignored; \ + unignore it to publish" + ); + } + + // 2. Warn + confirm: publishing is permanent. + println!("Publishing {owner}/{name} as a model release on branch {branch}:"); + println!( + " {} git files, {} chunked files", + scan.git_files.len(), + scan.chunked_files.len() + ); + for p in &scan.chunked_files { + let size = std::fs::symlink_metadata(root.join(p)) + .map(|m| m.len()) + .unwrap_or(0); + if size > SINGLE_FILE_WARN_BYTES { + eprintln!( + "warning: {p} is over 50 GiB; huggingface_hub refuses plain downloads that large" + ); + } + } + eprintln!( + "publishing stores the blocks in this node's configured block store and commits a \ + signed release manifest to git: the bytes stay available only while this node \ + keeps them and the repo stays readable, and nothing is pinned to IPFS or \ + anchored to Arweave" + ); + if !args.yes && !confirm_publish()? { + println!("aborted"); + return Ok(()); + } + + let client = NodeClient::new(&args.node, Some(kp.clone())); + let base = format!("/api/v1/repos/{owner}/{name}"); + + // 3. Dedup: reconstructions of prior releases in this clone, plus the + // declared parent's when given. + let mut priors: Vec = Vec::new(); + let mut parent_ref: Option = None; + let prior_commits = release_commits(&root); + for commit in &prior_commits { + if let Some(rec) = fetch_reconstruction(&client, &owner, &name, commit).await? { + priors.push(rec); + } + } + if let Some(spec) = &args.parent { + let ((powner, pname), pcommit) = parse_parent(spec)?; + let rec = fetch_reconstruction(&client, &powner, &pname, &pcommit) + .await? + .context("declared parent has no published reconstruction on this node")?; + // There is no manifest-serving route, so the parent manifest sha256 + // is the sha of the manifest bytes in the local clone when the parent + // commit is here, and the sha of the parent's reconstruction object + // (the only parent artifact the node serves) otherwise. The node + // records the field without checking it (R9: a signed claim, not a + // verified link). + let manifest_sha = git( + &root, + &["show", &format!("{pcommit}:.twigpine/model-release.json")], + ) + .map(|out| sha256_hex(&out.stdout)) + .unwrap_or_else(|_| sha256_hex(&rec.to_bytes().unwrap_or_default())); + parent_ref = Some(ParentRef { + repo: format!("{powner}/{pname}"), + commit: pcommit, + manifest_sha256: manifest_sha, + }); + priors.push(rec); + } + let prior_refs: Vec<&Reconstruction> = priors.iter().collect(); + let mut dedup = DedupIndex::from_reconstructions(&prior_refs); + let mut all_entries: HashMap = HashMap::new(); + for rec in &priors { + for b in &rec.blocks { + all_entries.insert(b.sha256.clone(), b.clone()); + } + } + + // 4. Open (or resume) the upload session before packing, so each new + // block streams out as it seals instead of buffering the whole + // model in memory. + let state_path = git_dir.join(STATE_FILE_NAME); + let mut state = load_state(&state_path); + if !state.session_id.is_empty() { + let resp = client + .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) + .await + .context("session status request failed")?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + state = PublishState::default(); + } else { + let v: Value = read_json(resp, "session status").await?; + if v["state"].as_str() != Some("open") { + state = PublishState::default(); + } + } + } + if state.session_id.is_empty() { + let body = serde_json::to_vec(&json!({}))?; + let resp = client + .post(&format!("{base}/models/sessions"), &body) + .await?; + let v: Value = json_or_denial("open model session", resp).await?; + state.session_id = v["session_id"] + .as_str() + .context("session response had no session_id")? + .to_string(); + state.uploaded.clear(); + save_state(&state_path, &state)?; + } + let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); + let session_id = state.session_id.clone(); + + // 5. Pack every chunked file; shared chunks become terms into prior + // blocks, the rest seal into new blocks uploaded as they seal. + let mut rec = Reconstruction::new(); + let mut files: Vec = Vec::new(); + for path in &scan.chunked_files { + // Pack on a blocking thread and upload each block as it seals: a + // bounded channel keeps resident memory to a couple of blocks + // rather than the whole file. The dedup index moves to the thread + // through an Arc and comes back when it finishes. + let shared_dedup = std::sync::Arc::new(std::mem::take(&mut dedup)); + let task_dedup = shared_dedup.clone(); + let (block_tx, mut block_rx) = + tokio::sync::mpsc::channel::(2); + let pack_path = path.clone(); + let pack_root = root.clone(); + let pack_task = tokio::task::spawn_blocking(move || { + let file = std::fs::File::open(pack_root.join(&pack_path)) + .map_err(|e| std::io::Error::new(e.kind(), format!("open {pack_path}: {e}")))?; + pack_file_with(&pack_path, file, &task_dedup, move |block| { + block_tx + .blocking_send(block) + .map_err(|_| std::io::Error::other("block upload channel closed")) + }) + }); + while let Some(block) = block_rx.recv().await { + let sha = block.sha256; + if uploaded.contains(&sha) { + continue; + } + upload_block(&client, &base, &session_id, &sha, block.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded block {}", &sha[..16]); + } + let (file_entry, block_entries) = pack_task + .await + .context("pack task failed")? + .with_context(|| format!("pack {path}"))?; + dedup = std::sync::Arc::try_unwrap(shared_dedup).unwrap_or_else(|a| (*a).clone()); + // Make this file's fresh chunks visible to the next file's dedup. + dedup.add_block_entries(&block_entries); + let head = read_head(&root.join(path), 64)?; + files.push(ManifestFile { + path: path.clone(), + size: file_entry.size, + sha256: file_entry.sha256.clone(), + format: detect_format(&head, path), + storage: StorageKind::Chunked, + }); + rec.files.push(file_entry); + for e in block_entries { + all_entries.insert(e.sha256.clone(), e.clone()); + rec.blocks.push(e); + } + } + // Terms into earlier blocks need those entries in this object: a reader + // resolves term.block against rec.blocks only. + // Sorted so the appended block rows (and therefore the serialized + // reconstruction object and its sha) are identical across processes on + // a retried publish. + let mut needed: Vec = rec + .files + .iter() + .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) + .collect::>() + .into_iter() + .collect(); + needed.sort(); + let mut present: HashSet = rec.blocks.iter().map(|b| b.sha256.clone()).collect(); + for sha in needed { + if present.contains(&sha) { + continue; + } + let entry = all_entries + .get(&sha) + .with_context(|| format!("term references unknown block {sha}"))?; + present.insert(entry.sha256.clone()); + rec.blocks.push(entry.clone()); + } + // A release with no chunked files has no chunked bytes to reconstruct: + // no reconstruction object, no reconstruction block. + let rec_bytes = if scan.chunked_files.is_empty() { + Vec::new() + } else { + rec.validate() + .map_err(|e| anyhow::anyhow!("reconstruction object invalid: {e}"))?; + rec.to_bytes() + .map_err(|e| anyhow::anyhow!("reconstruction serialize failed: {e}"))? + }; + let rec_sha = sha256_hex(&rec_bytes); + + // 6. The reconstruction object goes up as one more content block. + let has_rec = !rec_bytes.is_empty(); + let rec_size = rec_bytes.len() as u64; + if has_rec && !uploaded.contains(&rec_sha) { + upload_block(&client, &base, &session_id, &rec_sha, rec_bytes).await?; + state.uploaded.push(rec_sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded reconstruction object"); + } + + // 7. Managed .gitignore block. A symlink target outside the checkout is + // never written through, and edits made while blocks uploaded are + // caught against the scan snapshot rather than silently lost. + if let Ok(meta) = std::fs::symlink_metadata(&gitignore_path) { + if meta.file_type().is_symlink() { + bail!(".gitignore is a symlink; refusing to write through it"); + } + } + let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); + if new_gitignore != existing_gitignore { + let current = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); + if current != existing_gitignore { + bail!( + ".gitignore changed while blocks uploaded; re-run to publish \ + from a fresh scan" + ); + } + std::fs::write(&gitignore_path, &new_gitignore)?; + } + + // 8. Stage into a dedicated index seeded from HEAD: the release commit + // holds exactly the scanned set, the user's real index and anything + // already staged in it are never read or rewritten, and the hashed + // blobs below are the same index state the commit records. Only + // paths that exist go in the first stage; the release metadata + // follows after it is written below. + let index_path = git_dir.join("twigpine-model-index"); + let _ = std::fs::remove_file(&index_path); + if git(&root, &["rev-parse", "--verify", "-q", "HEAD"]).is_ok() { + git_index(&root, &index_path, &["read-tree", "HEAD"])?; + } else { + git_index(&root, &index_path, &["read-tree", "--empty"])?; + } + let pathspec_path = git_dir.join("twigpine-model-pathspec"); + { + let mut spec = Vec::new(); + for p in scan.git_files.iter().chain(&scan.deleted) { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + if gitignore_path.is_file() { + spec.extend_from_slice(b".gitignore"); + spec.push(0); + } + if spec.is_empty() { + let _ = std::fs::remove_file(&pathspec_path); + } else { + std::fs::write(&pathspec_path, spec)?; + } + } + if pathspec_path.exists() { + let staged = git_index( + &root, + &index_path, + &[ + "--literal-pathspecs", + "add", + "-A", + "--pathspec-file-nul", + &format!("--pathspec-from-file={}", pathspec_path.display()), + ], + ); + let _ = std::fs::remove_file(&pathspec_path); + staged?; + } + + // 9. Hash the git-stored files from the release index (the exact bytes + // the commit stores), then write and stage the manifest. + for path in &scan.git_files { + let bytes = staged_blob(&root, &index_path, path)?; + files.push(ManifestFile { + path: path.clone(), + size: bytes.len() as u64, + sha256: sha256_hex(&bytes), + format: detect_format(&bytes[..bytes.len().min(64)], path), + storage: StorageKind::Git, + }); + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner}/{name}"), + publisher_did: kp.did().to_string(), + license: args.license.clone(), + parent: parent_ref, + files, + reconstruction: if !has_rec { + None + } else { + Some(ReconstructionRef { + sha256: rec_sha, + size: rec_size, + }) + }, + }; + let manifest_bytes = manifest + .to_bytes() + .map_err(|e| anyhow::anyhow!("manifest serialize failed: {e}"))?; + let twigpine_dir = root.join(".twigpine"); + std::fs::create_dir_all(&twigpine_dir)?; + std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; + std::fs::write( + twigpine_dir.join("model-release.sig"), + format!( + "{}\n", + manifest::sign( + &ed25519_dalek::SigningKey::from_bytes(&kp.to_seed()), + &manifest_bytes, + ) + ), + )?; + git_index( + &root, + &index_path, + &[ + "--literal-pathspecs", + "add", + ".twigpine/model-release.json", + ".twigpine/model-release.sig", + ], + )?; + + // 10. Commit when the release index differs, push, and claim HEAD. + let has_changes = git_index(&root, &index_path, &["diff", "--cached", "--quiet"]).is_err(); + if has_changes { + let n = prior_commits.len() + 1; + git_index( + &root, + &index_path, + &["commit", "-m", &format!("model release {n}")], + )?; + } else { + // Nothing staged: a re-publish of identical content lands here, and + // HEAD must already be a release commit to claim. + if git( + &root, + &["cat-file", "-e", "HEAD:.twigpine/model-release.json"], + ) + .is_err() + { + bail!("nothing to publish and HEAD carries no release manifest"); + } + println!("no changes to commit; claiming the existing release commit"); + } + let _ = std::fs::remove_file(&index_path); + // The dedicated index left the real index holding the old HEAD tree: + // every released path would look staged for reversion, and the next + // plain `git commit` would undo the release. Sync exactly the released + // paths back to HEAD; unrelated staged entries keep their state. + let mut released: Vec = scan.git_files.clone(); + released.extend(scan.deleted.iter().cloned()); + if gitignore_path.is_file() || git(&root, &["cat-file", "-e", "HEAD:.gitignore"]).is_ok() { + released.push(".gitignore".to_string()); + } + released.push(".twigpine/model-release.json".to_string()); + released.push(".twigpine/model-release.sig".to_string()); + sync_index_to_head(&root, &git_dir, &released)?; + let commit = git_lines(&root, &["rev-parse", "HEAD"])? + .into_iter() + .next() + .context("no HEAD commit")?; + + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. + let push = std::process::Command::new("git") + .args(["push", &remote_name, &format!("HEAD:{branch}")]) + .current_dir(&root) + .env("TWIGPINE_NODE", &args.node) + // The helper on PATH may be a build from before the rename. + .env("GITLAWB_NODE", &args.node) + .output() + .context("failed to run git push")?; + if !push.status.success() { + bail!( + "git push failed:\n{}", + String::from_utf8_lossy(&push.stderr).trim() + ); + } + println!("pushed {commit} to {remote_name}/{branch}"); + + let claim_body = serde_json::to_vec(&json!({ + "commit": commit, + "branch": branch, + }))?; + let resp = client + .post(&format!("{base}/models/claims"), &claim_body) + .await?; + let claim: Value = json_or_denial("claim release", resp).await?; + let release_id = claim["release_id"].as_i64().unwrap_or_default(); + println!("release {release_id} claimed; verifying"); + + // 10. Poll until the verification worker settles the release. + let release_path = format!("{base}/models/releases/{commit}"); + let deadline = Instant::now() + POLL_BUDGET; + loop { + // One transport hiccup should not abort the publish; the signed + // status read is idempotent, so retry it a few times. + let resp = 'poll: { + let mut last = None; + for _ in 0..3 { + match client.get_signed(&release_path).await { + Ok(r) => break 'poll r, + Err(e) => { + last = Some(e); + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + } + return Err(last + .expect("three attempts ran") + .context("release status request failed")); + }; + let v: Value = read_json(resp, "release status").await?; + match v["state"].as_str() { + Some("published") => { + println!("published release {release_id}"); + println!(" commit: {}", v["commit"].as_str().unwrap_or(&commit)); + println!( + " manifest: {}", + v["manifest_sha256"].as_str().unwrap_or("?") + ); + let _ = std::fs::remove_file(&state_path); + return Ok(()); + } + Some("rejected") => { + bail!( + "release {release_id} rejected: {}", + v["failure_reason"].as_str().unwrap_or("unknown reason") + ); + } + _ => { + if Instant::now() >= deadline { + return Err(still_verifying_error( + release_id, + POLL_BUDGET.as_secs(), + &release_path, + )); + } + tokio::time::sleep(POLL_INTERVAL).await; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const THR: u64 = 1024; + + #[test] + fn classify_by_threshold_tracking_and_ignore() { + // Below threshold: tracked or unignored-untracked are git files. + assert_eq!(classify(THR - 1, true, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, true, false, THR), Class::Ignored); + assert_eq!(classify(THR - 1, false, true, true, THR), Class::Ignored); + // At/above threshold: tracked refuses; untracked chunks unless + // ignored outside the managed block. + assert_eq!(classify(THR, true, false, false, THR), Class::LargeTracked); + assert_eq!( + classify(THR + 1, true, true, false, THR), + Class::LargeTracked + ); + assert_eq!(classify(THR, false, false, false, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, true, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, false, THR), Class::Ignored); + } + + #[test] + fn managed_block_upsert_insert_replace_idempotent_remove() { + let base = "*.tmp\n".to_string(); + let paths = vec!["weights/a.bin".to_string(), "b.bin".to_string()]; + let once = upsert_managed_block(&base, &paths); + assert!(once.contains("*.tmp\n")); + assert!(once.contains(GITIGNORE_BEGIN)); + assert!(once.contains("/weights/a.bin\n/b.bin\n")); + assert!(once.contains(GITIGNORE_END)); + assert_eq!(once, upsert_managed_block(&once, &paths), "idempotent"); + + let replaced = upsert_managed_block(&once, &["c.bin".to_string()]); + assert!(replaced.contains("c.bin")); + assert!(!replaced.contains("a.bin")); + + let removed = upsert_managed_block(&replaced, &[]); + assert!(!removed.contains(GITIGNORE_BEGIN)); + assert_eq!(removed, "*.tmp\n"); + + let empty = upsert_managed_block("", &paths); + assert_eq!(managed_block_paths(&empty), paths); + } + + #[test] + fn a_verifying_release_past_the_budget_is_an_error() { + // The poll loop needs a live node, so the budget decision is kept + // in this pure helper: the arm it feeds must exit non-zero with the + // release id, the budget, and the status path. + let e = still_verifying_error(7, 300, "/api/v1/repos/o/r/models/releases/cc"); + let msg = e.to_string(); + assert!(msg.contains("7"), "{msg}"); + assert!(msg.contains("300"), "{msg}"); + assert!( + msg.contains("/api/v1/repos/o/r/models/releases/cc"), + "{msg}" + ); + } + + #[test] + fn managed_block_paths_reads_only_the_block() { + let text = format!("a\n{GITIGNORE_BEGIN}\nx.bin\ny.bin\n{GITIGNORE_END}\nz\n"); + assert_eq!(managed_block_paths(&text), vec!["x.bin", "y.bin"]); + assert!(managed_block_paths("nothing here\n").is_empty()); + } + + #[cfg(unix)] + #[test] + fn save_state_is_owner_only_even_over_a_loose_file() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "bearer".to_string(), + uploaded: vec![], + }; + save_state(&path, &state).unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&path), 0o600); + // A resume file left loose by an earlier run is tightened on rewrite. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + save_state(&path, &state).unwrap(); + assert_eq!(mode(&path), 0o600); + assert_eq!(load_state(&path), state); + } + + #[test] + fn publish_state_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "abc".to_string(), + uploaded: vec!["aa".into(), "bb".into()], + }; + save_state(&path, &state).unwrap(); + assert_eq!(load_state(&path), state); + assert_eq!( + load_state(&dir.path().join("missing.json")), + PublishState::default() + ); + std::fs::write(&path, "not json").unwrap(); + assert_eq!(load_state(&path), PublishState::default()); + } + + #[test] + fn parse_parent_shapes() { + let commit = "a".repeat(40); + let ((owner, name), c) = parse_parent(&format!("alice/weights@{commit}")).unwrap(); + assert_eq!( + (owner.as_str(), name.as_str(), c.as_str()), + ("alice", "weights", commit.as_str()) + ); + // A did:key owner carries colons; the split is on the LAST '@'. + let did_owner = "did:key:z6MkAbc"; + let ((owner, name), _) = parse_parent(&format!("{did_owner}/weights@{commit}")).unwrap(); + assert_eq!((owner.as_str(), name.as_str()), (did_owner, "weights")); + for bad in [ + "noslash", + "a/b@", + "a/b@cafe", + &format!("a/b/c@{commit}"), + &format!("a/b@{commit}x"), + &format!("a/b@{}", "g".repeat(40)), + ] { + assert!(parse_parent(bad).is_err(), "{bad}"); + } + } + + #[test] + fn manifest_assembly_round_trips_storage_kinds() { + // The manifest the command writes: schema v1, repo as owner/name, + // git and chunked entries sorted by path, reconstruction ref present. + let kp = twigpine_core::identity::Keypair::from_seed(&[3u8; 32]).unwrap(); + let mut files = vec![ + ManifestFile { + path: "weights.bin".to_string(), + size: 11, + sha256: "b".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Other, + storage: StorageKind::Chunked, + }, + ManifestFile { + path: "README.md".to_string(), + size: 5, + sha256: "a".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Text, + storage: StorageKind::Git, + }, + ]; + files.sort_by(|a, b| a.path.cmp(&b.path)); + let m = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "did:key:z6MkA/w".to_string(), + publisher_did: kp.did().to_string(), + license: "apache-2.0".to_string(), + parent: None, + files, + reconstruction: Some(ReconstructionRef { + sha256: "c".repeat(64), + size: 42, + }), + }; + let bytes = m.to_bytes().unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["schema"].as_str(), Some(MANIFEST_SCHEMA_V1)); + assert_eq!(v["repo"].as_str(), Some("did:key:z6MkA/w")); + assert_eq!(v["license"].as_str(), Some("apache-2.0")); + let paths: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["path"].as_str()) + .collect(); + assert_eq!(paths, ["README.md", "weights.bin"]); + let storages: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["storage"].as_str()) + .collect(); + assert_eq!(storages, ["git", "chunked"]); + let rec_sha = "c".repeat(64); + assert_eq!( + v["reconstruction"]["sha256"].as_str(), + Some(rec_sha.as_str()) + ); + } + + #[test] + fn remote_url_parses_both_schemes() { + assert_eq!( + parse_remote_url("twigpine://did:key:z6MkA/repo.git"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!( + parse_remote_url("gitlawb://did:key:z6MkA/repo"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!(parse_remote_url("https://x/y"), None); + } + + fn tgit(dir: &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() + } + + fn trepo() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + tgit(dir.path(), &["init", "-q", "-b", "main"]); + dir + } + + #[test] + fn a_push_url_naming_a_different_repo_is_rejected() { + let dir = trepo(); + tgit( + dir.path(), + &["remote", "add", "origin", "twigpine://did:key:z6MkA/aaa"], + ); + tgit( + dir.path(), + &[ + "remote", + "set-url", + "--push", + "origin", + "twigpine://did:key:z6MkB/bbb", + ], + ); + let e = detect_remote(dir.path()).unwrap_err(); + assert!(e.to_string().contains("pushes to"), "{e}"); + } + + #[test] + fn a_matching_push_url_is_accepted() { + let dir = trepo(); + tgit( + dir.path(), + &["remote", "add", "origin", "twigpine://did:key:z6MkA/aaa"], + ); + tgit( + dir.path(), + &[ + "remote", + "set-url", + "--push", + "origin", + "twigpine://did:key:z6MkA/aaa", + ], + ); + assert_eq!( + detect_remote(dir.path()).unwrap(), + ( + "origin".to_string(), + "did:key:z6MkA".to_string(), + "aaa".to_string() + ) + ); + } + + #[test] + fn managed_patterns_anchor_at_root_and_escape_wildcards() { + assert_eq!(escape_gitignore_path("a*b?.bin"), "/a\\*b\\?.bin"); + assert_eq!(escape_gitignore_path("weights.bin"), "/weights.bin"); + let text = + format!("{GITIGNORE_BEGIN}\n/weights.bin\n/experiments/weights.bin\n{GITIGNORE_END}\n"); + assert_eq!( + managed_block_paths(&text), + vec!["weights.bin", "experiments/weights.bin"] + ); + } + + #[test] + fn a_literal_pathspec_filename_resolves_its_own_blob() { + let dir = trepo(); + std::fs::write(dir.path().join(":(glob)weights*.txt"), b"magic").unwrap(); + std::fs::write(dir.path().join("weights-a.txt"), b"plain").unwrap(); + tgit( + dir.path(), + &[ + "--literal-pathspecs", + "add", + "--", + ":(glob)weights*.txt", + "weights-a.txt", + ], + ); + let index = dir.path().join(".git/index"); + assert_eq!( + staged_blob(dir.path(), &index, ":(glob)weights*.txt").unwrap(), + b"magic" + ); + assert_eq!( + staged_blob(dir.path(), &index, "weights-a.txt").unwrap(), + b"plain" + ); + } + + fn tcommit(dir: &Path, index: &Path, msg: &str) { + git_index( + dir, + index, + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + msg, + ], + ) + .unwrap(); + } + + /// After the release commit and the index sync, status must show only + /// what the user staged: no released path may linger as a staged + /// reversion the next plain commit would apply. + fn assert_only_unrelated_staged(dir: &Path) { + let status = tgit(dir, &["status", "--porcelain"]); + assert_eq!(status, "A unrelated.bin", "status"); + let staged = tgit(dir, &["diff", "--cached", "--name-status"]); + assert_eq!(staged, "A\tunrelated.bin", "diff --cached"); + } + + #[test] + fn the_release_index_leaves_user_staging_alone() { + let dir = trepo(); + std::fs::write(dir.path().join("a.txt"), b"a").unwrap(); + tgit(dir.path(), &["add", "a.txt"]); + tgit( + dir.path(), + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "init", + ], + ); + // An unrelated file staged in the real index must not ride into the + // release commit, and must still be staged afterwards. + std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); + tgit(dir.path(), &["add", "unrelated.bin"]); + let index = dir.path().join(".git").join("tmp-index"); + git_index(dir.path(), &index, &["read-tree", "HEAD"]).unwrap(); + std::fs::write(dir.path().join("b.txt"), b"b").unwrap(); + git_index(dir.path(), &index, &["add", "b.txt"]).unwrap(); + tcommit(dir.path(), &index, "rel"); + let tree = tgit(dir.path(), &["ls-tree", "--name-only", "HEAD"]); + assert!(!tree.contains("unrelated.bin"), "{tree}"); + assert!(tree.contains("b.txt"), "{tree}"); + sync_index_to_head(dir.path(), &dir.path().join(".git"), &["b.txt".to_string()]).unwrap(); + assert_only_unrelated_staged(dir.path()); + } + + #[test] + fn the_index_sync_handles_a_deleted_tracked_path() { + let dir = trepo(); + std::fs::write(dir.path().join("gone.txt"), b"x").unwrap(); + std::fs::write(dir.path().join("kept.txt"), b"y").unwrap(); + tgit(dir.path(), &["add", "gone.txt", "kept.txt"]); + tgit( + dir.path(), + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "init", + ], + ); + std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); + tgit(dir.path(), &["add", "unrelated.bin"]); + std::fs::remove_file(dir.path().join("gone.txt")).unwrap(); + let index = dir.path().join(".git").join("tmp-index"); + git_index(dir.path(), &index, &["read-tree", "HEAD"]).unwrap(); + git_index(dir.path(), &index, &["add", "-A", "gone.txt"]).unwrap(); + tcommit(dir.path(), &index, "rel"); + let tree = tgit(dir.path(), &["ls-tree", "--name-only", "HEAD"]); + assert!(!tree.contains("gone.txt"), "{tree}"); + sync_index_to_head( + dir.path(), + &dir.path().join(".git"), + &["gone.txt".to_string()], + ) + .unwrap(); + assert_only_unrelated_staged(dir.path()); + } + + #[test] + fn the_index_sync_works_on_a_repos_first_commit() { + let dir = trepo(); + std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); + tgit(dir.path(), &["add", "unrelated.bin"]); + let index = dir.path().join(".git").join("tmp-index"); + git_index(dir.path(), &index, &["read-tree", "--empty"]).unwrap(); + std::fs::write(dir.path().join("rel.txt"), b"r").unwrap(); + git_index(dir.path(), &index, &["add", "rel.txt"]).unwrap(); + tcommit(dir.path(), &index, "first release"); + sync_index_to_head( + dir.path(), + &dir.path().join(".git"), + &["rel.txt".to_string()], + ) + .unwrap(); + assert_only_unrelated_staged(dir.path()); + } + + #[test] + fn an_unstaged_tracked_deletion_is_recorded_for_staging() { + let dir = trepo(); + std::fs::write(dir.path().join("gone.txt"), b"x").unwrap(); + std::fs::write(dir.path().join("kept.txt"), b"y").unwrap(); + tgit(dir.path(), &["add", "gone.txt", "kept.txt"]); + tgit( + dir.path(), + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "init", + ], + ); + std::fs::remove_file(dir.path().join("gone.txt")).unwrap(); + let scan = scan_files(dir.path(), "", 1024).unwrap(); + assert_eq!(scan.deleted, vec!["gone.txt"]); + assert!(scan.git_files.contains(&"kept.txt".to_string())); + assert!(!scan.git_files.contains(&"gone.txt".to_string())); + } +} diff --git a/crates/twigpine-cli/tests/no_parse_before_status.rs b/crates/twigpine-cli/tests/no_parse_before_status.rs index 708498c1..f9b2bfbd 100644 --- a/crates/twigpine-cli/tests/no_parse_before_status.rs +++ b/crates/twigpine-cli/tests/no_parse_before_status.rs @@ -66,6 +66,7 @@ const CONVERTED_IN_186: &[&str] = &[ "changelog.rs", "issue.rs", "mcp.rs", + "model.rs", "peer.rs", "pr.rs", "protect.rs", diff --git a/crates/twigpine-core/src/model/chunking.rs b/crates/twigpine-core/src/model/chunking.rs index 95aa5395..64e52787 100644 --- a/crates/twigpine-core/src/model/chunking.rs +++ b/crates/twigpine-core/src/model/chunking.rs @@ -34,10 +34,25 @@ pub struct Block { pub data: Vec, } +/// A reader that retries `ErrorKind::Interrupted`: a signal interrupting +/// one read must not abort the whole pack. +struct RetryInterrupted(R); + +impl Read for RetryInterrupted { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + loop { + match self.0.read(buf) { + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + other => return other, + } + } + } +} + /// Stream a reader into content-defined chunks. Memory stays bounded by the /// maximum chunk size, never the file size. pub fn chunk_reader(reader: R) -> impl Iterator> { - StreamCDC::new(reader, CHUNK_MIN, CHUNK_AVG, CHUNK_MAX).map(|r| { + StreamCDC::new(RetryInterrupted(reader), CHUNK_MIN, CHUNK_AVG, CHUNK_MAX).map(|r| { let c = r?; Ok(Chunk { sha256: sha256_hex(&c.data), @@ -56,6 +71,39 @@ mod tests { const SEED: u64 = 0x9e3779b97f4a7c15; + /// Interrupts one read after some progress, then serves the rest of the + /// inner reader. + struct InterruptOnce { + inner: Cursor>, + left: usize, + } + + impl std::io::Read for InterruptOnce { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.left > 0 { + self.left -= 1; + return Err(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "interrupted", + )); + } + self.inner.read(buf) + } + } + + #[test] + fn an_interrupted_read_is_retried() { + let bytes = gen_bytes(1024 * 1024, SEED); + let reader = InterruptOnce { + inner: Cursor::new(bytes.clone()), + left: 1, + }; + let chunked: Vec = chunk_reader(reader).collect::>().unwrap(); + let shas: Vec<_> = chunked.iter().map(|c| c.sha256.clone()).collect(); + let expect: Vec<_> = chunk_all(&bytes).iter().map(|c| c.sha256.clone()).collect(); + assert_eq!(shas, expect); + } + fn chunk_all(bytes: &[u8]) -> Vec { chunk_reader(Cursor::new(bytes.to_vec())) .collect::>() diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index 758d9084..6a831de8 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -203,7 +203,13 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { return FileFormat::Pickle; } let lower = path.to_ascii_lowercase(); - let ext = lower.rsplit('.').next().unwrap_or(""); + // Only a '.' in the final path component makes an extension: an + // extensionless file named `bin` or `json` must not type itself. + let ext = lower + .rsplit('/') + .next() + .and_then(|name| name.rsplit_once('.').map(|(_, e)| e)) + .unwrap_or(""); // Torch/HF checkpoints are zip archives containing pickled tensors. if first_bytes.starts_with(b"PK\x03\x04") && matches!(ext, "bin" | "pt" | "pth" | "ckpt") { return FileFormat::Pickle; @@ -394,6 +400,13 @@ mod tests { detect_format(b"\x00\x01\x02", "blob.weird"), FileFormat::Other ); + // An extensionless final component has no extension, even when the + // name itself spells one. + assert_eq!(detect_format(b"PK\x03\x04z", "bin"), FileFormat::Other); + assert_eq!(detect_format(b"{\"a\":1}", "json"), FileFormat::Other); + assert_eq!(detect_format(b"PK\x03\x04z", "m.bin"), FileFormat::Pickle); + assert_eq!(detect_format(b"(dp0\n.", "m.pkl"), FileFormat::Pickle); + assert_eq!(detect_format(b"{\"a\":1}", "m.json"), FileFormat::Text); } /// Regenerate the frozen fixture (run once, deliberately): diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 51f9ad68..4f3ff392 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -186,7 +186,7 @@ impl Default for Reconstruction { /// Chunk-sha lookup over prior reconstruction objects, the dedup surface: /// a chunk whose hash a prior release already stored can be referenced by /// term instead of re-uploaded. -#[derive(Default)] +#[derive(Default, Clone)] pub struct DedupIndex { /// chunk sha256 -> (block sha256, chunk index inside that block) by_chunk: HashMap, @@ -209,7 +209,13 @@ impl DedupIndex { } pub fn add(&mut self, rec: &Reconstruction) { - for block in &rec.blocks { + self.add_block_entries(&rec.blocks); + } + + /// Index only `entries`: callers packing several files can add each + /// file's fresh block table instead of re-scanning every prior entry. + pub fn add_block_entries(&mut self, entries: &[BlockEntry]) { + for block in entries { if self.layouts.contains_key(&block.sha256) { continue; } diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index f1a5f827..acf6097c 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -28,6 +28,11 @@ name = "deny_harness" path = "tests/deny_harness.rs" required-features = ["test-harness"] +[[test]] +name = "models_api" +path = "tests/models_api.rs" +required-features = ["test-harness"] + [dependencies] twigpine-core = { path = "../twigpine-core" } async-trait = "0.1" diff --git a/crates/twigpine-node/src/api/mod.rs b/crates/twigpine-node/src/api/mod.rs index 75a560be..5d69fadd 100644 --- a/crates/twigpine-node/src/api/mod.rs +++ b/crates/twigpine-node/src/api/mod.rs @@ -13,6 +13,7 @@ pub mod events; pub mod ipfs; pub mod issues; pub mod labels; +pub mod models; pub mod peers; pub mod profiles; pub mod protect; @@ -219,6 +220,7 @@ mod authz_guard { let repos = include_str!("repos.rs"); let register = include_str!("register.rs"); let ipfs = include_str!("ipfs.rs"); + let models = include_str!("models.rs"); // (source, handler, expected gate marker) let rows: &[(&str, &str, &str)] = &[ @@ -323,6 +325,14 @@ mod authz_guard { (visibility, "remove_visibility", "require_owner("), (visibility, "list_visibility", "authorize_repo_read("), (visibility, "list_visibility", "require_owner("), + // Model hosting writes: session open and claim are owner-only + // behind the shared read gate; the unsigned block PUT read-gates + // as the session's owner. + (models, "open_model_session", "authorize_repo_read("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "authorize_repo_read("), + (models, "claim_model_release", "require_repo_owner("), + (models, "put_model_block", "authorize_repo_read("), ]; // Rows above prove each visibility handler calls authorize_repo_read and @@ -352,6 +362,8 @@ mod authz_guard { (issues, "close_issue", "did_matches("), (protect, "protect_branch", "did_matches("), (protect, "unprotect_branch", "did_matches("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "require_repo_owner("), ] { let body = fn_body(src, func); let gate = body.find("authorize_repo_read(").expect("gate marker"); @@ -1194,6 +1206,7 @@ mod tests { async fn t() { let _ = did_matches(x, y); } } (include_str!("events.rs"), "events.rs"), (include_str!("issues.rs"), "issues.rs"), (include_str!("labels.rs"), "labels.rs"), + (include_str!("models.rs"), "models.rs"), (include_str!("protect.rs"), "protect.rs"), (include_str!("pulls.rs"), "pulls.rs"), (include_str!("replicas.rs"), "replicas.rs"), diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs new file mode 100644 index 00000000..01766919 --- /dev/null +++ b/crates/twigpine-node/src/api/models.rs @@ -0,0 +1,442 @@ +//! Open-weight model hosting routes: signed upload-session open, unsigned +//! bearer-session block ingest, signed release claim, and the publisher +//! status reads. Mounted only when the operator enables model hosting; every +//! handler re-checks `state.block_store` so a disabled node answers the same +//! not-found as an unmounted route. + +use axum::extract::{Path, Request, State}; +use axum::http::HeaderMap; +use axum::response::IntoResponse; +use axum::{Extension, Json}; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::json; + +use crate::api::{authorize_repo_read, require_repo_owner}; +use crate::auth::{AuthenticatedDid, SignatureMaterial}; +use crate::blockstore::{BlockId, BlockStoreError, PutOutcome}; +use crate::db::{RepoRecord, VisibilityRule}; +use crate::error::{AppError, Result}; +use crate::models; +use crate::state::AppState; + +/// `X-Twigpine-Model-Session`: the bearer credential on block PUTs. The +/// session id is a 256-bit random capability minted at session open; there +/// is no HTTP signature on the PUT because a 64 MiB signed body would have +/// to be buffered whole to verify. +pub const SESSION_HEADER: &str = "x-twigpine-model-session"; + +fn hosting_enabled(state: &AppState) -> Result<()> { + if state.block_store.is_some() { + Ok(()) + } else { + Err(AppError::NotFound( + "model hosting is not enabled on this node".into(), + )) + } +} + +/// Model hosting only serves fully public repositories: a private repo, or +/// a public one carrying any path-scoped visibility rule, refuses with a +/// clear 4xx rather than partially publishing. +fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { + // A mirror row (slash-form id) carries a vacuous publicity pair: its + // is_public is hardcoded true and rules never sync, so passing this + // check on one means nothing. Mirrors are replication-managed, not + // publishable; refuse them the same way as a gated canonical repo. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { + return Err(AppError::BadRequest( + "model hosting requires a fully public repository".into(), + )); + } + Ok(()) +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/sessions` — open an upload +/// session. Owner-only (a session writes bytes the owner is billed for) on a +/// fully public repo. +pub async fn open_model_session( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + _body: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + let session = state + .db + .model_open_session(caller, &record.id, state.config.model_session_ttl_secs) + .await?; + Ok(( + axum::http::StatusCode::CREATED, + Json(json!({ + "session_id": session.id, + "expires_at": session.expires_at, + })), + )) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/sessions/{id}` — owner-only +/// session status. +pub async fn get_model_session( + State(state): State, + Path((owner, name, id)): Path<(String, String, String)>, + Extension(auth): Extension, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, _rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + let session = state + .db + .model_load_session(&id) + .await? + .filter(|s| s.repo_id == record.id && s.expires_at > models::ts_now()) + .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; + Ok(Json(json!({ + "session_id": session.id, + "state": session.state, + "bytes_received": session.bytes_received, + "expires_at": session.expires_at, + }))) +} + +/// PUT `/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}` — stream one +/// content block under a session bearer. Unsigned by design (see +/// [`SESSION_HEADER`]); the gate resolves the session, then runs the repo +/// read check as the session's owner so a repo turned private or withheld +/// mid-upload stops accepting bytes. +pub async fn put_model_block( + State(state): State, + Path((owner, name, sha)): Path<(String, String, String)>, + headers: HeaderMap, + request: Request, +) -> Result> { + hosting_enabled(&state)?; + let Some(session_id) = headers + .get(SESSION_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + else { + return Err(AppError::Unauthorized( + "a model block PUT requires the session header".into(), + )); + }; + let db = &state.db; + let Some(session) = db.model_load_session(&session_id).await? else { + return Err(AppError::NotFound("model upload session not found".into())); + }; + // authorize_repo_read 404s a repo the session owner can no longer read; + // the session-to-repo binding check below keeps foreign-session PUTs + // indistinguishable from a missing session. The owner always reads their + // own repo, so the fully-public check is what stops bytes landing on a + // repo that turned private or gained visibility rules mid-upload. + // mirror-rows-handled: sessions can only bind canonical repos (open + // refuses slash ids); the id check below already makes a mirror row a + // mismatch, and the explicit slash guard keeps the publicity pair from + // being trusted on one. + let (record, rules) = + authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; + if session.repo_id != record.id + || session.state != "open" + || session.expires_at <= models::ts_now() + || !record.is_public + || !rules.is_empty() + || record.id.contains('/') + { + return Err(AppError::NotFound("model upload session not found".into())); + } + let block_id = + BlockId::parse(&sha).map_err(|e| AppError::BadRequest(format!("block id: {e}")))?; + let declared: u64 = headers + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .ok_or_else(|| AppError::BadRequest("Content-Length is required".into()))?; + if declared == 0 || declared > models::MAX_BLOCK_BYTES { + return Err(AppError::BadRequest(format!( + "block bodies are 1..{} bytes", + models::MAX_BLOCK_BYTES + ))); + } + + // Admission before any byte is stored: the conditional update is the + // atomic charge against both the per-identity session cap and the + // node-wide quota, and it slides the session expiry in the same write. + let session_cap = state.config.effective_model_max_session_bytes() as i64; + let node_cap = state.config.model_node_quota_bytes as i64; + let Some(_) = db + .model_admit_bytes( + &session.id, + declared as i64, + state.config.model_session_ttl_secs, + session_cap, + node_cap, + ) + .await? + else { + // Not admitted: re-check whether the session died (404 hides the + // session) or a cap refused (named quota). + let session = db + .model_load_session(&session_id) + .await? + .filter(|s| s.state == "open" && s.expires_at > models::ts_now()); + return match session { + None => Err(AppError::NotFound("model upload session not found".into())), + Some(_) => Err(AppError::TooManyRequests(format!( + "the upload would exceed a model storage cap \ + (session cap {session_cap} bytes, node cap {node_cap} bytes)" + ))), + }; + }; + + let store = state.block_store.clone().expect("checked above"); + let stream = request + .into_body() + .into_data_stream() + .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); + // The store write and its bookkeeping run in one spawned task whose + // JoinHandle this handler awaits: a client that disconnects after + // sending the body drops the handler future, and a bare await between + // put_verified and model_record_block would strand a stored object with + // no model_blocks row and no refund, which the sweep can never find + // (its candidate list is model_blocks rows). + let bookkeep_db = state.db.clone(); + let bookkeep_session = session.id.clone(); + let bookkeep_sha = sha.clone(); + let bookkeeping = tokio::spawn(async move { + let outcome = match store + .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) + .await + { + Ok(o) => o, + Err(e) => { + let _ = bookkeep_db + .model_refund_bytes(&bookkeep_session, declared as i64) + .await; + return Err(match e { + BlockStoreError::DigestMismatch => AppError::BadRequest(format!( + "block body does not hash to the named id {bookkeep_sha}" + )), + BlockStoreError::TooLarge(cap) => { + AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + } + BlockStoreError::Unknown => AppError::Conflict( + "the write's outcome is unknown; check the object before retrying".into(), + ), + BlockStoreError::Body(e) => { + AppError::BadRequest(format!("block body could not be read: {e}")) + } + other => { + AppError::Internal(anyhow::anyhow!("block store write failed: {other}")) + } + }); + } + }; + // Stored and AlreadyPresent both leave the bytes stored. On a tail + // failure the admission is always refunded, but the object is + // deleted only when this request stored it AND no model_blocks row + // names it now: an already-present block, or one a row carries, is + // shared and must survive. + let size = match store.size(&block_id).await { + Ok(Some(s)) => s, + r => { + let _ = bookkeep_db + .model_refund_bytes(&bookkeep_session, declared as i64) + .await; + if outcome == PutOutcome::Stored + && !bookkeep_db + .model_block_exists(&bookkeep_sha) + .await + .unwrap_or(true) + { + let _ = store.delete(&block_id).await; + } + return Err(match r { + Ok(None) => AppError::Internal(anyhow::anyhow!( + "block {bookkeep_sha} absent immediately after write" + )), + Err(e) => AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")), + Ok(Some(_)) => unreachable!(), + }); + } + }; + match bookkeep_db + .model_record_block(&bookkeep_session, &bookkeep_sha, size, declared as i64) + .await + { + Ok(duplicate) => Ok(duplicate), + Err(e) => { + let _ = bookkeep_db + .model_refund_bytes(&bookkeep_session, declared as i64) + .await; + if outcome == PutOutcome::Stored + && !bookkeep_db + .model_block_exists(&bookkeep_sha) + .await + .unwrap_or(true) + { + let _ = store.delete(&block_id).await; + } + Err(e.into()) + } + } + }); + let duplicate = bookkeeping.await.map_err(|e| { + AppError::Internal(anyhow::anyhow!("upload bookkeeping task failed: {e}")) + })??; + let fresh = db.model_load_session(&session.id).await?; + Ok(Json(json!({ + "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), + "duplicate": duplicate, + "expires_at": fresh.map(|s| s.expires_at).unwrap_or_default(), + }))) +} + +#[derive(Debug, Deserialize)] +pub struct ClaimBody { + pub commit: String, + pub branch: String, +} + +fn release_view(r: &models::ReleaseRow) -> serde_json::Value { + json!({ + "release_id": r.id, + "commit": r.commit_sha, + "branch": r.branch, + "state": r.state, + "manifest_sha256": r.manifest_sha256, + "failure_reason": r.failure_reason, + "created_at": r.created_at, + "published_at": r.published_at, + }) +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/claims` — claim a pushed commit +/// as a model release. Runs the ordered KTD5 checks; a replay resolves to the +/// original row via the persisted request digest. +pub async fn claim_model_release( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + material: Option>, + Json(body): Json, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + + let Some(Extension(material)) = material else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its signature material" + ))); + }; + let Some(body_bytes) = material.body.clone() else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its persisted request body" + ))); + }; + crate::api::status::require_body_bound_signature(&material, &body_bytes)?; + if body.commit.len() != 40 || !body.commit.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(AppError::BadRequest("commit must be a 40-hex sha".into())); + } + let material = models::claim::ClaimMaterial { + request_digest: crate::api::status::request_digest(&material, &body_bytes), + signature: material.signature, + signature_input: material.signature_input, + signing_string: material.signing_string, + body: body_bytes.to_vec(), + }; + let release = models::claim::claim_release( + &state, + &record, + caller, + &body.commit, + &body.branch, + &material, + ) + .await?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}` — release +/// status. Same read gate as the repo's other listing surfaces: anonymous on +/// a public repo, 404 where the caller cannot read. +pub async fn get_model_release( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result> { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + let (record, _rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + let release = state + .db + .model_release_by_commit(&record.id, &commit) + .await? + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}/reconstruction` +/// — the reconstruction object of a published release, for publisher-side +/// dedup (KTD6). The repo read gate applies, plus the current-public check: +/// once a repo stops being fully public it stops serving model objects, +/// owner included. +pub async fn get_model_reconstruction( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + // mirror-rows-handled: a mirror row (slash-form id) can never carry a + // claimed release, and its publicity pair is vacuous, so it takes the + // same 404 as a private repo. + let (record, rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + if !record.is_public || !rules.is_empty() || record.id.contains('/') { + return Err(AppError::NotFound("model release not found".into())); + } + let release = state + .db + .model_release_by_commit(&record.id, &commit) + .await? + .filter(|r| r.state == "published") + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + // The stored reconstruction ref was bound when the release verified; + // re-reading and re-verifying the manifest per GET is wasted work. + let Some(sha) = state.db.model_reconstruction_sha(release.id).await? else { + return Err(AppError::NotFound( + "release has no reconstruction object".into(), + )); + }; + let store = state.block_store.clone().expect("checked above"); + let size = store + .size( + &BlockId::parse(&sha) + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?, + ) + .await + .ok() + .flatten() + .ok_or_else(|| AppError::NotFound("reconstruction object not stored".into()))?; + // Stream the object straight into the response body: buffering the whole + // reconstruction object per anonymous GET would be an uncapped read. + let id = BlockId::parse(&sha) + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; + let stream = store + .get_range(&id, 0, size) + .await + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; + Ok(( + [(axum::http::header::CONTENT_TYPE, "application/octet-stream")], + axum::body::Body::from_stream(stream), + )) +} diff --git a/crates/twigpine-node/src/api/status/mod.rs b/crates/twigpine-node/src/api/status/mod.rs index ab736a80..7fe8cf21 100644 --- a/crates/twigpine-node/src/api/status/mod.rs +++ b/crates/twigpine-node/src/api/status/mod.rs @@ -278,7 +278,7 @@ pub async fn create_status( /// /// A 400, not a 500: the material is exactly what the client signed, and what /// they signed does not cover what they sent. -fn require_body_bound_signature( +pub(crate) fn require_body_bound_signature( material: &crate::auth::SignatureMaterial, body: &[u8], ) -> Result<()> { @@ -317,7 +317,7 @@ fn require_body_bound_signature( /// This is not a nonce, and deliberately so. A nonce table needs pruning and a /// pruning window is a second replay window; the claim row IS the record of what /// was accepted, so uniqueness on it is self-maintaining. -fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { +pub(crate) fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); for part in [ diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 44f4d0df..dc0f95cd 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -35,27 +35,32 @@ pub struct FsBlockStore { root: PathBuf, } +/// Directories to fsync after `create_dir_all(dir)`, deepest first: the +/// parent of every ancestor. A relative root's chain ends at an empty +/// parent, whose entry lives in the current directory. +fn ancestor_parents(dir: &Path) -> Vec { + dir.ancestors() + .map_while(|d| d.parent()) + .map(|p| { + if p.as_os_str().is_empty() { + PathBuf::from(".") + } else { + p.to_path_buf() + } + }) + .collect() +} + impl FsBlockStore { pub fn new(root: PathBuf) -> io::Result { let tmp = root.join("tmp"); - // Every directory this call creates, deepest first. Creating them - // adds an entry to each one's parent, and an entry that is not - // fsynced is lost on a crash together with every block under it. - let created: Vec = tmp - .ancestors() - .take_while(|a| !a.as_os_str().is_empty() && !a.exists()) - .map(Path::to_path_buf) - .collect(); std::fs::create_dir_all(&tmp)?; - for dir in &created { - if let Some(parent) = dir.parent() { - let parent = if parent.as_os_str().is_empty() { - Path::new(".") - } else { - parent - }; - fsync_dir_blocking(parent)?; - } + // An existing directory proves nothing about durability: sync the + // parent of every directory in the chain, deepest first. A retry + // after a crash mid-init finds every dir present and must still + // persist the names create_dir_all made the first time. + for parent in ancestor_parents(&tmp) { + fsync_dir_blocking(&parent)?; } Ok(Self { root }) } @@ -142,17 +147,27 @@ impl BlockStore for FsBlockStore { } let tmp = self.temp_path(); - // Declared before `file`, so the handle closes before the removal. - let _staged = StagedFile(tmp.clone()); - let mut file = match tokio::fs::File::create(&tmp).await { - Ok(f) => f, - Err(e) => return Err(e.into()), + // Create the file and arm its guard inside the blocking task: a + // caller cancelled while the open is in flight still removes the + // file when the blocking op lands. + let (mut file, _staged) = match tokio::task::spawn_blocking({ + let tmp = tmp.clone(); + move || { + let staged = StagedFile(tmp); + std::fs::File::create(&staged.0).map(|f| (f, staged)) + } + }) + .await + { + Ok(Ok((f, staged))) => (tokio::fs::File::from_std(f), staged), + Ok(Err(e)) => return Err(e.into()), + Err(e) => return Err(io::Error::other(e.to_string()).into()), }; let mut hasher = Sha256::new(); let mut len: u64 = 0; let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); @@ -179,8 +194,15 @@ impl BlockStore for FsBlockStore { Self::cleanup(&tmp).await; return Err(BlockStoreError::EmptyBlock); } - // Flush before the link: a crash between link and write-back would - // leave a truncated object under a valid id. + // Flush first: tokio buffers the tail of a file write and only a + // flush or a following op surfaces its error. Then fsync before the + // link: a crash between link and write-back would leave a truncated + // object under a valid id. + if let Err(e) = file.flush().await { + drop(file); + Self::cleanup(&tmp).await; + return Err(e.into()); + } if let Err(e) = file.sync_all().await { drop(file); Self::cleanup(&tmp).await; @@ -204,9 +226,12 @@ impl BlockStore for FsBlockStore { // makes a same-content race benign rather than a torn write. match tokio::fs::hard_link(&tmp, &dest).await { Ok(()) => { - if let Err(e) = fsync_dir(dir).await { + if fsync_dir(dir).await.is_err() { Self::cleanup(&tmp).await; - return Err(e.into()); + // The link landed; whether it is durable is unknown, so + // the write's outcome is too. The destination object is + // left for a reconciling size() check. + return Err(BlockStoreError::Unknown); } Self::cleanup(&tmp).await; Ok(PutOutcome::Stored) @@ -255,7 +280,16 @@ impl BlockStore for FsBlockStore { } async fn delete(&self, id: &BlockId) -> Result<(), BlockStoreError> { - match tokio::fs::remove_file(self.content_path(id)).await { + let path = self.content_path(id); + let dir = path.parent().expect("content path has two levels"); + match tokio::fs::remove_file(&path).await { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } + // Persist the removal: the sweep commits the row delete right after, + // and a crash in between can otherwise resurrect the object. + match fsync_dir(dir).await { Ok(()) => Ok(()), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e.into()), @@ -296,6 +330,31 @@ mod tests { FsBlockStore::new(dir.path().join("blocks")).unwrap() } + #[test] + fn ancestor_parents_maps_a_relative_roots_top_to_the_cwd() { + // A relative root's ancestor chain ends at a path with an empty + // parent: fsyncing "" is ENOENT, so the chain must name "." there. + let parents = ancestor_parents(Path::new("data/blocks/tmp")); + assert_eq!( + parents, + vec![ + PathBuf::from("data/blocks"), + PathBuf::from("data"), + PathBuf::from("."), + ] + ); + assert!(!parents.iter().any(|p| p.as_os_str().is_empty())); + let abs = ancestor_parents(Path::new("/a/b/c")); + assert_eq!( + abs, + vec![ + PathBuf::from("/a/b"), + PathBuf::from("/a"), + PathBuf::from("/") + ] + ); + } + #[tokio::test] async fn put_get_size_roundtrip() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs index d44210d9..0d19f577 100644 --- a/crates/twigpine-node/src/blockstore/mod.rs +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -101,6 +101,10 @@ pub enum BlockStoreError { /// unknown. #[error("the write's outcome is unknown; check size() before retrying")] Unknown, + /// The body stream itself failed (client abort, truncated upload): a + /// caller fault, distinct from a store-side `Io`. + #[error("body stream error: {0}")] + Body(io::Error), #[error("i/o error: {0}")] Io(#[from] io::Error), #[error("backend error: {0}")] diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index a8ff1086..544da5eb 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -108,9 +108,19 @@ impl S3BlockStore { /// AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_ENDPOINT_URL_S3 /// environment the Tigris repo backend reads. pub async fn new(bucket: &str) -> anyhow::Result { - let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; + // The SDK sets no default operation timeout: without one a wedged + // endpoint hangs the caller (including the sweep, which holds a row + // lock across delete) indefinitely. + let sdk = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; + let config = aws_sdk_s3::config::Builder::from(&sdk) + .timeout_config( + aws_sdk_s3::config::timeout::TimeoutConfig::builder() + .operation_timeout(std::time::Duration::from_secs(60)) + .build(), + ) + .build(); Ok(Self { - s3: S3Client::new(&config), + s3: S3Client::from_conf(config), bucket: bucket.to_string(), }) } @@ -264,7 +274,7 @@ impl BlockStore for S3BlockStore { // ever resident, never the whole body. let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 59084b4f..d36d63dd 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1215,6 +1215,30 @@ impl Config { /// validated. pub fn validate(&mut self) -> Result<(), String> { self.settle_default_key_paths()?; + // Byte caps land in an i64 quota ledger (`as i64` at claim/session + // admission); above i64::MAX the cast wraps negative and every admit + // fails. + for (name, value) in [ + ("TWIGPINE_MODEL_QUOTA_BYTES", Some(self.model_quota_bytes)), + ( + "TWIGPINE_MODEL_NODE_QUOTA_BYTES", + Some(self.model_node_quota_bytes), + ), + ( + "TWIGPINE_MODEL_MAX_SESSION_BYTES", + self.model_max_session_bytes, + ), + ] { + if let Some(v) = value { + if v > i64::MAX as u64 { + return Err(format!( + "{name} ({v}) exceeds {i64max}, the largest value the \ + signed quota ledger can hold", + i64max = i64::MAX + )); + } + } + } if self.model_unclaimed_ttl_secs <= self.model_session_ttl_secs { return Err(format!( "TWIGPINE_MODEL_UNCLAIMED_TTL_SECS ({}) must exceed \ @@ -1692,6 +1716,30 @@ mod tests { ); } + #[test] + fn model_byte_caps_stop_at_the_i64_ledger_bound() { + let mut ok = Config::parse_from(["twigpine-node"]); + ok.validate().expect("defaults validate"); + let mut at_max = Config::parse_from([ + "twigpine-node", + "--model-quota-bytes", + "9223372036854775807", + "--model-node-quota-bytes", + "9223372036854775807", + "--model-max-session-bytes", + "9223372036854775807", + ]); + assert!(at_max.validate().is_ok(), "i64::MAX is the last valid cap"); + for flag in [ + "--model-quota-bytes", + "--model-node-quota-bytes", + "--model-max-session-bytes", + ] { + let mut over = Config::parse_from(["twigpine-node", flag, "9223372036854775808"]); + assert!(over.validate().is_err(), "{flag} above i64::MAX"); + } + } + #[test] fn require_signature_nonce_ships_off() { assert!( diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index b0d32a88..541c19df 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -524,6 +524,8 @@ pub struct MarkerCleanup { pub dead_letter: bool, } +pub mod model_queries; + /// The lifecycle states of a row in `pending_ref_transitions`. Persisted as a /// TEXT column with one of these string values; the constants are the canonical /// spellings, and tests + the recovery drain all use them so a typo on one @@ -2820,6 +2822,51 @@ const MIGRATIONS: &[Migration] = &[ "CREATE INDEX IF NOT EXISTS idx_model_durability_jobs_pending ON model_durability_jobs (state, created_at)", ], }, + Migration { + version: 50, + name: "model_release_claim_digest_and_cascades", + stmts: &[ + // Replayed claims resolve by request digest instead of writing a + // second row, mirroring status_claims' dedupe. + "ALTER TABLE model_releases ADD COLUMN IF NOT EXISTS claim_request_digest TEXT", + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_request_digest ON model_releases (claim_request_digest) WHERE claim_request_digest IS NOT NULL", + // One in-flight verification per publisher: claim admission's + // check is check-then-act under the advisory lock, and this index + // is the backstop that makes a bug there still fail closed. + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_one_verifying ON model_releases (publisher_did) WHERE state = 'verifying'", + // A deleted repo takes its sessions, releases, and links with it. + // The FK constraints are re-declared with ON DELETE CASCADE; the + // names are Postgres defaults (table_column_fkey). + "ALTER TABLE model_upload_sessions DROP CONSTRAINT IF EXISTS model_upload_sessions_repo_id_fkey, ADD CONSTRAINT model_upload_sessions_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_session_id_fkey, ADD CONSTRAINT model_session_blocks_session_id_fkey FOREIGN KEY (session_id) REFERENCES model_upload_sessions(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_block_sha256_fkey, ADD CONSTRAINT model_session_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_releases DROP CONSTRAINT IF EXISTS model_releases_repo_id_fkey, ADD CONSTRAINT model_releases_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_release_id_fkey, ADD CONSTRAINT model_release_blocks_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_block_sha256_fkey, ADD CONSTRAINT model_release_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_durability_jobs DROP CONSTRAINT IF EXISTS model_durability_jobs_release_id_fkey, ADD CONSTRAINT model_durability_jobs_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + ], + }, + Migration { + version: 51, + name: "model_upload_sessions_repo_id_index", + stmts: &[ + // Purging a repo cascades through its upload sessions; without + // this index the delete scans the whole session table. + "CREATE INDEX IF NOT EXISTS idx_model_upload_sessions_repo ON model_upload_sessions (repo_id)", + ], + }, + Migration { + version: 52, + name: "model_blocks_payer_did", + stmts: &[ + // The first claimer pays for a block, which is not always the + // release's publisher (a free claim rides another payer's + // bytes). Rejection and repo-deletion refunds follow this + // column; NULL rows fall back to the release's publisher, which + // is how every pre-column block was claimed. + "ALTER TABLE model_blocks ADD COLUMN IF NOT EXISTS payer_did TEXT", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -3977,6 +4024,26 @@ impl Db { .await?; } + // Live model releases carry a quota charge keyed on the claim's + // payer; the cascade off `repos` would drop the release and block + // links without refunding it, leaking the charge (and inflating the + // node-wide sum). Refund each release the way a rejection does, + // serialized with concurrent claims on the same advisory lock. + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(crate::models::CLAIM_LOCK_KEY) + .execute(&mut *tx) + .await?; + let release_ids: Vec = sqlx::query_scalar( + "SELECT id FROM model_releases + WHERE repo_id = $1 AND state IN ('verifying', 'published')", + ) + .bind(id) + .fetch_all(&mut *tx) + .await?; + for release_id in release_ids { + self.model_release_refund_tx(&mut tx, release_id).await?; + } + let result = sqlx::query("DELETE FROM repos WHERE id = $1") .bind(id) .execute(&mut *tx) @@ -14435,7 +14502,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ($1, $2, 'main', 'did:key:zOwner', 'verifying', + VALUES ($1, $2, 'main', 'did:key:zOwner', 'published', $3, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(repo_id) @@ -14512,7 +14579,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'verifying', + VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'published', $2, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(SHA_A) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs new file mode 100644 index 00000000..11b1e94c --- /dev/null +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -0,0 +1,1652 @@ +//! Model-hosting queries. Timestamps follow the repo convention: rfc3339 +//! text in TEXT columns, written and compared through the helpers here. + +use sqlx::{Postgres, Transaction}; + +use super::{Db, Result}; + +pub(crate) fn ts_now() -> String { + chrono::Utc::now().to_rfc3339() +} + +fn ts_from_now(secs: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() +} + +#[derive(Debug, Clone)] +pub struct ModelSession { + pub id: String, + pub owner_did: String, + pub repo_id: String, + pub expires_at: String, + pub bytes_received: i64, + pub state: String, +} + +type SessionTuple = (String, String, String, String, i64, String); + +/// Global advisory key serializing block-byte admission across sessions +/// (see `model_admit_bytes`). Distinct from `CLAIM_LOCK_KEY` in +/// `crate::models`, which serializes claim admission. +pub(crate) const MODEL_ADMIT_LOCK: i64 = 0x6D6F64656C61646D; // "modeladm" + +const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; + +impl From for ModelSession { + fn from(t: SessionTuple) -> Self { + ModelSession { + id: t.0, + owner_did: t.1, + repo_id: t.2, + expires_at: t.3, + bytes_received: t.4, + state: t.5, + } + } +} + +#[derive(Debug, Clone)] +pub struct ModelRelease { + pub id: i64, + pub repo_id: String, + pub commit_sha: String, + pub branch: String, + pub publisher_did: String, + pub state: String, + pub manifest_sha256: String, + pub failure_reason: Option, + pub created_at: String, + pub published_at: Option, + pub request_digest: Option, +} + +#[allow(clippy::type_complexity)] +pub type ReleaseTuple = ( + i64, + String, + String, + String, + String, + String, + String, + Option, + String, + Option, + Option, +); + +impl From for ModelRelease { + fn from(t: ReleaseTuple) -> Self { + ModelRelease { + id: t.0, + repo_id: t.1, + commit_sha: t.2, + branch: t.3, + publisher_did: t.4, + state: t.5, + manifest_sha256: t.6, + failure_reason: t.7, + created_at: t.8, + published_at: t.9, + request_digest: t.10, + } + } +} + +/// Result of [`Db::model_publish_if_public`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PublishOutcome { + /// The release flipped to `published` inside the locked check. + Published, + /// The repo is gone, private, mirror-form, or now has visibility rules. + NoLongerPublic, + /// The release left `verifying` already (a concurrent verifier + /// published it, or it was rejected); the caller must re-read the row + /// before deciding what to unwind. + NotVerifying, +} + +pub const RELEASE_COLS: &str = "id, repo_id, commit_sha, branch, publisher_did, \ + state, manifest_sha256, failure_reason, created_at, published_at, \ + claim_request_digest"; + +/// Fields of the signed claim persisted on the release row (the status-claim +/// pattern: the row is the replay ledger). +pub struct ClaimPersist { + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, + pub request_digest: String, +} + +impl Db { + pub async fn model_open_session( + &self, + owner_did: &str, + repo_id: &str, + ttl_secs: u64, + ) -> Result { + let id = hex::encode(rand::random::<[u8; 32]>()); + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1, $2, $3, $4, $5, 0, 'open') + RETURNING {SESSION_COLS}" + )) + .bind(&id) + .bind(owner_did) + .bind(repo_id) + .bind(ts_now()) + .bind(ts_from_now(ttl_secs as i64)) + .fetch_one(&self.pool) + .await?; + Ok(row.into()) + } + + pub async fn model_load_session(&self, id: &str) -> Result> { + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "SELECT {SESSION_COLS} FROM model_upload_sessions WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Atomically admit `claimed` bytes against the caller's per-identity + /// open-session cap and the node-wide quota, sliding expiry forward in + /// the same update. `None` when the session is closed, expired, or a cap + /// would be exceeded; the caller re-reads the session to pick the honest + /// denial. + pub async fn model_admit_bytes( + &self, + session_id: &str, + claimed: i64, + ttl_secs: u64, + session_cap: i64, + node_cap: i64, + ) -> Result> { + // Serialize admissions process-wide: the per-owner and node-wide cap + // terms read other sessions' bytes_received, and two concurrent PUTs + // on different sessions would otherwise admit against the same stale + // sums. The critical section is one UPDATE, so the global key costs + // nothing next to the upload itself. + let mut tx = self.pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(MODEL_ADMIT_LOCK) + .execute(&mut *tx) + .await?; + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "UPDATE model_upload_sessions s + SET bytes_received = s.bytes_received + $1, + expires_at = $2 + WHERE s.id = $3 + AND s.state = 'open' + AND s.expires_at > $4 + AND s.bytes_received + $1 + COALESCE(( + SELECT SUM(o.bytes_received) FROM model_upload_sessions o + WHERE o.owner_did = s.owner_did AND o.state = 'open' AND o.id <> s.id + AND o.expires_at > $4 + ), 0) <= $5 + AND COALESCE((SELECT SUM(q.bytes_used) FROM model_quota_usage q), 0) + + COALESCE(( + SELECT SUM(o2.bytes_received) FROM model_upload_sessions o2 + WHERE o2.state = 'open' AND o2.expires_at > $4 + ), 0) + + $1 <= $6 + RETURNING {SESSION_COLS}" + )) + .bind(claimed) + .bind(ts_from_now(ttl_secs as i64)) + .bind(session_id) + .bind(ts_now()) + .bind(session_cap) + .bind(node_cap) + .fetch_optional(&mut *tx) + .await?; + tx.commit().await?; + Ok(row.map(Into::into)) + } + + /// Refund an admitted charge when the store or the bookkeeping fails. + /// Best-effort under races; an expired session frees the bytes anyway. + pub async fn model_refund_bytes(&self, session_id: &str, bytes: i64) -> Result<()> { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(bytes) + .bind(session_id) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Book the stored block against the session in one transaction. `true` + /// when the admission credit was refunded: a duplicate within the + /// session, or a block a verifying or published release of the session's + /// own owner already carries. Claim authorizes that release's blocks + /// without a session link and billed them at claim, so the block is + /// neither charged nor linked here; a link would outlive the release and + /// hold the block unbilled once it is rejected. Blocks carried by another + /// publisher's release, or held only by other open sessions, are still + /// charged and linked. + pub async fn model_record_block( + &self, + session_id: &str, + block_sha: &str, + size: u64, + admitted: i64, + ) -> Result { + let mut tx = self.pool.begin().await?; + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at, unreferenced_since) + VALUES ($1, $2, $3, $3) + ON CONFLICT (sha256) DO NOTHING", + ) + .bind(block_sha) + .bind(size as i64) + .bind(ts_now()) + .execute(&mut *tx) + .await?; + let own_release_carries = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + JOIN model_upload_sessions s ON s.owner_did = r.publisher_did + WHERE rb.block_sha256 = $1 AND s.id = $2 + AND r.state IN ('verifying', 'published'))", + ) + .bind(block_sha) + .bind(session_id) + .fetch_one(&mut *tx) + .await?; + let linked = if own_release_carries { + 0 + } else { + sqlx::query( + "INSERT INTO model_session_blocks (session_id, block_sha256) + VALUES ($1, $2) + ON CONFLICT (session_id, block_sha256) DO NOTHING", + ) + .bind(session_id) + .bind(block_sha) + .execute(&mut *tx) + .await? + .rows_affected() + }; + let refund = linked == 0; + if refund { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(admitted) + .bind(session_id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(refund) + } + + /// Whether a `model_blocks` row exists for `sha`. A failed bookkeeping + /// cleanup deletes a stored object only when no row references it, so a + /// block a release or another session already carries is never removed + /// from under it. + pub async fn model_block_exists(&self, sha: &str) -> Result { + Ok(sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM model_blocks WHERE sha256 = $1)", + ) + .bind(sha) + .fetch_one(&self.pool) + .await?) + } + + pub async fn model_release_by_digest(&self, digest: &str) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE claim_request_digest = $1" + )) + .bind(digest) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_release_by_commit( + &self, + repo_id: &str, + commit: &str, + ) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Ids of `verifying` releases stuck past `stale_secs`: the worker + /// retries them forever today, so the sweep rejects them to un-wedge + /// the publisher's one-verifying slot. + pub async fn model_stale_verifying(&self, stale_secs: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases + WHERE state = 'verifying' AND created_at < $1", + ) + .bind(ts_from_now(-stale_secs)) + .fetch_all(&self.pool) + .await?) + } + + /// The reconstruction object sha a release was claimed with, if any. + /// The reconstruction GET serves by this stored ref: the manifest it + /// names is immutable under the pinned commit and was verified at claim. + pub async fn model_reconstruction_sha(&self, id: i64) -> Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT reconstruction_sha256 FROM model_releases WHERE id = $1", + ) + .bind(id) + .fetch_optional(&self.pool) + .await? + .flatten()) + } + + pub async fn model_release_by_id(&self, id: i64) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_begin(&self) -> Result> { + Ok(self.pool.begin().await?) + } + + // ── claim transaction steps ─────────────────────────────────────────── + + pub async fn model_tx_advisory_lock( + &self, + tx: &mut Transaction<'_, Postgres>, + key: i64, + ) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(&mut **tx) + .await?; + Ok(()) + } + + pub async fn model_tx_release_by_digest( + &self, + tx: &mut Transaction<'_, Postgres>, + digest: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE claim_request_digest = $1" + )) + .bind(digest) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + pub async fn model_tx_release_by_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + /// Lock and return the present subset of `shas` (`FOR UPDATE` so a + /// racing sweep cannot delete a block mid-claim). + pub async fn model_tx_lock_present_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result> { + if shas.is_empty() { + return Ok(Vec::new()); + } + Ok( + sqlx::query_scalar("SELECT sha256 FROM model_blocks WHERE sha256 = ANY($1) FOR UPDATE") + .bind(shas) + .fetch_all(&mut **tx) + .await?, + ) + } + + pub async fn model_tx_session_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + owner_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sb.block_sha256 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE s.owner_did = $1 AND s.state = 'open' AND s.expires_at > $2", + ) + .bind(owner_did) + .bind(ts_now()) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_publisher_release_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.publisher_did = $1 AND r.state IN ('verifying', 'published')", + ) + .bind(publisher_did) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_release_blocks_at_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.repo_id = $1 AND r.commit_sha = $2 AND r.state = 'published'", + ) + .bind(repo_id) + .bind(commit) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_has_verifying( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT id FROM model_releases + WHERE publisher_did = $1 AND state = 'verifying' LIMIT 1", + ) + .bind(publisher_did) + .fetch_optional(&mut **tx) + .await? + .is_some()) + } + + /// Bytes of `shas` not already referenced by any live release: the + /// first-claimer-pays charge. + pub async fn model_tx_unclaimed_bytes( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result { + if shas.is_empty() { + return Ok(0); + } + // SUM over bigint returns numeric; cast back so the i64 decode holds. + Ok(sqlx::query_scalar::<_, Option>( + "SELECT SUM(b.size)::bigint FROM model_blocks b + WHERE b.sha256 = ANY($1) + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published'))", + ) + .bind(shas) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + /// Atomic per-identity reservation; `None` when the cap would be + /// exceeded. The cap applies on BOTH branches: a `WHERE` inside `DO + /// UPDATE` alone would let a first-time DID insert any `delta`, since + /// that clause never guards the insert attempt. + pub async fn model_tx_reserve_quota( + &self, + tx: &mut Transaction<'_, Postgres>, + did: &str, + delta: i64, + cap: i64, + ) -> Result> { + Ok(sqlx::query_scalar::<_, i64>( + "INSERT INTO model_quota_usage (did, bytes_used) + SELECT $1, $2 WHERE $2 <= $3 + ON CONFLICT (did) DO UPDATE + SET bytes_used = model_quota_usage.bytes_used + $2 + WHERE model_quota_usage.bytes_used + $2 <= $3 + RETURNING bytes_used", + ) + .bind(did) + .bind(delta) + .bind(cap) + .fetch_optional(&mut **tx) + .await?) + } + + /// Node-wide used bytes: claimed quota plus every open session's bytes. + pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { + // SUM over bigint returns numeric; cast back so the i64 decode holds. + // A session past its wall-clock expiry is dead before the sweep + // flips its state, so it does not count against the cap. + Ok(sqlx::query_scalar::<_, Option>( + "SELECT (COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions + WHERE state = 'open' AND expires_at > $1), 0))::bigint", + ) + .bind(ts_now()) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + #[allow(clippy::too_many_arguments)] + pub async fn model_tx_insert_release( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + branch: &str, + publisher_did: &str, + manifest_sha256: &str, + reconstruction_sha256: Option<&str>, + claim: &ClaimPersist, + ) -> Result { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + reconstruction_sha256, claim_signature, claim_signature_input, + claim_signing_string, claim_body, claim_request_digest, created_at) + VALUES ($1,$2,$3,$4,'verifying',$5,$6,$7,$8,$9,$10,$11,$12) + RETURNING {RELEASE_COLS}" + )) + .bind(repo_id) + .bind(commit) + .bind(branch) + .bind(publisher_did) + .bind(manifest_sha256) + .bind(reconstruction_sha256) + .bind(&claim.signature) + .bind(&claim.signature_input) + .bind(&claim.signing_string) + .bind(&claim.body) + .bind(&claim.request_digest) + .bind(ts_now()) + .fetch_one(&mut **tx) + .await?; + Ok(row.into()) + } + + /// Link `shas` to the release and drop them from the publisher's open + /// sessions, so the same bytes stop counting twice node-wide. Batched: + /// this runs inside the claim's advisory lock, so a manifest naming + /// thousands of blocks must not pay two round trips per block. + pub async fn model_tx_link_release_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + release_id: i64, + publisher_did: &str, + shas: &[String], + ) -> Result<()> { + if shas.is_empty() { + return Ok(()); + } + // The claimer pays for exactly the blocks model_tx_unclaimed_bytes + // counted as new (no live release references them); blocks a live + // release already carries keep their first payer. Runs before the + // link insert below so this release's own rows do not mask the set. + sqlx::query( + "UPDATE model_blocks b SET payer_did = $2 + WHERE b.sha256 = ANY($1) + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published'))", + ) + .bind(shas) + .bind(publisher_did) + .execute(&mut **tx) + .await?; + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) + SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING", + ) + .bind(release_id) + .bind(shas) + .execute(&mut **tx) + .await?; + // The release now carries these blocks, so the sessions stop being + // charged for exactly the bytes that moved. Subtracting the moved + // set (rather than recounting links) preserves bytes admitted but + // not yet recorded by a PUT still in flight. + sqlx::query( + "WITH moved AS ( + DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE s.id = sb.session_id AND s.owner_did = $1 + AND s.state = 'open' AND sb.block_sha256 = ANY($2) + RETURNING sb.session_id, sb.block_sha256 + ), per_session AS ( + SELECT m.session_id, COALESCE(SUM(b.size), 0)::bigint AS bytes + FROM moved m + JOIN model_blocks b ON b.sha256 = m.block_sha256 + GROUP BY m.session_id + ) + UPDATE model_upload_sessions s + SET bytes_received = GREATEST(s.bytes_received - ps.bytes, 0) + FROM per_session ps + WHERE ps.session_id = s.id", + ) + .bind(publisher_did) + .bind(shas) + .execute(&mut **tx) + .await?; + Ok(()) + } + + // ── verification ─────────────────────────────────────────────────────── + + /// `false` when the release left `verifying` first (the stale-verify + /// sweep rejected it mid-run); the caller then unwinds what it wrote. + pub async fn model_mark_published(&self, release_id: i64) -> Result { + let done = sqlx::query( + "UPDATE model_releases + SET state = 'published', published_at = $2 + WHERE id = $1 AND state = 'verifying'", + ) + .bind(release_id) + .bind(ts_now()) + .execute(&self.pool) + .await? + .rows_affected(); + Ok(done > 0) + } + + /// Publish a verifying release only while its repo is still fully + /// public. The repo row is taken FOR UPDATE, the same lock + /// `set_visibility_rule` and `remove_visibility_rule` hold while they + /// write a rule and bump the epoch, so a rule added mid-verify (after + /// the handler-time publicity check) serializes: either it commits + /// first and this returns `NoLongerPublic`, or it waits and sees the + /// release already published. + pub async fn model_publish_if_public( + &self, + release_id: i64, + repo_id: &str, + ) -> Result { + if repo_id.contains('/') { + return Ok(PublishOutcome::NoLongerPublic); + } + let mut tx = self.pool.begin().await?; + let is_public: Option = + sqlx::query_scalar("SELECT is_public FROM repos WHERE id = $1 FOR UPDATE") + .bind(repo_id) + .fetch_optional(&mut *tx) + .await?; + let Some(true) = is_public else { + return Ok(PublishOutcome::NoLongerPublic); + }; + let has_rules: bool = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM visibility_rules WHERE repo_id = $1)") + .bind(repo_id) + .fetch_one(&mut *tx) + .await?; + if has_rules { + return Ok(PublishOutcome::NoLongerPublic); + } + let done = sqlx::query( + "UPDATE model_releases + SET state = 'published', published_at = $2 + WHERE id = $1 AND state = 'verifying'", + ) + .bind(release_id) + .bind(ts_now()) + .execute(&mut *tx) + .await? + .rows_affected(); + tx.commit().await?; + Ok(if done > 0 { + PublishOutcome::Published + } else { + PublishOutcome::NotVerifying + }) + } + + /// Reject: mark the release, drop its refs, and refund the publisher the + /// bytes no other live release still references. + pub async fn model_reject_release(&self, release_id: i64, reason: &str) -> Result<()> { + let mut tx = self.pool.begin().await?; + // The refund's "no other live release references this block" test + // and a concurrent claim's "not already claimed" test must agree; + // the claim lock makes them serialize. Same order as claim_release + // (advisory first, then rows), so no deadlock is introduced. + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(crate::models::CLAIM_LOCK_KEY) + .execute(&mut *tx) + .await?; + let released: Option<(String,)> = sqlx::query_as( + "UPDATE model_releases + SET state = 'rejected', failure_reason = $2 + WHERE id = $1 AND state = 'verifying' + RETURNING publisher_did", + ) + .bind(release_id) + .bind(reason) + .fetch_optional(&mut *tx) + .await?; + let Some((_publisher,)) = released else { + tx.commit().await?; + return Ok(()); + }; + self.model_release_refund_tx(&mut tx, release_id).await?; + tx.commit().await?; + Ok(()) + } + + /// Free the quota a release's blocks were charged under. Blocks no other + /// live release references are released; each refunds to the DID that + /// paid for it at claim (`model_blocks.payer_did`), falling back to this + /// release's publisher for rows claimed before the column existed. The + /// release's block links are dropped and the freed blocks' payer is + /// cleared so nothing refunds them twice. Callers must hold + /// `CLAIM_LOCK_KEY` inside the tx so the "no other live release" test + /// serializes with claim's "not already claimed" test. + pub async fn model_release_refund_tx( + &self, + tx: &mut Transaction<'_, Postgres>, + release_id: i64, + ) -> Result<()> { + // SUM over bigint returns numeric; cast back so the i64 decode holds. + let per_payer: Vec<(String, i64)> = sqlx::query_as( + "SELECT COALESCE(b.payer_did, r.publisher_did) AS payer, + COALESCE(SUM(b.size), 0)::bigint AS bytes + FROM model_blocks b + JOIN model_release_blocks rb ON rb.block_sha256 = b.sha256 + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.release_id = $1 + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks r2 + JOIN model_releases r2r ON r2r.id = r2.release_id + WHERE r2.block_sha256 = b.sha256 AND r2.release_id <> $1 + AND r2r.state IN ('verifying', 'published')) + GROUP BY COALESCE(b.payer_did, r.publisher_did)", + ) + .bind(release_id) + .fetch_all(&mut **tx) + .await?; + sqlx::query( + "UPDATE model_blocks b SET payer_did = NULL + WHERE b.payer_did IS NOT NULL + AND b.sha256 IN ( + SELECT rb.block_sha256 FROM model_release_blocks rb + WHERE rb.release_id = $1) + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks r2 + JOIN model_releases r2r ON r2r.id = r2.release_id + WHERE r2.block_sha256 = b.sha256 AND r2.release_id <> $1 + AND r2r.state IN ('verifying', 'published'))", + ) + .bind(release_id) + .execute(&mut **tx) + .await?; + sqlx::query("DELETE FROM model_release_blocks WHERE release_id = $1") + .bind(release_id) + .execute(&mut **tx) + .await?; + for (payer, bytes) in per_payer { + sqlx::query( + "UPDATE model_quota_usage SET bytes_used = GREATEST(bytes_used - $2, 0) + WHERE did = $1", + ) + .bind(&payer) + .bind(bytes) + .execute(&mut **tx) + .await?; + } + Ok(()) + } + + pub async fn model_verifying_ids(&self, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases WHERE state = 'verifying' + ORDER BY created_at LIMIT $1", + ) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + // ── sweep ────────────────────────────────────────────────────────────── + + pub async fn model_expire_sessions(&self) -> Result> { + Ok(sqlx::query_scalar( + "UPDATE model_upload_sessions SET state = 'expired' + WHERE state = 'open' AND expires_at <= $1 + RETURNING id", + ) + .bind(ts_now()) + .fetch_all(&self.pool) + .await?) + } + + /// Drop links under every expired session, not only the ids this pass + /// expired: a failed DELETE must not strand links under sessions that + /// are never re-selected. + pub async fn model_drop_sessions_blocks(&self) -> Result<()> { + sqlx::query( + "DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE sb.session_id = s.id AND s.state = 'expired'", + ) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Stamp `unreferenced_since` on blocks that lost every live reference, + /// and clear it on blocks that regained one. Returns rows marked. + pub async fn model_remark_liveness(&self) -> Result { + let marked = sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = $1 + WHERE b.unreferenced_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open')", + ) + .bind(ts_now()) + .execute(&self.pool) + .await? + .rows_affected(); + sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = NULL + WHERE b.unreferenced_since IS NOT NULL + AND (EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + OR EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open'))", + ) + .execute(&self.pool) + .await?; + Ok(marked) + } + + pub async fn model_stale_blocks(&self, grace_secs: i64, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sha256 FROM model_blocks + WHERE unreferenced_since < $1 + LIMIT $2", + ) + .bind(ts_from_now(-grace_secs)) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + /// Under the same row lock the claim path takes, confirm the block is + /// still unreferenced. The caller keeps the transaction open across the + /// store delete, then calls `model_tx_delete_block_row`. + pub async fn model_tx_block_still_dead( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + grace_secs: i64, + ) -> Result { + // Lock the block row first. READ COMMITTED snapshots are taken per + // statement, so folding the liveness subqueries into the locking + // SELECT would evaluate them against the pre-lock snapshot and miss + // a link committed while this statement waited. + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM model_blocks WHERE sha256 = $1 FOR UPDATE)", + ) + .bind(sha) + .fetch_one(&mut **tx) + .await?; + if !exists { + return Ok(true); + } + // The grace clock is re-checked too: a block re-marked after the + // stale selection ran must earn its new grace period, not die on + // the old one. + Ok(sqlx::query_scalar::<_, bool>( + "SELECT b.unreferenced_since IS NOT NULL + AND b.unreferenced_since < $2 + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = $1 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = $1 AND s.state = 'open') + FROM model_blocks b WHERE b.sha256 = $1", + ) + .bind(sha) + .bind(ts_from_now(-grace_secs)) + .fetch_one(&mut **tx) + .await?) + } + + pub async fn model_tx_delete_block_row( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + ) -> Result<()> { + sqlx::query("DELETE FROM model_blocks WHERE sha256 = $1") + .bind(sha) + .execute(&mut **tx) + .await?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn migrated(pool: sqlx::PgPool) -> Db { + let db = Db::for_testing(pool.clone()); + db.run_migrations().await.unwrap(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r1', 'repo', 'did:owner', TRUE, 'main', 't', 't', '/r1')", + ) + .execute(&pool) + .await + .unwrap(); + db + } + + #[sqlx::test] + async fn admit_bytes_enforces_session_cap_and_slides_expiry(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + let first = db + .model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); + assert_eq!(first.bytes_received, 100); + assert!(first.expires_at > s.expires_at); + // Over the per-identity session cap: refused. + assert!(db + .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) + .await + .unwrap() + .is_none()); + // Within the cap still admits. + assert!(db + .model_admit_bytes(&s.id, 900, 3600, 1000, 10_000) + .await + .unwrap() + .is_some()); + } + + #[sqlx::test] + async fn record_block_refunds_duplicate_within_session(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "a".repeat(64); + // First PUT: admit the block's bytes, then record the link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); + assert!(!db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + // Same block again: the second admission is charged then refunded + // when the record sees the existing link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("second admission"); + assert!(db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + let s2 = db.model_load_session(&s.id).await.unwrap().unwrap(); + assert_eq!(s2.bytes_received, 100); + } + + #[sqlx::test] + async fn expire_then_sweep_marks_and_deletes_dead_blocks(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "b".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + // Blocks are born stamped; while the session is open, remarking + // clears the stamp. + db.model_remark_liveness().await.unwrap(); + let stamp: Option = + sqlx::query_scalar("SELECT unreferenced_since FROM model_blocks WHERE sha256 = $1") + .bind(&sha) + .fetch_one(&pool) + .await + .unwrap(); + assert!(stamp.is_none()); + + // Force the session expired and drop its links. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_expire_sessions().await.unwrap(), + vec![s.id.clone()] + ); + db.model_drop_sessions_blocks().await.unwrap(); + + // The block is now unreferenced: marked, then deletable past grace. + assert_eq!(db.model_remark_liveness().await.unwrap(), 1); + sqlx::query("UPDATE model_blocks SET unreferenced_since = $1 WHERE sha256 = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_stale_blocks(3600, 10).await.unwrap(), + vec![sha.clone()] + ); + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_block_still_dead(&mut tx, &sha, 3600) + .await + .unwrap()); + db.model_tx_delete_block_row(&mut tx, &sha).await.unwrap(); + tx.commit().await.unwrap(); + } + + #[sqlx::test] + async fn a_remarked_block_earns_its_new_grace_period(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "f".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at, unreferenced_since) VALUES ($1, 1, $2, $2)") + .bind(&sha) + .bind(ts_from_now(-7200)) + .execute(&pool) + .await + .unwrap(); + // Selected while stale, then re-marked moments ago (as a racing + // unmark/remark cycle would): the fresh stamp restarts the grace + // clock and the block must not be deleted on the old one. + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_block_still_dead(&mut tx, &sha, 3600) + .await + .unwrap()); + sqlx::query("UPDATE model_blocks SET unreferenced_since = $1 WHERE sha256 = $2") + .bind(ts_from_now(-10)) + .bind(&sha) + .execute(&mut *tx) + .await + .unwrap(); + assert!(!db + .model_tx_block_still_dead(&mut tx, &sha, 3600) + .await + .unwrap()); + tx.commit().await.unwrap(); + } + + #[sqlx::test] + async fn caps_ignore_wall_clock_dead_open_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // A same-owner peer and a different-owner peer each hold 900 bytes. + let peer_same = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + let peer_other = db.model_open_session("did:other", "r1", 60).await.unwrap(); + for s in [&peer_same, &peer_other] { + db.model_admit_bytes(&s.id, 900, 3600, 10_000, 100_000) + .await + .unwrap() + .expect("peer admission"); + } + // Past the wall-clock TTL the rows still say 'open' until the sweep. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1") + .bind("2000-01-01T00:00:00+00:00") + .execute(&pool) + .await + .unwrap(); + + // Claim-side node total must not count the dead sessions. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!(db.model_tx_node_used(&mut tx).await.unwrap(), 0); + tx.rollback().await.unwrap(); + + // Per-owner term: the dead same-owner peer must not eat the cap. + let live = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live.id, 200, 3600, 1000, 100_000) + .await + .unwrap() + .is_some()); + // Node-wide term: both dead peers (1800) must not eat a 1000 cap. + let live2 = db.model_open_session("did:third", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live2.id, 200, 3600, 10_000, 1000) + .await + .unwrap() + .is_some()); + } + + async fn seed_release_with_block( + pool: &sqlx::PgPool, + publisher: &str, + state: &str, + commit: &str, + sha: &str, + ) { + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't') + ON CONFLICT DO NOTHING", + ) + .bind(sha) + .execute(pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1', $1, 'main', $3, $2, 'm', 's', 'i', 'ss', '\\x00', 't') + RETURNING id", + ) + .bind(commit) + .bind(state) + .bind(publisher) + .fetch_one(pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1, $2)") + .bind(rid) + .bind(sha) + .execute(pool) + .await + .unwrap(); + } + + async fn session_bytes(pool: &sqlx::PgPool, id: &str) -> i64 { + sqlx::query_scalar("SELECT bytes_received FROM model_upload_sessions WHERE id = $1") + .bind(id) + .fetch_one(pool) + .await + .unwrap() + } + + #[sqlx::test] + async fn record_block_refunds_only_bytes_a_live_release_already_carries(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + + // Block already carried by the owner's published release: claim + // authorizes it without a link and billed it, so the PUT is free + // and leaves no link behind to outlive the release. + let carried = "d".repeat(64); + seed_release_with_block(&pool, "did:owner", "published", "c1", &carried).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(db + .model_record_block(&s.id, &carried, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 0); + let links: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM model_session_blocks WHERE session_id = $1") + .bind(&s.id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(links, 0); + + // Another publisher's published release bills its owner, not this + // session, and the session needs the link to claim the block. + let theirs = "9".repeat(64); + seed_release_with_block(&pool, "did:other", "published", "c3", &theirs).await; + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s.id, &theirs, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 100); + + // Block only in a rejected release: nothing bills it, so the + // session keeps the charge. + let dead = "e".repeat(64); + seed_release_with_block(&pool, "did:owner", "rejected", "c2", &dead).await; + let s2 = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s2.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s2.id, &dead, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s2.id).await, 100); + + // Block held only by another open session: that session is the + // one billed, and a refund here would let a session pair hold + // unbilled bytes once the first expires. + let held = "f".repeat(64); + let a = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let b = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + for x in [&a, &b] { + db.model_admit_bytes(&x.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + } + assert!(!db.model_record_block(&a.id, &held, 100, 100).await.unwrap()); + assert!(!db.model_record_block(&b.id, &held, 100, 100).await.unwrap()); + assert_eq!(session_bytes(&pool, &b.id).await, 100); + } + + #[sqlx::test] + async fn session_blocks_ignore_expired_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "c".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap(), + vec![sha.clone()] + ); + tx.rollback().await.unwrap(); + + // Past the wall-clock TTL the row still says 'open' until the sweep + // runs, yet the claim-side reachability set must already be empty. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap() + .is_empty()); + tx.rollback().await.unwrap(); + } + + #[sqlx::test] + async fn reserve_quota_caps_first_and_later_claims(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // First claim over cap: refused, and no row may be left behind. + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 2000, 1000) + .await + .unwrap() + .is_none()); + tx.commit().await.unwrap(); + let row: Option = + sqlx::query_scalar("SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'") + .fetch_optional(&pool) + .await + .unwrap(); + assert!(row.is_none()); + // Within cap inserts, over-cap update refuses, within-cap update adds. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 600, 1000) + .await + .unwrap(), + Some(600) + ); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 500, 1000) + .await + .unwrap() + .is_none()); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 400, 1000) + .await + .unwrap(), + Some(1000) + ); + tx.commit().await.unwrap(); + } + + #[sqlx::test] + async fn release_blocks_keep_a_block_alive(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "c".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 5, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1','c1','main','did:owner','published','m','s','i','ss','\\x00','t') + RETURNING id", + ) + .execute(&pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar("SELECT id FROM model_releases WHERE repo_id = 'r1'") + .fetch_one(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1,$2)") + .bind(rid) + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + // Live release reference: the block never goes stale. + assert_eq!(db.model_remark_liveness().await.unwrap(), 0); + assert!(db.model_stale_blocks(-1, 10).await.unwrap().is_empty()); + let mut tx = db.model_begin().await.unwrap(); + assert!(!db + .model_tx_block_still_dead(&mut tx, &sha, 3600) + .await + .unwrap()); + tx.commit().await.unwrap(); + } + + /// Run the claim transaction's charge path against `shas` (unclaimed + /// bytes -> per-payer quota -> release insert -> block link/payer stamp) + /// and return the release id. The HTTP and git halves of claim_release + /// are not exercised here. + async fn claim_as(db: &Db, publisher: &str, commit: &str, repo: &str, shas: &[String]) -> i64 { + let mut tx = db.model_begin().await.unwrap(); + db.model_tx_advisory_lock(&mut tx, crate::models::CLAIM_LOCK_KEY) + .await + .unwrap(); + let new_bytes = db.model_tx_unclaimed_bytes(&mut tx, shas).await.unwrap(); + db.model_tx_reserve_quota(&mut tx, publisher, new_bytes, i64::MAX) + .await + .unwrap(); + let persist = ClaimPersist { + signature: "s".into(), + signature_input: "i".into(), + signing_string: "ss".into(), + body: vec![0], + request_digest: format!("{publisher}-{commit}"), + }; + let row = db + .model_tx_insert_release( + &mut tx, repo, commit, "main", publisher, "m", None, &persist, + ) + .await + .unwrap(); + db.model_tx_link_release_blocks(&mut tx, row.id, publisher, shas) + .await + .unwrap(); + tx.commit().await.unwrap(); + row.id + } + + async fn quota_used(pool: &sqlx::PgPool, did: &str) -> i64 { + sqlx::query_scalar("SELECT COALESCE(bytes_used, 0) FROM model_quota_usage WHERE did = $1") + .bind(did) + .fetch_optional(pool) + .await + .unwrap() + .unwrap_or(0) + } + + #[sqlx::test] + async fn rejection_refunds_the_payer_not_the_release_publisher(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "a".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + // A claims the block (pays 100); B's later claim is free. + let ra = claim_as(&db, "did:a", "ca", "r1", std::slice::from_ref(&sha)).await; + let rb = claim_as(&db, "did:b", "cb", "r1", std::slice::from_ref(&sha)).await; + assert_eq!(quota_used(&pool, "did:a").await, 100); + assert_eq!(quota_used(&pool, "did:b").await, 0); + + // Rejecting A's release first changes nothing: the block is still + // carried by B's live release, so nothing is freed. + db.model_reject_release(ra, "x").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 100); + // Rejecting B's release then frees the block, and the refund goes + // to the payer A, never to the rejected release's publisher B (who + // was never charged). + db.model_reject_release(rb, "x").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 0); + assert_eq!(quota_used(&pool, "did:b").await, 0); + // The payer stamp was cleared: a re-claim would charge anew, not + // refund-into-reclaim. + let payer: Option = + sqlx::query_scalar("SELECT payer_did FROM model_blocks WHERE sha256 = $1") + .bind(&sha) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(payer, None); + } + + #[sqlx::test] + async fn free_claimer_rejection_first_keeps_the_payer_charge(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "b".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + let ra = claim_as(&db, "did:a", "ca", "r1", std::slice::from_ref(&sha)).await; + let rb = claim_as(&db, "did:b", "cb", "r1", std::slice::from_ref(&sha)).await; + // B rejects first: still live under A, so nothing moves. + db.model_reject_release(rb, "x").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 100); + let payer: Option = + sqlx::query_scalar("SELECT payer_did FROM model_blocks WHERE sha256 = $1") + .bind(&sha) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(payer.as_deref(), Some("did:a")); + // Then A: freed, refunded. + db.model_reject_release(ra, "x").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 0); + } + + #[sqlx::test] + async fn delete_repo_refunds_live_release_charges(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r2', 'repo2', 'did:a', TRUE, 'main', 't', 't', '/r2')", + ) + .execute(&pool) + .await + .unwrap(); + let sha = "c".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + // A publishes the block on r2 (payer A); B free-claims it on r1. + let ra = claim_as(&db, "did:a", "ca", "r2", std::slice::from_ref(&sha)).await; + sqlx::query("UPDATE model_releases SET state = 'published' WHERE id = $1") + .bind(ra) + .execute(&pool) + .await + .unwrap(); + claim_as(&db, "did:b", "cb", "r1", std::slice::from_ref(&sha)).await; + assert_eq!(quota_used(&pool, "did:a").await, 100); + + // Deleting r1 must not touch A's charge: the block is still carried + // by r2's live release. + db.delete_repo_by_id("r1").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 100); + // Deleting r2 frees it: the payer is refunded even though the + // cascade also dropped the rows. + db.delete_repo_by_id("r2").await.unwrap(); + assert_eq!(quota_used(&pool, "did:a").await, 0); + } + + #[sqlx::test] + async fn rejection_refunds_the_publisher_for_a_legacy_unpayered_block(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "d".repeat(64); + seed_release_with_block(&pool, "did:c", "verifying", "cl", &sha).await; + sqlx::query("INSERT INTO model_quota_usage (did, bytes_used) VALUES ('did:c', 100)") + .execute(&pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar("SELECT id FROM model_releases WHERE commit_sha = 'cl'") + .fetch_one(&pool) + .await + .unwrap(); + db.model_reject_release(rid, "x").await.unwrap(); + assert_eq!(quota_used(&pool, "did:c").await, 0); + } + + async fn seed_verifying_release(pool: &sqlx::PgPool, commit: &str) -> i64 { + // A distinct publisher per row: the one-verifying index is real. + sqlx::query_scalar( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1', $1, 'main', 'did:' || $1, 'verifying', 'm', 's', 'i', 'ss', '\\x00', 't') + RETURNING id", + ) + .bind(commit) + .fetch_one(pool) + .await + .unwrap() + } + + #[sqlx::test] + async fn publish_if_public_gates_on_the_locked_repo_state(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + + // Public repo: the verifying release publishes. + let rid = seed_verifying_release(&pool, "cp1").await; + assert_eq!( + db.model_publish_if_public(rid, "r1").await.unwrap(), + PublishOutcome::Published + ); + + // A visibility rule appearing between the handler check and publish + // flips the outcome to NoLongerPublic and the row stays verifying. + sqlx::query( + "INSERT INTO visibility_rules + (id, repo_id, path_glob, mode, reader_dids, created_by, created_at) + VALUES ('v1', 'r1', '/x', 'withhold', '[]', 'did:owner', 't')", + ) + .execute(&pool) + .await + .unwrap(); + let rid2 = seed_verifying_release(&pool, "cp2").await; + assert_eq!( + db.model_publish_if_public(rid2, "r1").await.unwrap(), + PublishOutcome::NoLongerPublic + ); + let state: String = sqlx::query_scalar("SELECT state FROM model_releases WHERE id = $1") + .bind(rid2) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(state, "verifying"); + + // With the rule gone the repo is fully public again: a row already + // out of verifying is NotVerifying, not a re-publish. + sqlx::query("DELETE FROM visibility_rules WHERE repo_id = 'r1'") + .execute(&pool) + .await + .unwrap(); + let rid3 = seed_verifying_release(&pool, "cp3").await; + sqlx::query("UPDATE model_releases SET state = 'published' WHERE id = $1") + .bind(rid3) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_publish_if_public(rid3, "r1").await.unwrap(), + PublishOutcome::NotVerifying + ); + + // A missing repo row is NoLongerPublic. + let rid4 = seed_verifying_release(&pool, "cp4").await; + assert_eq!( + db.model_publish_if_public(rid4, "gone").await.unwrap(), + PublishOutcome::NoLongerPublic + ); + } +} diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index c296eb0b..2f4d351d 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -1,6 +1,16 @@ use anyhow::{bail, Context, Result}; use std::path::Path; use std::process::Command; +/// Ref namespaces clients must never see: `refs/gitlawb/requests/*` is +/// internal bookkeeping, and `refs/gitlawb/releases/*` pins published model +/// releases so gc never prunes them. One shared list keeps the +/// repo-config writers in lockstep. +pub(crate) const HIDDEN_REFS: &[(&str, &str)] = &[ + ("uploadpack.hideRefs", "refs/gitlawb/requests/"), + ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), +]; /// Initialize a new bare git repository with SHA-1 object format (default). /// @@ -88,14 +98,11 @@ pub fn init_bare(path: &Path) -> Result<()> { Ok(_) => {} } - // Hide the internal marker namespace from clone/fetch - // advertisement. `refs/gitlawb/requests/*` carries request UUIDs - // and would otherwise leak per-push metadata to every client and - // grow advertisement cost with push count. - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ] { + // Hide the internal marker namespaces from clone/fetch + // advertisement: `refs/gitlawb/requests/*` would leak per-push + // metadata to every client and grow advertisement cost with push + // count. + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: same init-time local `git config` as above. let out = Command::new("git") .args(["config", "--add", key, value]) @@ -126,10 +133,7 @@ pub fn ensure_marker_hidden(repo_path: &Path) { } pub fn ensure_marker_hidden_checked(repo_path: &Path) -> Result<()> { - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ] { + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: reached only through the #[allow(dead_code)] // ensure_marker_hidden wrapper; the push path runs this config through // verify_recovery_prereqs_bounded's timeout runner. @@ -220,10 +224,7 @@ pub async fn verify_recovery_prereqs_bounded( ); } } - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ] { + for &(key, value) in HIDDEN_REFS { let current = run_git(git_bin, repo_path, &["config", "--get-all", key], deadline).await?; let already = String::from_utf8_lossy(¤t.stdout) .lines() @@ -356,7 +357,7 @@ pub async fn delete_marker_bounded( /// serving) or a live push's admission permits, lease, and write lock. /// `kill_on_drop(true)` makes the timeout real for these plumbing commands /// (no helper processes to reparent, unlike receive-pack's pack-objects). -async fn run_git_bounded( +pub(crate) async fn run_git_bounded( git_bin: &str, repo_path: &Path, args: &[&str], @@ -403,6 +404,87 @@ async fn run_git_bounded( .map_err(|_| anyhow::anyhow!("{label} timed out"))? } +/// [`run_git_bounded`] plus a hard cap on captured stdout: reads the pipe +/// incrementally and kills the child the moment output exceeds +/// `max_stdout`, so a huge blob never lands fully in memory. Other callers +/// keep the uncapped helper above. +pub(crate) async fn run_git_bounded_capped( + git_bin: &str, + repo_path: &Path, + args: &[&str], + stdin_bytes: &[u8], + timeout: std::time::Duration, + label: &str, + max_stdout: usize, +) -> Result { + use tokio::io::AsyncReadExt; + use tokio::io::AsyncWriteExt; + use tokio::process::Command as AsyncCommand; + let fut = async { + let mut cmd = AsyncCommand::new(git_bin); + cmd.kill_on_drop(true); + cmd.args(args).current_dir(repo_path); + cmd.stdout(std::process::Stdio::piped()); + cmd.stderr(std::process::Stdio::piped()); + if !stdin_bytes.is_empty() { + cmd.stdin(std::process::Stdio::piped()); + } else { + cmd.stdin(std::process::Stdio::null()); + } + let mut child = cmd.spawn().context(format!("{label} spawn failed"))?; + if !stdin_bytes.is_empty() { + child + .stdin + .as_mut() + .context(format!("{label} stdin pipe"))? + .write_all(stdin_bytes) + .await + .context(format!("{label} stdin write"))?; + } + let mut stderr = child.stderr.take(); + let err_task = tokio::spawn(async move { + let mut buf = Vec::new(); + if let Some(mut e) = stderr.take() { + let _ = e.read_to_end(&mut buf).await; + } + buf + }); + let mut stdout = Vec::new(); + let mut oversized = false; + if let Some(mut pipe) = child.stdout.take() { + let mut chunk = [0u8; 16 * 1024]; + loop { + match pipe.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + if stdout.len() + n > max_stdout { + oversized = true; + break; + } + stdout.extend_from_slice(&chunk[..n]); + } + } + } + } + if oversized { + let _ = child.kill().await; + let _ = child.wait().await; + let _ = err_task.await; + anyhow::bail!("{label} output exceeded {max_stdout} bytes"); + } + let stderr = err_task.await.unwrap_or_default(); + let status = child.wait().await.context(format!("{label} wait"))?; + Ok(std::process::Output { + status, + stdout, + stderr, + }) + }; + tokio::time::timeout(timeout, fut) + .await + .map_err(|_| anyhow::anyhow!("{label} timed out"))? +} + /// Bounded [`list_refs`]: same listing through the configured git binary /// with a timeout. Used by startup reconcile, which awaits recovery before /// serving — an unbounded `for-each-ref` would hold startup forever past diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 0784f4dc..d9cc9243 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -22,6 +22,7 @@ mod graphql; mod icaptcha; mod ipfs_pin; mod metrics; +pub mod models; mod operator; mod p2p; mod pinata; @@ -919,6 +920,16 @@ pub async fn run() -> Result<()> { // with the one-shot reconcile/drain on backlog rows. let _due_request_worker = spawn_due_request_worker(&state); + // Model hosting workers (verify + sweep) only run while the operator + // flag is on; the block store is the flag's live form. + let mut model_workers = Vec::new(); + if state.block_store.is_some() { + model_workers.push(tokio::spawn(models::verify::run_verify_worker( + state.clone(), + ))); + model_workers.push(tokio::spawn(models::sweep::run_sweep_worker(state.clone()))); + } + // `into_make_service_with_connect_info` exposes the socket peer address as // `ConnectInfo` so the push limiter can key on the real client // when no trusted proxy header applies (see `rate_limit::client_key`). diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs new file mode 100644 index 00000000..d1e48f50 --- /dev/null +++ b/crates/twigpine-node/src/models/claim.rs @@ -0,0 +1,342 @@ +//! Release claim: the commit point. The ordered checks from KTD5 run here; +//! the check-then-act tail (other-verifying probe, quota reservation, release +//! insert) runs inside one transaction under the claim advisory lock. + +use twigpine_core::model::manifest::{Manifest, StorageKind}; + +use crate::db::model_queries::ClaimPersist; +use crate::db::RepoRecord; +use crate::error::AppError; +use crate::state::AppState; + +use super::{ReleaseRow, CLAIM_LOCK_KEY}; + +/// Everything the handler verified about the signed request, threaded so the +/// release row is the replay ledger: a replayed claim resolves by request +/// digest to the original row instead of writing a second one. +pub struct ClaimMaterial { + pub request_digest: String, + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, +} + +fn bad_request(msg: impl Into) -> AppError { + AppError::BadRequest(msg.into()) +} + +/// Hard cap on the bytes a `git show` of release metadata may return: a +/// manifest listing every file of a large model is still a few hundred KiB, +/// so 8 MiB is generous and a blob beyond it cannot be a real manifest. +const MAX_RELEASE_METADATA_BYTES: usize = 8 * 1024 * 1024; + +pub(crate) async fn git_show( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + path: &str, +) -> Result>, AppError> { + let spec = format!("{commit}:{path}"); + let out = crate::git::store::run_git_bounded_capped( + git_bin, + disk_path, + &["show", &spec], + b"", + std::time::Duration::from_secs(30), + "git show", + MAX_RELEASE_METADATA_BYTES, + ) + .await + .map_err(AppError::Internal)?; + if out.status.success() { + return Ok(Some(out.stdout)); + } + match out.status.code() { + // Path missing inside a real commit: honest absence. + Some(128) => Ok(None), + _ => Err(AppError::Internal(anyhow::anyhow!( + "git show {spec} failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))), + } +} + +pub async fn commit_exists( + git_bin: &str, + disk_path: &std::path::Path, + sha: &str, +) -> Result { + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["cat-file", "-e", &format!("{sha}^{{commit}}")], + b"", + std::time::Duration::from_secs(30), + "git cat-file", + ) + .await + .map_err(AppError::Internal)?; + Ok(out.status.success()) +} + +/// Read and anchor-verify the release manifest at `commit`. The verifying key +/// comes from the repo owner DID (the independent anchor), never the artifact. +pub(crate) async fn read_verified_manifest( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + owner_did: &str, +) -> Result<(Vec, Manifest), AppError> { + let manifest_bytes = git_show(git_bin, disk_path, commit, ".twigpine/model-release.json") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.json"))?; + let sig_text = git_show(git_bin, disk_path, commit, ".twigpine/model-release.sig") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; + let sig_text = + String::from_utf8(sig_text).map_err(|_| bad_request("model-release.sig is not utf-8"))?; + let did: twigpine_core::did::Did = crate::db::canonical_did(owner_did) + .parse() + .map_err(|_| bad_request("repo owner DID does not resolve"))?; + let manifest = twigpine_core::model::manifest::verify(&manifest_bytes, &sig_text, &did) + .map_err(|e| bad_request(format!("manifest signature rejected: {e}")))?; + Ok((manifest_bytes, manifest)) +} + +/// Claim `commit` on `branch` as a model release. The handler has already +/// proven the feature flag, the owner gate, and full publicity; everything +/// from the manifest read down runs here. +pub async fn claim_release( + state: &AppState, + record: &RepoRecord, + caller: &str, + commit: &str, + branch: &str, + material: &ClaimMaterial, +) -> Result { + let db = &state.db; + let disk_path = std::path::PathBuf::from(&record.disk_path); + + if !commit_exists(&state.git_bin, &disk_path, commit).await? { + return Err(bad_request("commit not found in this repository")); + } + let (manifest_bytes, manifest) = + read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; + let expected_repo = format!( + "{}/{}", + crate::db::canonical_did(&record.owner_did), + record.name + ); + if manifest.repo != expected_repo { + return Err(bad_request("manifest names a different repository")); + } + if manifest.reconstruction.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return Err(bad_request( + "chunked files declared but the manifest has no reconstruction object", + )); + } + let m_sha = twigpine_core::cid::sha256_hex(&manifest_bytes); + let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); + let blocks = super::referenced_blocks(state, &manifest).await?; + + // Exact replay resolves before the parent publicity check: a parent made + // private since the first claim must not turn the recorded row into a + // rejection. The lookup repeats under the claim lock below, before any + // insert, so a first claim still serializes correctly. + if let Some(existing) = db.model_release_by_digest(&material.request_digest).await? { + return Ok(existing); + } + + // Resolve the declared parent before the transaction: the repo lookup + // uses its own pool connection and must not sit behind the global + // advisory lock, where pool pressure would stall every claim. + let parent = match &manifest.parent { + None => None, + Some(parent) => { + let (powner, pname) = parent + .repo + .split_once('/') + .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; + // A parent only confers blocks while its repo is fully public: + // a withdrawn parent cannot launder references. + let (precord, prules) = + crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; + // A mirror parent row fails closed the same way: its publicity + // pair is vacuous. + if !precord.is_public || !prules.is_empty() || precord.id.contains('/') { + return Err(bad_request( + "declared parent's repo is no longer fully public", + )); + } + Some((precord.id, parent.commit.clone())) + } + }; + + let mut tx = db.model_begin().await?; + db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; + // The claim's node-cap check must serialize against the admission-side + // ledger writes the PUT path takes under MODEL_ADMIT_LOCK. + db.model_tx_advisory_lock(&mut tx, crate::db::model_queries::MODEL_ADMIT_LOCK) + .await?; + + // Replay by request digest, then idempotent re-claim by (repo, commit): + // both return the original row, whatever its state. A rejected release + // is final for that commit: verification judges the pinned, immutable + // commit, so a retry would re-run the same checks, and the publisher + // retries by minting a new commit. + if let Some(existing) = db + .model_tx_release_by_digest(&mut tx, &material.request_digest) + .await? + { + tx.commit().await?; + return Ok(existing); + } + if let Some(existing) = db + .model_tx_release_by_commit(&mut tx, &record.id, commit) + .await? + { + tx.commit().await?; + return Ok(existing); + } + + // Lock the referenced block rows so a racing sweep cannot delete one + // mid-claim, and require each to exist. + if !blocks.is_empty() { + let present: std::collections::HashSet = db + .model_tx_lock_present_blocks(&mut tx, &blocks) + .await? + .into_iter() + .collect(); + if let Some(missing) = blocks.iter().find(|b| !present.contains(b.as_str())) { + return Err(bad_request(format!( + "manifest references block {} which is not stored on this node", + missing.get(..16).unwrap_or(missing) + ))); + } + } + + // Authorization: every referenced block must arrive through the caller's + // open session, a live release of the caller's, or the declared parent. + let caller_session_blocks: std::collections::HashSet = db + .model_tx_session_blocks(&mut tx, caller) + .await? + .into_iter() + .collect(); + let caller_release_blocks: std::collections::HashSet = db + .model_tx_publisher_release_blocks(&mut tx, caller) + .await? + .into_iter() + .collect(); + let parent_blocks: std::collections::HashSet = match &parent { + None => std::collections::HashSet::new(), + Some((prepo_id, pcommit)) => { + // Existence of a published parent release is the check, not its + // block links: an all-Git parent links no blocks yet still + // stands as a parent. + let published = db + .model_tx_release_by_commit(&mut tx, prepo_id, pcommit) + .await? + .is_some_and(|r| r.state == "published"); + if !published { + return Err(bad_request( + "declared parent is not a published release on this node", + )); + } + db.model_tx_release_blocks_at_commit(&mut tx, prepo_id, pcommit) + .await? + .into_iter() + .collect() + } + }; + for b in &blocks { + let allowed = caller_session_blocks.contains(b) + || caller_release_blocks.contains(b) + || parent_blocks.contains(b); + if !allowed { + return Err(bad_request(format!( + "block {} is not reachable through an open session, a prior \ + release, or the declared parent", + b.get(..16).unwrap_or(b) + ))); + } + } + + // One verifying release per publisher. + if db.model_tx_has_verifying(&mut tx, caller).await? { + return Err(AppError::Conflict( + "another release is still verifying; wait for it to settle".into(), + )); + } + + // New bytes are the distinct blocks not already claimed by any live + // release anywhere: first claimer pays, dedup stays free. + let new_bytes = db.model_tx_unclaimed_bytes(&mut tx, &blocks).await?; + + // Per-identity quota, atomically. + let did_cap = state.config.model_quota_bytes as i64; + let admitted = db + .model_tx_reserve_quota(&mut tx, caller, new_bytes, did_cap) + .await?; + if new_bytes > 0 && admitted.is_none() { + return Err(bad_request(format!( + "per-publisher model quota ({did_cap} bytes) would be exceeded" + ))); + } + + let persist = ClaimPersist { + signature: material.signature.clone(), + signature_input: material.signature_input.clone(), + signing_string: material.signing_string.clone(), + body: material.body.clone(), + request_digest: material.request_digest.clone(), + }; + let row = db + .model_tx_insert_release( + &mut tx, + &record.id, + commit, + branch, + caller, + &m_sha, + rec_sha.as_deref(), + &persist, + ) + .await?; + let release_id = row.id; + + // Claimed blocks leave the caller's open sessions' charge: the + // release now carries them. This must precede the node-cap check or + // the just-claimed bytes count twice (once under quota, once under + // the sessions they still appear linked to). + db.model_tx_link_release_blocks(&mut tx, release_id, caller, &blocks) + .await?; + + // Node-wide quota in the same transaction: claimed bytes plus open + // session bytes. + let node_cap = state.config.model_node_quota_bytes as i64; + let node_total = db.model_tx_node_used(&mut tx).await?; + if node_total > node_cap { + return Err(AppError::TooManyRequests(format!( + "node model storage cap ({node_cap} bytes) would be exceeded" + ))); + } + + tx.commit().await?; + + // Pin the commit under the hidden release ref now: between claim and + // publish a force-push plus gc could drop the commit the verifier + // needs. Best-effort; the publish path writes it again. + if let Err(e) = super::verify::write_release_ref(&state.git_bin, &disk_path, commit).await { + tracing::warn!(%commit, "release ref write at claim failed: {e}"); + } + Ok(row) +} diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs new file mode 100644 index 00000000..f4e3e036 --- /dev/null +++ b/crates/twigpine-node/src/models/mod.rs @@ -0,0 +1,86 @@ +//! Open-weight model hosting: upload sessions, release claims, verification, +//! and reclamation. Feature-gated by `model_hosting_enabled`; the routes are +//! mounted only when `state.block_store` is `Some`, and every handler +//! re-checks it. +//! +//! All SQL lives in `crate::db::model_queries` as typed `Db` methods; the +//! free functions here are the store read helpers the handlers and workers +//! share. + +pub mod claim; +pub mod sweep; +pub mod verify; + +use std::sync::Arc; + +use crate::db::model_queries::ModelRelease; +use crate::error::AppError; +use crate::state::AppState; + +pub(crate) use crate::db::model_queries::ts_now; + +/// Transport + store hard cap on one block (KTD1: 64 MiB target, 128 MiB cap). +pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; + +/// Advisory-lock key serializing claim admission: the "one verifying release +/// per publisher" check and the quota reservations are check-then-act, so the +/// lock is what makes them safe under racing claims. +pub(crate) const CLAIM_LOCK_KEY: i64 = 0x6D6F64656C636C61; // "modelcla" + +pub type ReleaseRow = ModelRelease; + +pub async fn read_range( + store: &Arc, + sha: &str, + start: u64, + len: u64, +) -> Result, crate::blockstore::BlockStoreError> { + use futures::StreamExt; + let id = crate::blockstore::BlockId::parse(sha) + .map_err(|e| crate::blockstore::BlockStoreError::Backend(e.to_string()))?; + let end = start + .checked_add(len) + .ok_or(crate::blockstore::BlockStoreError::OutOfRange)?; + let mut stream = store.get_range(&id, start, end).await?; + let mut out = Vec::with_capacity(len.min(1 << 22) as usize); + while let Some(chunk) = stream.next().await { + out.extend_from_slice(&chunk?); + } + Ok(out) +} + +pub async fn read_block( + store: &Arc, + sha: &str, + size: u64, +) -> Result, crate::blockstore::BlockStoreError> { + read_range(store, sha, 0, size).await +} + +/// The set of blocks a manifest references: the reconstruction object itself +/// (stored as its own content block) plus every data block the parsed +/// reconstruction names. The reconstruction object is read from the block +/// store and validated before its block table is trusted. +pub async fn referenced_blocks( + state: &AppState, + manifest: &twigpine_core::model::manifest::Manifest, +) -> Result, AppError> { + use twigpine_core::model::reconstruction::Reconstruction; + let Some(rec_ref) = &manifest.reconstruction else { + return Ok(Vec::new()); + }; + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::NotFound("model hosting is not enabled".into()))?; + let bytes = read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|e| AppError::BadRequest(format!("reconstruction object unreadable: {e}")))?; + let rec = Reconstruction::parse(&bytes) + .map_err(|e| AppError::BadRequest(format!("reconstruction object invalid: {e}")))?; + let mut out = vec![rec_ref.sha256.clone()]; + for b in &rec.blocks { + out.push(b.sha256.clone()); + } + Ok(out) +} diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs new file mode 100644 index 00000000..8337773e --- /dev/null +++ b/crates/twigpine-node/src/models/sweep.rs @@ -0,0 +1,104 @@ +//! Reclamation: expire upload sessions, drop their block links, mark blocks +//! unreferenced, and delete unreferenced blocks after the unclaimed grace +//! period. Blocks referenced by a live release or an open session survive. +//! The claim path locks block rows (`FOR UPDATE`) before referencing them, +//! and the sweep's delete candidate is re-checked inside its own +//! transaction, so a claim in flight can never lose a block mid-reference. + +use crate::error::AppError; +use crate::state::AppState; + +/// A release still `verifying` this many seconds after claim is treated as +/// wedged: the worker died mid-verify or hit a persistent internal error. +const STALE_VERIFY_SECS: i64 = 6 * 3600; + +/// Bound on one store delete: the sweep holds a block row lock while it +/// runs, and a wedged backend would otherwise hold that lock forever. +const BLOCK_DELETE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + +#[derive(Debug, Default)] +pub struct SweepStats { + pub sessions_expired: u64, + pub blocks_marked: u64, + pub blocks_deleted: u64, +} + +/// One sweep pass. Exposed for tests; the worker calls it on a tick. +pub async fn sweep_once(state: &AppState) -> Result { + let db = &state.db; + let mut stats = SweepStats::default(); + + // Expire sessions past TTL, then drop their block links: an expired + // session no longer confers liveness. + let expired = db.model_expire_sessions().await?; + stats.sessions_expired = expired.len() as u64; + db.model_drop_sessions_blocks().await?; + + // A `verifying` row that outlived its window wedges the publisher's + // one-verifying slot; reject it (which also frees the reservation). + for id in db.model_stale_verifying(STALE_VERIFY_SECS).await? { + crate::models::verify::reject_release(state, id, "verification timed out").await?; + } + + // Re-mark liveness both ways: blocks that lost every live reference get + // an unreferenced_since stamp; blocks that regained one clear theirs. + stats.blocks_marked = db.model_remark_liveness().await?; + + // Delete blocks past the grace period. The store object goes first so a + // crash leaves a dangling row (an honest "missing" at next claim) rather + // than an untracked object the sweep can never find again. + let grace = state.config.model_unclaimed_ttl_secs as i64; + let stale = db.model_stale_blocks(grace, 128).await?; + let Some(store) = state.block_store.clone() else { + return Ok(stats); + }; + for sha in stale { + // Re-check liveness under the row lock the claim path also takes, + // held across the store delete so a racing claim blocks rather than + // wins a reference to an object we just removed. + let mut tx = db.model_begin().await?; + if !db.model_tx_block_still_dead(&mut tx, &sha, grace).await? { + tx.commit().await?; + continue; + } + let Ok(id) = crate::blockstore::BlockId::parse(&sha) else { + tx.commit().await?; + continue; + }; + // A wedged backend must not hold the row lock forever: bound the + // delete and skip the block on expiry, releasing the transaction. + match tokio::time::timeout(BLOCK_DELETE_TIMEOUT, store.delete(&id)).await { + Ok(Ok(())) | Ok(Err(crate::blockstore::BlockStoreError::NotFound)) => {} + Ok(Err(e)) => { + tracing::warn!("block {sha} store delete failed: {e}"); + tx.commit().await?; + continue; + } + Err(_) => { + tracing::warn!("block {sha} store delete timed out; skipping"); + tx.commit().await?; + continue; + } + } + db.model_tx_delete_block_row(&mut tx, &sha).await?; + tx.commit().await?; + stats.blocks_deleted += 1; + } + Ok(stats) +} + +/// Periodic sweep; spawned once when model hosting is enabled and exits on +/// node shutdown. +pub async fn run_sweep_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); + let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); + loop { + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } + if let Err(e) = sweep_once(&state).await { + tracing::warn!("model sweep failed: {e}"); + } + } +} diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs new file mode 100644 index 00000000..ef94330b --- /dev/null +++ b/crates/twigpine-node/src/models/verify.rs @@ -0,0 +1,890 @@ +//! Release verification: rebuild every chunk-stored file, hash it against +//! the manifest, check the declared format against detected bytes, and only +//! then mark the release published (and pin the hidden ref). Rejection frees +//! the quota reservation and drops the block refs. + +use futures::StreamExt; +use sha2::Digest; +use std::io::Write; +use twigpine_core::model::manifest::{detect_format, StorageKind}; +use twigpine_core::model::reconstruction::Reconstruction; + +use crate::error::AppError; +use crate::state::AppState; + +/// Sink hashing rebuilt bytes and keeping the head for format detection. +struct VerifySink { + hasher: sha2::Sha256, + head: Vec, +} + +impl Write for VerifySink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.hasher.update(buf); + if self.head.len() < 64 { + let take = (64 - self.head.len()).min(buf.len()); + self.head.extend_from_slice(&buf[..take]); + } + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Verify one release end to end. Idempotent: a release no longer in +/// `verifying` returns immediately. +pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), AppError> { + let Some(release) = state.db.model_release_by_id(release_id).await? else { + return Ok(()); + }; + if release.state != "verifying" { + return Ok(()); + } + + // The repo must still be fully public: a repo turned private or given + // visibility rules mid-verification never publishes. + let record = state + .db + .get_repo_by_id(&release.repo_id) + .await? + .ok_or_else(|| AppError::NotFound("repo gone".into()))?; + // mirror-rows-handled: a slash-form id fails closed in the condition + // below; the vacuous pair never admits a mirror for publishing. + let rules = state.db.list_visibility_rules(&record.id).await?; + // A mirror row (slash-form id) has a vacuous publicity pair, so it can + // never prove full publicity here either. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { + return reject_release(state, release_id, "repository is no longer fully public").await; + } + + let disk_path = std::path::PathBuf::from(&record.disk_path); + let (manifest_bytes, manifest) = match super::claim::read_verified_manifest( + &state.git_bin, + &disk_path, + &release.commit_sha, + &record.owner_did, + ) + .await + { + Ok(v) => v, + Err(e) => { + return reject_release(state, release_id, &format!("manifest re-check failed: {e}")) + .await; + } + }; + if twigpine_core::cid::sha256_hex(&manifest_bytes) != release.manifest_sha256 { + return reject_release(state, release_id, "manifest digest changed since claim").await; + } + + let rec = match &manifest.reconstruction { + Some(rec_ref) => { + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object unreadable: {e}"), + ) + .await; + } + }; + match Reconstruction::parse(&rec_bytes) { + Ok(r) => Some(r), + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object invalid: {e}"), + ) + .await; + } + } + } + None => None, + }; + // An all-Git release legitimately carries no reconstruction object; a + // manifest naming chunked files without one is self-contradictory. + if rec.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return reject_release( + state, + release_id, + "chunked files declared but the manifest has no reconstruction object", + ) + .await; + } + + // Commit ⊆ manifest: a committed file the manifest does not name as + // git-stored slipped past the publish scan; refuse it rather than + // release bytes the manifest never described. + let tree = crate::git::store::run_git_bounded( + &state.git_bin, + &disk_path, + &["ls-tree", "-rz", "--name-only", &release.commit_sha], + b"", + std::time::Duration::from_secs(30), + "git ls-tree", + ) + .await + .map_err(AppError::Internal)?; + let manifest_git_paths: std::collections::HashSet<&str> = manifest + .files + .iter() + .filter(|f| f.storage == StorageKind::Git) + .map(|f| f.path.as_str()) + .collect(); + // -z, not line-splitting: with core.quotePath on, a non-ASCII path is + // printed as escaped octal and could never match a manifest path. + for path in String::from_utf8_lossy(&tree.stdout) + .split('\0') + .filter(|p| !p.is_empty() && !p.starts_with(".twigpine/")) + { + if !manifest_git_paths.contains(path) { + return reject_release( + state, + release_id, + &format!("{path} is committed but not in the manifest"), + ) + .await; + } + } + + let rec_by_path: std::collections::HashMap<&str, _> = rec + .as_ref() + .map(|r| r.files.iter().map(|f| (f.path.as_str(), f)).collect()) + .unwrap_or_default(); + for file in &manifest.files { + match file.storage { + StorageKind::Chunked => { + let Some(&entry) = rec_by_path.get(file.path.as_str()) else { + return reject_release( + state, + release_id, + &format!("reconstruction object has no entry for {}", file.path), + ) + .await; + }; + if entry.sha256 != file.sha256 || entry.size != file.size { + return reject_release( + state, + release_id, + &format!("{}: reconstruction disagrees with the manifest", file.path), + ) + .await; + } + // Rebuild by ordered range reads, fully async: a sync walker + // would force block_on, which has no reactor under the S3 + // backend. Blocks were hash-verified at write, so the + // whole-file digest is the check that matters here. + let rec = rec.as_ref().expect("entry implies rec"); + let slices = match twigpine_core::model::reconstruction::map_file_range( + entry, rec, 0, file.size, + ) { + Ok(s) => s, + Err(e) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + }; + let mut sink = VerifySink { + 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() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let jobs = slices + .iter() + .map(|s| (s.block.clone(), s.offset, s.len)) + .collect::>(); + // Ordered prefetch: `buffered` preserves order while + // overlapping the store's per-slice round trips. Consume + // as slices land: collecting first would hold the whole + // rebuilt file in memory. + let mut fetched = + futures::stream::iter(jobs.into_iter().map(|(block, offset, len)| { + let store = store.clone(); + async move { super::read_range(&store, &block, offset, len).await } + })) + .buffered(4); + while let Some(bytes) = fetched.next().await { + let bytes = match bytes { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + }; + if sink.write_all(&bytes).is_err() { + return Err(AppError::Internal(anyhow::anyhow!("verify sink write"))); + } + } + let digest = hex::encode(sink.hasher.finalize()); + if digest != file.sha256 { + return reject_release( + state, + release_id, + &format!("{}: rebuilt bytes hash to {digest}", file.path), + ) + .await; + } + let detected = detect_format(&sink.head, &file.path); + if detected != file.format { + return reject_release( + state, + release_id, + &format!( + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected + ), + ) + .await; + } + } + StorageKind::Git => { + match super::claim::git_show( + &state.git_bin, + &disk_path, + &release.commit_sha, + &file.path, + ) + .await + { + Ok(Some(bytes)) => { + let got = twigpine_core::cid::sha256_hex(&bytes); + if got != file.sha256 || bytes.len() as u64 != file.size { + return reject_release( + state, + release_id, + &format!("{}: git blob does not match the manifest", file.path), + ) + .await; + } + let detected = detect_format(&bytes[..bytes.len().min(64)], &file.path); + if detected != file.format { + return reject_release( + state, + release_id, + &format!( + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected + ), + ) + .await; + } + } + Ok(None) => { + return reject_release( + state, + release_id, + &format!("{}: not present in the claimed commit", file.path), + ) + .await; + } + Err(e) => return Err(e), + } + } + } + } + + // Publish: hidden ref first, then the state flip, so a crash leaves a + // verifying row the worker retries rather than a dangling ref. + write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; + match state + .db + .model_publish_if_public(release_id, &release.repo_id) + .await? + { + crate::db::model_queries::PublishOutcome::Published => {} + crate::db::model_queries::PublishOutcome::NoLongerPublic => { + reject_release(state, release_id, "repository is no longer fully public").await?; + } + crate::db::model_queries::PublishOutcome::NotVerifying => { + // The row settled while this pass ran: a rejected release's ref + // must go, but a concurrently published one owns its ref. + let rejected = state + .db + .model_release_by_id(release_id) + .await? + .is_some_and(|r| r.state == "rejected"); + if rejected { + remove_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await; + } + } + } + Ok(()) +} + +/// Drop the hidden release ref written for `commit`. Best-effort like the +/// write it undoes: a failure leaves an advertised ref, which is a +/// leak of a commit, not a correctness wedge. +async fn remove_release_ref(git_bin: &str, disk_path: &std::path::Path, commit: &str) { + let ref_name = format!("refs/gitlawb/releases/{commit}"); + let _ = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["update-ref", "-d", &ref_name], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await; +} + +/// `refs/gitlawb/releases/` -> the release commit itself: reachable, +/// so `gc` never prunes it, and hidden under the gitlawb ref namespace. +/// Idempotently add the release-ref hideRefs config: repos created before +/// the namespace existed only get it via the push-path prereq, which is +/// warn-and-proceed, so a failed write there would leave release commits +/// advertised to every clone. +async fn ensure_release_refs_hidden( + git_bin: &str, + disk_path: &std::path::Path, +) -> Result<(), AppError> { + for &(key, value) in crate::git::store::HIDDEN_REFS + .iter() + .filter(|(_, v)| v.contains("releases/")) + { + let have = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--get-all", key], + b"", + std::time::Duration::from_secs(30), + "git config --get-all", + ) + .await + .map_err(AppError::Internal)?; + if String::from_utf8_lossy(&have.stdout) + .lines() + .any(|l| l.trim() == value) + { + continue; + } + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--add", key, value], + b"", + std::time::Duration::from_secs(30), + "git config --add", + ) + .await + .map_err(AppError::Internal)?; + // A failed add (e.g. a stale config.lock) still reports Ok from + // run_git_bounded; without this the release ref is written to a repo + // that advertises it to every clone. + if !out.status.success() { + return Err(AppError::Internal(anyhow::anyhow!( + "git config --add {key} failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))); + } + } + Ok(()) +} + +pub async fn write_release_ref( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, +) -> Result<(), AppError> { + ensure_release_refs_hidden(git_bin, disk_path).await?; + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &[ + "update-ref", + &format!("refs/gitlawb/releases/{commit}"), + commit, + ], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await + .map_err(AppError::Internal)?; + if !out.status.success() { + return Err(AppError::Internal(anyhow::anyhow!( + "git update-ref failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))); + } + Ok(()) +} + +/// Reject a release: drop its block refs, release the quota it reserved for +/// blocks no other live release still references, and record the reason. +pub async fn reject_release( + state: &AppState, + release_id: i64, + reason: &str, +) -> Result<(), AppError> { + state.db.model_reject_release(release_id, reason).await?; + tracing::info!(release_id, %reason, "model release rejected"); + // A rejected release must not keep its hidden pin: the ref may exist if + // a pass wrote it and then errored before the state flip. Remove it only + // when the row really settled as rejected, never for a published one. + if let Some(release) = state.db.model_release_by_id(release_id).await? { + if release.state == "rejected" { + if let Some(record) = state.db.get_repo_by_id(&release.repo_id).await? { + remove_release_ref( + &state.git_bin, + std::path::Path::new(&record.disk_path), + &release.commit_sha, + ) + .await; + } + } + } + Ok(()) +} + +/// Poll for `verifying` releases and verify them in order. Spawned once per +/// node when model hosting is enabled; exits on node shutdown. +pub async fn run_verify_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); + let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); + // Consecutive verify_release errors per release id, reset on success and + // on reject: the bound on retries a persistently broken release gets. + let mut failures: std::collections::HashMap = std::collections::HashMap::new(); + loop { + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } + let ids = match state.db.model_verifying_ids(4).await { + Ok(v) => v, + Err(e) => { + tracing::warn!("model verify worker query failed: {e}"); + continue; + } + }; + for id in &ids { + match verify_release(&state, *id).await { + Ok(()) => { + failures.remove(id); + } + Err(e) => { + tracing::warn!("model release {id} verification errored: {e}"); + let n = failures.entry(*id).or_insert(0); + *n += 1; + // A persistent internal error would otherwise hold the + // publisher's one-verifying slot until the 6h stale + // sweep; a bounded run of errors rejects the row sooner. + if *n >= 5 { + if let Err(re) = reject_release( + &state, + *id, + &format!("verification failed repeatedly: {e}"), + ) + .await + { + tracing::warn!( + "model release {id} reject after repeated failures failed: {re}" + ); + } + failures.remove(id); + } + } + } + } + // Rows that left `verifying` by another path (publish, stale sweep) + // carry no counter forward. + failures.retain(|id, _| ids.contains(id)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use twigpine_core::model::manifest::{ + FileFormat, Manifest, ManifestFile, StorageKind, MANIFEST_SCHEMA_V1, + }; + + 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 `verifying` release whose publish step fails every pass (a stale + /// `config.lock` refuses the hideRefs `git config --add`) is rejected by + /// the worker after a bounded run of errors, and the publisher's + /// one-verifying slot is then free for a new claim. + #[sqlx::test] + async fn a_persistently_failing_verify_is_rejected_and_frees_the_claim_slot( + pool: sqlx::PgPool, + ) { + let state = crate::test_support::test_state(pool.clone()).await; + let signing = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]); + let owner_did = + twigpine_core::did::Did::from_verifying_key(&signing.verifying_key()).to_string(); + + // A real commit: a.txt rides as a git-stored manifest file, so the + // whole verify path runs and only the ref-pin step fails. + let dir = tempfile::tempdir().expect("tempdir"); + git(dir.path(), &["init", "-q", "-b", "main"]); + std::fs::create_dir_all(dir.path().join(".twigpine")).expect("mkdir"); + std::fs::write(dir.path().join("a.txt"), b"hello\n").expect("a.txt"); + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{}/model", crate::db::canonical_did(&owner_did)), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![ManifestFile { + path: "a.txt".to_string(), + size: 6, + sha256: twigpine_core::cid::sha256_hex(b"hello\n"), + format: FileFormat::Text, + storage: StorageKind::Git, + }], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + std::fs::write( + dir.path().join(".twigpine/model-release.json"), + &manifest_bytes, + ) + .expect("manifest"); + std::fs::write(dir.path().join(".twigpine/model-release.sig"), sig).expect("sig"); + git(dir.path(), &["add", "a.txt", ".twigpine"]); + git( + dir.path(), + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "r1", + ], + ); + let commit = git(dir.path(), &["rev-parse", "HEAD"]); + + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r1', 'model', $1, TRUE, 'main', $2, $2, $3)", + ) + .bind(&owner_did) + .bind(chrono::Utc::now().to_rfc3339()) + .bind(dir.path().to_str().expect("utf-8 path")) + .execute(&pool) + .await + .expect("repo row"); + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, claim_request_digest, created_at) + VALUES ('r1', $1, 'main', $2, 'verifying', $3, 's', 'i', 'ss', + decode('00','hex'), 'd1', $4) + RETURNING id", + ) + .bind(&commit) + .bind(&owner_did) + .bind(twigpine_core::cid::sha256_hex(&manifest_bytes)) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(&pool) + .await + .expect("release row"); + + // A stale lock makes `git config --add` fail every pass; the pin + // step then errors instead of writing an advertised release ref. + std::fs::write(dir.path().join(".git/config.lock"), b"").expect("config.lock"); + + let worker = tokio::spawn(run_verify_worker(state.clone())); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + let state_str = loop { + let s: String = + sqlx::query_scalar("SELECT state FROM model_releases WHERE commit_sha = $1") + .bind(&commit) + .fetch_one(&pool) + .await + .expect("release state"); + if s != "verifying" { + break s; + } + assert!( + std::time::Instant::now() < deadline, + "release never settled" + ); + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + }; + worker.abort(); + assert_eq!(state_str, "rejected"); + let reason: String = + sqlx::query_scalar("SELECT failure_reason FROM model_releases WHERE commit_sha = $1") + .bind(&commit) + .fetch_one(&pool) + .await + .expect("failure_reason"); + assert!( + reason.contains("verification failed repeatedly"), + "got: {reason}" + ); + + // The slot is free: a claim on a new commit is accepted. + std::fs::write(dir.path().join("a.txt"), b"hello again\n").expect("a.txt v2"); + git(dir.path(), &["add", "a.txt"]); + git( + dir.path(), + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "r2", + ], + ); + let commit2 = git(dir.path(), &["rev-parse", "HEAD"]); + let record = state + .db + .get_repo_by_id("r1") + .await + .expect("repo read") + .expect("repo row"); + let material = super::super::claim::ClaimMaterial { + request_digest: "d2".to_string(), + signature: "s".to_string(), + signature_input: "i".to_string(), + signing_string: "ss".to_string(), + body: Vec::new(), + }; + let row = super::super::claim::claim_release( + &state, &record, &owner_did, &commit2, "main", &material, + ) + .await + .expect("claim after rejection is accepted"); + assert_eq!(row.state, "verifying"); + } + + /// One verifying release over a real repo holding `files`: the manifest + /// names `manifest_paths` of them as git-stored; any committed file the + /// manifest does not name is extra. Returns (state, release_id, commit). + async fn verify_fixture( + pool: &sqlx::PgPool, + worktree: &std::path::Path, + files: &[(&str, &[u8])], + manifest_paths: &[&str], + ) -> (crate::state::AppState, i64, String) { + let state = crate::test_support::test_state(pool.clone()).await; + let signing = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]); + let owner_did = + twigpine_core::did::Did::from_verifying_key(&signing.verifying_key()).to_string(); + git(worktree, &["init", "-q", "-b", "main"]); + std::fs::create_dir_all(worktree.join(".twigpine")).expect("mkdir"); + let mut entries = Vec::new(); + let mut add = vec![".twigpine".to_string()]; + for (path, bytes) in files { + std::fs::write(worktree.join(path), bytes).expect("worktree file"); + add.push(path.to_string()); + entries.push(ManifestFile { + path: path.to_string(), + size: bytes.len() as u64, + sha256: twigpine_core::cid::sha256_hex(bytes), + format: FileFormat::Text, + storage: StorageKind::Git, + }); + } + entries.retain(|f| manifest_paths.contains(&f.path.as_str())); + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{}/model", crate::db::canonical_did(&owner_did)), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: entries, + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + std::fs::write( + worktree.join(".twigpine/model-release.json"), + &manifest_bytes, + ) + .expect("manifest"); + std::fs::write(worktree.join(".twigpine/model-release.sig"), sig).expect("sig"); + let add_refs: Vec<&str> = add.iter().map(String::as_str).collect(); + git(worktree, &[&["add"][..], &add_refs].concat()); + git( + worktree, + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "r1", + ], + ); + let commit = git(worktree, &["rev-parse", "HEAD"]); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r1', 'model', $1, TRUE, 'main', $2, $2, $3)", + ) + .bind(&owner_did) + .bind(chrono::Utc::now().to_rfc3339()) + .bind(worktree.to_str().expect("utf-8 path")) + .execute(pool) + .await + .expect("repo row"); + let release_id: i64 = sqlx::query_scalar( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, claim_request_digest, created_at) + VALUES ('r1', $1, 'main', $2, 'verifying', $3, 's', 'i', 'ss', + decode('00','hex'), 'd1', $4) + RETURNING id", + ) + .bind(&commit) + .bind(&owner_did) + .bind(twigpine_core::cid::sha256_hex(&manifest_bytes)) + .bind(chrono::Utc::now().to_rfc3339()) + .fetch_one(pool) + .await + .expect("release row"); + (state, release_id, commit) + } + + async fn release_state(pool: &sqlx::PgPool, release_id: i64) -> (String, Option) { + sqlx::query_as::<_, (String, Option)>( + "SELECT state, failure_reason FROM model_releases WHERE id = $1", + ) + .bind(release_id) + .fetch_one(pool) + .await + .expect("release row") + } + + /// A git-stored manifest file whose name needs quoting under + /// core.quotePath (`README-é.md`) still verifies: ls-tree -z must not + /// quote it into a phantom mismatch. + #[sqlx::test] + async fn a_non_ascii_git_file_verifies(pool: sqlx::PgPool) { + let dir = tempfile::tempdir().expect("tempdir"); + let (state, release_id, _commit) = verify_fixture( + &pool, + dir.path(), + &[("README-é.md", b"hi\n")], + &["README-é.md"], + ) + .await; + verify_release(&state, release_id).await.expect("verify"); + let (state_str, _) = release_state(&pool, release_id).await; + assert_eq!(state_str, "published"); + } + + /// The same committed-but-unlisted check must still fire on a non-ASCII + /// path the manifest does not name. + #[sqlx::test] + async fn an_unlisted_non_ascii_commit_is_still_rejected(pool: sqlx::PgPool) { + let dir = tempfile::tempdir().expect("tempdir"); + let (state, release_id, _commit) = verify_fixture( + &pool, + dir.path(), + &[("README-é.md", b"hi\n"), ("extra-é.bin", b"x")], + &["README-é.md"], + ) + .await; + verify_release(&state, release_id) + .await + .expect("verify call"); + let (state_str, reason) = release_state(&pool, release_id).await; + assert_eq!(state_str, "rejected"); + let reason = reason.expect("failure_reason"); + assert!( + reason.contains("committed but not in the manifest"), + "{reason}" + ); + assert!(reason.contains("extra-é.bin"), "{reason}"); + } + async fn ref_exists(dir: &std::path::Path, commit: &str) -> bool { + std::process::Command::new("git") + .args(["show-ref", "--verify", "-q"]) + .arg(format!("refs/gitlawb/releases/{commit}")) + .current_dir(dir) + .status() + .expect("git runs") + .success() + } + + /// Rejecting a release removes the hidden pin a failed pass left behind, + /// and leaves the ref of a release that is actually published alone. + #[sqlx::test] + async fn rejecting_a_release_drops_its_pin_but_not_a_published_ones(pool: sqlx::PgPool) { + let dir = tempfile::tempdir().expect("tempdir"); + let (state, release_id, commit) = + verify_fixture(&pool, dir.path(), &[("a.txt", b"hi\n")], &["a.txt"]).await; + write_release_ref(&state.git_bin, dir.path(), &commit) + .await + .expect("write ref"); + assert!(ref_exists(dir.path(), &commit).await); + reject_release(&state, release_id, "test") + .await + .expect("reject"); + assert_eq!(release_state(&pool, release_id).await.0, "rejected"); + assert!(!ref_exists(dir.path(), &commit).await, "pin must be gone"); + + sqlx::query("UPDATE model_releases SET state = 'published' WHERE id = $1") + .bind(release_id) + .execute(&pool) + .await + .expect("publish"); + write_release_ref(&state.git_bin, dir.path(), &commit) + .await + .expect("write ref"); + reject_release(&state, release_id, "late") + .await + .expect("no-op reject"); + assert_eq!(release_state(&pool, release_id).await.0, "published"); + assert!( + ref_exists(dir.path(), &commit).await, + "published keeps its pin" + ); + } +} diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 64c6f56a..e8f66d33 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -14,8 +14,9 @@ use tower_http::trace::{DefaultOnFailure, DefaultOnResponse, TraceLayer}; use tracing::Level; use crate::api::{ - agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, peers, profiles, - protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, webhooks, + agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, models, peers, + profiles, protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, + webhooks, }; use crate::auth; use crate::rate_limit; @@ -762,6 +763,72 @@ pub fn build_router(state: AppState) -> Router { auth::optional_signature, )); + // ── Model hosting routes ───────────────────────────────────────────── + // Mounted only when the operator enabled the feature (`block_store` is + // the flag's live form). Three surfaces with three different auth + // shapes: + // - session open + session status: signed, owner-only. + // - claims: signed, persists the request material and owns its replay + // defense exactly like status claims. + // - block PUT: unsigned by design — the session id is the bearer + // credential and a signed 128 MiB body would have to be buffered + // whole to verify. Default body limit off, explicit block cap, same + // per-IP write brake as the other write surfaces. + let model_routes = if state.block_store.is_some() { + let signed = add_auth_layers( + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions", + post(models::open_model_session), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + get(models::get_model_session), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .write_braked(&write_ip_limiter); + let claims = add_auth_layers( + Router::new().route( + "/api/v1/repos/{owner}/{repo}/models/claims", + post(models::claim_model_release), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .layer(RequestBodyLimitLayer::new(status::MAX_REQUEST_BODY_BYTES)) + .layer(axum::Extension(auth::PersistsSignedBody)) + .layer(axum::Extension(auth::OwnsReplayDefense)) + .write_braked(&write_ip_limiter); + let blocks = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}", + axum::routing::put(models::put_model_block), + ) + .layer(DefaultBodyLimit::disable()) + .layer(RequestBodyLimitLayer::new( + crate::models::MAX_BLOCK_BYTES as usize, + )) + .write_braked(&write_ip_limiter); + let reads = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + get(models::get_model_release), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}/reconstruction", + get(models::get_model_reconstruction), + ) + .layer(middleware::from_fn_with_state( + auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), + auth::optional_signature, + )); + signed.merge(claims).merge(blocks).merge(reads) + } else { + Router::new() + }; + // ── Meta ────────────────────────────────────────────────────────────── let meta_routes = Router::new() .route("/", get(node_info)) @@ -791,6 +858,7 @@ pub fn build_router(state: AppState) -> Router { .merge(sync_trigger_routes) .merge(ipfs_routes) .merge(arweave_routes) + .merge(model_routes) .merge(meta_routes) .layer( TraceLayer::new_for_http() diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 21ec3d8d..25f5f5aa 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -156,7 +156,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, + block_store: Arc, +) -> 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); @@ -176,6 +181,11 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS task_tx.clone(), task_cursor_key.clone(), )); + // Model hosting is ON for the harness node: a filesystem block store in a + // temp dir mounts the model routes so the deny sweep can drive their + // gates for real. Writes land inside the node's per-test repos dir and + // are removed with it. + let block_store: Option> = Some(block_store); AppState { config: Arc::new(Config::parse_from(["twigpine-node"])), db, @@ -228,7 +238,7 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS 16, ), git_bin: "git".to_string(), - block_store: None, + block_store, } } @@ -238,15 +248,99 @@ 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 { + let repos_dir = unique_repos_dir(); + std::fs::create_dir_all(&repos_dir).expect("create temp repos dir"); + let block_dir = repos_dir.join("model-blocks"); + std::fs::create_dir_all(&block_dir).expect("create temp block dir"); + let block_store: Arc = + Arc::new(crate::blockstore::fs::FsBlockStore::new(block_dir).expect("fs block store")); + spawn_node_with_store(pool, repos_dir, block_store).await +} + +/// A [`crate::blockstore::BlockStore`] wrapper that fails the next `size()` +/// call once with a backend error, then delegates everything. The upload +/// handler's post-put failure tails are unreachable without a fault seam, so +/// the harness provides this one instead of a mock framework. +pub struct FailOnceSizeStore { + inner: Arc, + fail: std::sync::atomic::AtomicBool, +} + +impl FailOnceSizeStore { + pub fn new(inner: Arc) -> Self { + Self { + inner, + fail: std::sync::atomic::AtomicBool::new(false), + } + } + + /// Make the next `size()` call fail once. + pub fn fail_next_size(&self) { + self.fail.store(true, Ordering::SeqCst); + } +} + +#[async_trait::async_trait] +impl crate::blockstore::BlockStore for FailOnceSizeStore { + async fn put_verified( + &self, + id: &crate::blockstore::BlockId, + body: futures::stream::BoxStream<'static, std::io::Result>, + max_len: u64, + ) -> Result { + self.inner.put_verified(id, body, max_len).await + } + + async fn get_range( + &self, + id: &crate::blockstore::BlockId, + start: u64, + end_exclusive: u64, + ) -> Result< + futures::stream::BoxStream<'static, std::io::Result>, + crate::blockstore::BlockStoreError, + > { + self.inner.get_range(id, start, end_exclusive).await + } + + async fn size( + &self, + id: &crate::blockstore::BlockId, + ) -> Result, crate::blockstore::BlockStoreError> { + if self.fail.swap(false, Ordering::SeqCst) { + return Err(crate::blockstore::BlockStoreError::Backend( + "injected size failure".into(), + )); + } + self.inner.size(id).await + } + + async fn delete( + &self, + id: &crate::blockstore::BlockId, + ) -> Result<(), crate::blockstore::BlockStoreError> { + self.inner.delete(id).await + } + + fn backend_name(&self) -> &'static str { + "fail-once-size" + } +} + +/// Same as [`spawn_node`] but with a caller-supplied block store, so a test +/// can wrap the filesystem backend with fault injection (e.g. a `size()` +/// that fails once) to drive the upload handler's failure tails. +pub async fn spawn_node_with_store( + pool: PgPool, + repos_dir: PathBuf, + block_store: Arc, +) -> TestNode { let db = Arc::new(crate::db::Db::for_testing(pool.clone())); db.run_migrations() .await .expect("test schema migrations should apply"); - 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(), block_store); let node_did = state.node_did.to_string(); let shutdown_tx = state.shutdown_tx.clone(); let mut shutdown_rx = shutdown_tx.subscribe(); @@ -371,9 +465,50 @@ impl TestNode { record.id } + /// Seed a published model release row directly, bypassing the claim + /// pipeline: deny fixtures need a real row behind the read gate, not the + /// full upload-and-verify path. + pub async fn seed_model_release(&self, repo_id: &str, commit_sha: &str, publisher_did: &str) { + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ($1,$2,'main',$3,'published',$4,'sig','input','signing',\ + decode('00','hex'),$5)", + ) + .bind(repo_id) + .bind(commit_sha) + .bind(publisher_did) + .bind(format!("{commit_sha:0>64}")) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model release"); + } + + /// Seed an open model upload session row directly (see + /// [`Self::seed_model_release`]): the session-status read row's owner + /// twin needs a real session behind the gate. + pub async fn seed_model_session(&self, repo_id: &str, session_id: &str, owner_did: &str) { + sqlx::query( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1,$2,$3,$4,$5,0,'open')", + ) + .bind(session_id) + .bind(owner_did) + .bind(repo_id) + .bind(chrono::Utc::now().to_rfc3339()) + .bind((chrono::Utc::now() + chrono::Duration::hours(12)).to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model session"); + } + /// Mark `branch` as protected on `repo_id`, so a non-owner push to it is /// rejected by the branch-protection gate (used by the deny-prober's - /// protected-push probe — #195, F3). + /// protected-push probe, #195 F3). pub async fn seed_protected_branch(&self, repo_id: &str, branch: &str, created_by: &str) { self.db .protect_branch(repo_id, branch, created_by) diff --git a/crates/twigpine-node/tests/deny_harness.rs b/crates/twigpine-node/tests/deny_harness.rs index 26b0c0d7..76acf4cb 100644 --- a/crates/twigpine-node/tests/deny_harness.rs +++ b/crates/twigpine-node/tests/deny_harness.rs @@ -1429,6 +1429,24 @@ mod completeness { ("git_upload_pack", NotDrivenReason::GitSmartHttpRead), // Global list-FILTER: 200 with unreadable rows removed, never a 404. ("list_all_bounties", NotDrivenReason::GlobalListFilter), + // Model hosting writes: the session open, claim, and unsigned block + // PUT all read-gate the repo before their own credential checks. None + // is a 404-deny GET; the owner-gate rows drive the signed writes, and + // the bearer-session PUT's denies are covered by the models unit + // tests (a session row cannot be seeded through the public API for + // the stranger leg). + ("open_model_session", NotDrivenReason::ReadGatingMutation), + ("claim_model_release", NotDrivenReason::ReadGatingMutation), + ("put_model_block", NotDrivenReason::ReadGatingMutation), + // get_model_reconstruction's owner-2xx twin needs a completed claim: + // a signed manifest commit in git plus a real reconstruction object + // in the block store, substrate the fixture cannot seed through the + // public API. Its hostile 404 is still what a caller sees; only the + // twin lacks a drivable 2xx. + ( + "get_model_reconstruction", + NotDrivenReason::ExternalDependencyUnavailable, + ), ]; /// Every `.route("", ()…)` mount in `src`, as diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs new file mode 100644 index 00000000..f67cc3e6 --- /dev/null +++ b/crates/twigpine-node/tests/models_api.rs @@ -0,0 +1,1049 @@ +//! HTTP-level coverage for the U5/U6/U7 model-hosting routes: the signed +//! session open and session status, the unsigned bearer block PUT, the signed +//! release claim (including its request-digest replay), and the read-gated +//! release status. The deny sweep already proves the hostile statuses; these +//! tests drive the happy paths and the handler-specific 4xxes the sweep rows +//! cannot express. Requires `--features test-harness`. + +#[allow(dead_code)] +mod support; + +use serde_json::{json, Value}; +use support::bounded_client; +use support::signing::signed_request; + +use twigpine_core::cid::sha256_hex; +use twigpine_core::http_sig::sign_request; +use twigpine_core::identity::Keypair; +use twigpine_node::blockstore::{BlockId, BlockStore}; +use twigpine_node::test_harness::{spawn_node, spawn_node_with_store, FailOnceSizeStore, TestNode}; + +fn sessions_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/sessions") +} + +fn claims_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/claims") +} + +fn release_path(owner: &str, repo: &str, commit: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/releases/{commit}") +} + +fn blocks_path(owner: &str, repo: &str, sha: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/blocks/{sha}") +} + +fn put_block( + client: &reqwest::Client, + base_url: &str, + path: &str, + session: Option<&str>, + body: Vec, +) -> reqwest::RequestBuilder { + let mut req = client.put(format!("{base_url}{path}")).body(body); + if let Some(s) = session { + req = req.header("x-twigpine-model-session", s); + } + req +} + +/// An owner keypair plus the raw SigningKey the manifest format signs with; +/// both derive from one seed so the keypair's DID anchors the manifest. +fn owner_with_signing(seed: u8) -> (Keypair, ed25519_dalek::SigningKey) { + let seed_bytes = [seed; 32]; + ( + Keypair::from_seed(&seed_bytes).expect("keypair"), + ed25519_dalek::SigningKey::from_bytes(&seed_bytes), + ) +} + +/// Build a git repo on disk containing one commit with a valid signed release +/// manifest, returning the commit sha. The claim route's `git cat-file` / +/// `git show` calls run against `repos.disk_path`, so the row must point here. +fn make_release_repo(dir: &std::path::Path, manifest: &[u8], sig: &str) -> String { + let run = |args: &[&str]| { + let out = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + run(&["init", "-q", "-b", "main"]); + std::fs::create_dir_all(dir.join(".twigpine")).expect("mkdir .twigpine"); + std::fs::write(dir.join(".twigpine/model-release.json"), manifest).expect("write manifest"); + std::fs::write(dir.join(".twigpine/model-release.sig"), sig).expect("write sig"); + run(&["add", "-A"]); + run(&[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "model release 1", + ]); + run(&["rev-parse", "HEAD"]) +} + +/// Point the seeded repo row at an on-disk git directory (seed_repo writes a +/// placeholder disk_path the claim route cannot read). +async fn set_disk_path(pool: &sqlx::PgPool, repo_id: &str, dir: &std::path::Path) { + sqlx::query("UPDATE repos SET disk_path = $1 WHERE id = $2") + .bind(dir.to_str().expect("utf-8 temp path")) + .bind(repo_id) + .execute(pool) + .await + .expect("update disk_path"); +} + +async fn seed_open_session(node: &TestNode, repo_id: &str, owner_did: &str) -> String { + let session_id = "s".repeat(64); + node.seed_model_session(repo_id, &session_id, owner_did) + .await; + session_id +} + +// ── POST /models/sessions ──────────────────────────────────────────────────── + +/// The owner opening a session on a fully public repo gets 201 and a +/// 64-hex session id plus an expiry. +#[sqlx::test] +async fn open_session_owner_created(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 201); + let v: Value = resp.json().await.expect("session body"); + assert_eq!( + v["session_id"].as_str().map(str::len), + Some(64), + "session id is a 256-bit hex bearer" + ); + assert!(v["expires_at"].as_str().is_some()); + + node.shutdown().await; +} + +/// A mirror row with no canonical twin carries a vacuous publicity pair: +/// `is_public` is hardcoded true and rules never sync, so neither check may +/// admit it for publishing. Slash-form ids mark mirror rows (issue #244). +#[sqlx::test] +async fn mirror_repo_without_twin_cannot_publish(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos + (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1,'model',$2,'mirrored from peer',true,'main',$3,$3,'/tmp/mirror-model')", + ) + .bind(format!("{owner_did}/model")) + .bind(&owner_did) + .bind(&now) + .execute(&pool) + .await + .expect("mirror row seeds"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + let body = serde_json::to_vec(&json!({"commit": "0".repeat(40), "branch": "main"})).unwrap(); + let signed = sign_request(&owner, "POST", &claims_path(&owner_did, "model"), &body); + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + node.shutdown().await; +} + +/// A signed caller who is not the repo owner gets the owner gate's 403. +#[sqlx::test] +async fn open_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +/// An unsigned request is stopped by the signature layer before any repo +/// lookup: 401. +#[sqlx::test] +async fn open_session_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = client + .post(format!( + "{}{}", + node.base_url, + sessions_path(&owner_did, "model") + )) + .body(b"{}".to_vec()) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A private repo answers the read gate's existence-hiding 404 to a signed +/// non-reader, before the owner gate can fire. +#[sqlx::test] +async fn open_session_private_repo_hidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A public repo carrying a path-scoped visibility rule is not "fully +/// public", so the session open refuses it with a named 400 rather than +/// partially publishing. +#[sqlx::test] +async fn open_session_repo_with_visibility_rule_rejected(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + node.withhold_path(&repo_id, "sub/**", &[], &owner_did) + .await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let body = resp.text().await.unwrap_or_default(); + assert!( + body.contains("fully public"), + "denial should name the fully-public requirement, got: {body}" + ); + + node.shutdown().await; +} + +// ── GET /models/sessions/{id} ──────────────────────────────────────────────── + +/// The owner reads back an open session's state and byte counter. +#[sqlx::test] +async fn get_session_owner_reads_open(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("session body"); + assert_eq!(v["session_id"].as_str(), Some(session_id.as_str())); + assert_eq!(v["state"].as_str(), Some("open")); + + node.shutdown().await; +} + +/// A signed stranger reaches the owner gate on the session read: 403. +#[sqlx::test] +async fn get_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +// ── PUT /models/blocks/{sha256} ────────────────────────────────────────────── + +/// The unsigned PUT without the session header gets 401: the bearer +/// credential is absent, not invalid. +#[sqlx::test] +async fn put_block_without_session_header_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let sha = sha256_hex(b"block"); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + None, + b"block".to_vec(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A session id that was never issued answers the same 404 as an expired or +/// foreign one: a bearer guess learns nothing about which part failed. +#[sqlx::test] +async fn put_block_bogus_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = b"block".to_vec(); + let sha = sha256_hex(&body); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&"f".repeat(64)), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A session bound to repo A does not upload into repo B: the +/// session-to-repo binding check answers 404. +#[sqlx::test] +async fn put_block_session_for_other_repo_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_a = node.seed_repo(&owner_did, "model-a", true).await; + node.seed_repo(&owner_did, "model-b", true).await; + let session_id = seed_open_session(&node, &repo_a, &owner_did).await; + let body = b"block".to_vec(); + let sha = sha256_hex(&body); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model-b", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// An open session whose expiry already passed answers 404; the PUT never +/// reaches the block store. +#[sqlx::test] +async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "e".repeat(64); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); + let body = b"block".to_vec(); + let sha = sha256_hex(&body); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +#[sqlx::test] +async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = b"the quick brown fox".to_vec(); + let sha = sha256_hex(&body); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("block response"); + assert_eq!(v["duplicate"].as_bool(), Some(false)); + assert!( + v["received"].as_i64().unwrap_or(0) >= body.len() as i64, + "bytes_received should include this block: {v}" + ); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("dup response"); + assert_eq!(v["duplicate"].as_bool(), Some(true)); + + let wrong_sha = "0".repeat(64); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &wrong_sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400, "digest mismatch is a 400"); + + node.shutdown().await; +} + +/// A bookkeeping failure on a PUT whose bytes the store already held (the +/// put reports AlreadyPresent) must not delete the shared object or its +/// model_blocks row, and must refund the second session's admission. The +/// fault seam fails the `size()` call inside the second PUT's bookkeeping +/// tail. +#[sqlx::test] +async fn put_block_failed_bookkeeping_keeps_shared_block(pool: sqlx::PgPool) { + let repos_dir = tempfile::tempdir().expect("repos dir"); + let block_dir = tempfile::tempdir().expect("block dir"); + let inner: std::sync::Arc = std::sync::Arc::new( + twigpine_node::blockstore::fs::FsBlockStore::new(block_dir.path().to_path_buf()) + .expect("fs store"), + ); + let failing = std::sync::Arc::new(FailOnceSizeStore::new(inner.clone())); + let node = spawn_node_with_store( + pool.clone(), + repos_dir.path().to_path_buf(), + failing.clone(), + ) + .await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let body = b"shared-block".to_vec(); + let sha = sha256_hex(&body); + let block_id = BlockId::parse(&sha).expect("block id"); + + // The first PUT stores the block and books it. + let session1 = seed_open_session(&node, &repo_id, &owner_did).await; + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session1), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!( + resp.status().as_u16(), + 200, + "{}", + resp.text().await.unwrap_or_default() + ); + + // The second PUT sees the stored object (AlreadyPresent), then the + // injected size() failure lands in the bookkeeping tail. + failing.fail_next_size(); + let session2 = "t".repeat(64); + node.seed_model_session(&repo_id, &session2, &owner_did) + .await; + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session2), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 500); + + // The shared object and its model_blocks row survive; the failed + // session's admission is refunded and it records no link. + assert_eq!( + inner.size(&block_id).await.expect("size"), + Some(body.len() as u64), + "shared block must not be deleted" + ); + let block_row: bool = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM model_blocks WHERE sha256 = $1)") + .bind(&sha) + .fetch_one(&pool) + .await + .expect("block row check"); + assert!(block_row, "model_blocks row must remain"); + let (received, linked): (i64, i64) = sqlx::query_as( + "SELECT s.bytes_received, + (SELECT COUNT(*) FROM model_session_blocks l + WHERE l.session_id = s.id AND l.block_sha256 = $2) + FROM model_upload_sessions s WHERE s.id = $1", + ) + .bind(&session2) + .bind(&sha) + .fetch_one(&pool) + .await + .expect("session state"); + assert_eq!(received, 0, "admission refunded"); + assert_eq!(linked, 0, "no session link recorded"); + + node.shutdown().await; +} + +/// A session bearer that declares a small Content-Length but streams a larger +/// valid block must not get the larger block stored under the small charge. +/// Both framing headers are sent so the body is read to EOF by chunked +/// framing while the handler still sees the understated length. +#[sqlx::test] +async fn put_block_understated_content_length_is_not_stored_under_small_charge(pool: sqlx::PgPool) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let node = spawn_node(pool).await; + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = vec![b'x'; 4096]; + let sha = sha256_hex(&body); + let addr = node.base_url.trim_start_matches("http://").to_string(); + let mut sock = tokio::net::TcpStream::connect(&addr) + .await + .expect("connect"); + let head = format!( + "PUT {} HTTP/1.1\r\nHost: {addr}\r\nx-twigpine-model-session: {session_id}\r\n\ + Content-Length: 4\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n", + blocks_path(&owner_did, "model", &sha) + ); + sock.write_all(head.as_bytes()).await.expect("write head"); + sock.write_all(format!("{:x}\r\n", body.len()).as_bytes()) + .await + .expect("write chunk size"); + sock.write_all(&body).await.expect("write body"); + sock.write_all(b"\r\n0\r\n\r\n").await.expect("write end"); + let mut raw = Vec::new(); + let _ = sock.read_to_end(&mut raw).await; + let raw = String::from_utf8_lossy(&raw).to_string(); + let status_line = raw.lines().next().unwrap_or("").to_string(); + eprintln!("raw response: {raw}"); + assert!( + !status_line.contains(" 200 "), + "a block larger than its declared Content-Length must not be admitted: {status_line}" + ); + + node.shutdown().await; +} + +/// An open session past its `expires_at` is dead on the status read too, so +/// the CLI resume path (which abandons a 404) does not keep a lapsed session. +#[sqlx::test] +async fn get_session_expired_open_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let kp = Keypair::generate(); + let owner_did = kp.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "f".repeat(64); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + let path = format!("{}/{session_id}", sessions_path(&owner_did, "model")); + let live = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(live.status().as_u16(), 200, "a live session reads as open"); + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "a lapsed session is not found"); + + node.shutdown().await; +} + +// ── POST /models/claims ────────────────────────────────────────────────────── + +/// A claim against a pushed commit carrying a signed manifest inserts the +/// release row; re-sending the identical signed request resolves to the same +/// release_id through the persisted request digest. +#[sqlx::test] +async fn claim_accepts_signed_manifest_and_replays_idempotently(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(7); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + + let dir = tempfile::tempdir().expect("tempdir"); + let commit = make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let path = claims_path(&owner_did, "model"); + let body = + serde_json::to_vec(&json!({"commit": commit, "branch": "main"})).expect("claim body"); + // Sign once, then send the identical request twice: the digest replay + // resolves the second to the original row. + let signed = sign_request(&owner, "POST", &path, &body); + let send = |client: &reqwest::Client| { + client + .post(format!("{}{}", node.base_url, path)) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body.clone()) + }; + + let resp = send(&client).send().await.expect("request sends"); + let status = resp.status().as_u16(); + let text = resp.text().await.unwrap_or_default(); + assert_eq!(status, 200, "claim body: {text}"); + let v: Value = serde_json::from_str(&text).expect("claim response"); + let release_id = v["release_id"].as_i64().expect("release_id"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("verifying")); + + let resp = send(&client).send().await.expect("replay sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("replay response"); + assert_eq!( + v["release_id"].as_i64(), + Some(release_id), + "a replayed claim must resolve to the original release row" + ); + + node.shutdown().await; +} + +/// A claim naming a commit the repo does not hold is a 400, not a 404: the +/// repo exists and is readable; the commit is the bad input. +#[sqlx::test] +async fn claim_missing_commit_is_bad_request(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(8); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + // A real on-disk repo is needed for `git cat-file` to answer "missing" + // rather than the spawn failing on a nonexistent path. + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + let dir = tempfile::tempdir().expect("tempdir"); + make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let body = serde_json::to_vec(&json!({ + "commit": "b".repeat(40), + "branch": "main", + })) + .expect("claim body"); + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body, + &owner, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let text = resp.text().await.unwrap_or_default(); + assert!(text.contains("commit not found"), "got: {text}"); + + node.shutdown().await; +} + +/// The owner gate on claims: a signed stranger is 403, an unsigned request is +/// 401 before the handler runs. +#[sqlx::test] +async fn claim_non_owner_forbidden_and_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = serde_json::to_vec(&json!({ + "commit": "a".repeat(40), + "branch": "main", + })) + .expect("claim body"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body.clone(), + &stranger, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +// ── GET /models/releases/{sha} ─────────────────────────────────────────────── + +/// A seeded published release reads back its fields; an unknown commit is a +/// plain 404; a private repo's release is existence-hiding to a non-reader. +#[sqlx::test] +async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let commit = "c".repeat(40); + node.seed_model_release(&repo_id, &commit, &owner_did).await; + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &commit) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("release body"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("published")); + assert_eq!(v["branch"].as_str(), Some("main")); + assert!(v["release_id"].as_i64().is_some()); + assert!(v["manifest_sha256"].as_str().is_some()); + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &"d".repeat(40)) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "unknown commit is a 404"); + + // Private repo: a signed stranger gets the existence-hiding 404. + let priv_repo = node.seed_repo(&owner_did, "model-priv", false).await; + node.seed_model_release(&priv_repo, &commit, &owner_did) + .await; + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &release_path(&owner_did, "model-priv", &commit), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// The reconstruction GET and the claims POST hide a repo that is not fully +/// public: callers who fail the read gate (anonymous, stranger) get the same +/// 404 and none reach the store or the commit lookup. The owner can read the +/// repo but fails the fully-public requirement, so the claims POST answers +/// an explicit 400. The deny sweep cannot drive the hostile-only legs for +/// the reconstruction route, so they live here. +#[sqlx::test] +async fn reconstruction_and_claims_deny_on_private_repo(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + let commit = "c".repeat(40); + let rec_path = format!( + "{}/reconstruction", + release_path(&owner_did, "model", &commit) + ); + + for (label, req) in [ + ( + "anon GET reconstruction", + client.get(format!("{}{}", node.base_url, rec_path)), + ), + ( + "stranger GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &stranger, + ), + ), + ( + "owner GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &owner, + ), + ), + ( + "stranger POST claims", + signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + serde_json::to_vec(&serde_json::json!({ + "commit": commit, + "branch": "main", + })) + .expect("claim body"), + &stranger, + ) + .header("content-type", "application/json"), + ), + ] { + let resp = req.send().await.expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "{label}"); + } + + // The owner reads their own private repo, so the read gate passes and + // the fully-public requirement denies with a 400 rather than a 404. + let owner_claim = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + serde_json::to_vec(&serde_json::json!({ + "commit": commit, + "branch": "main", + })) + .expect("claim body"), + &owner, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(owner_claim.status().as_u16(), 400, "owner POST claims"); + + node.shutdown().await; +} diff --git a/crates/twigpine-node/tests/support/probe.rs b/crates/twigpine-node/tests/support/probe.rs index 9e27520d..a7fdbbca 100644 --- a/crates/twigpine-node/tests/support/probe.rs +++ b/crates/twigpine-node/tests/support/probe.rs @@ -256,6 +256,21 @@ impl Fixture { let priv_bounty_id = seed_private_bounty(node, &owner, &owner_did, priv_repo, &bounty_marker).await; + // Model hosting is mounted on the harness node (an fs block store in + // the per-test repos dir). The model-release read row fills `{sha}` + // with 40 a's, so seed that commit as a published release on the + // private repo: anon/stranger get the existence-hiding 404, the owner + // twin gets a 200 proving the gate. + node.seed_model_release( + &private_repo_id, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + &owner_did, + ) + .await; + // The session-status read row fills `{id}` with the fixed "1". + node.seed_model_session(&private_repo_id, "1", &owner_did) + .await; + let priv_markers = vec![issue_marker, pr_marker, pr_diff_marker, bounty_marker]; // #195 (F3): seed the caller-self task entities through the real task write diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 61ddf428..4cf536ba 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -1030,6 +1030,86 @@ pub fn deny_bearing_routes() -> &'static [Row] { id_source: IdSource::FailableTaskId, anon_read: AnonRead::Deny404, }, + // ── Model hosting (U5/U6). Session open and release claim are signed + // owner-gated writes behind the shared read gate; the session-status + // GET is doubly gated like list_webhooks (OwnerGate + ReadGate rows). + // The unsigned block PUT's bearer session is its credential, and the + // release/reconstruction reads are plain read-gated 404-deny GETs. + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/sessions", + gate: GateClass::OwnerGate, + handler: "models::open_model_session", + // Option> accepts an empty object; the owner + // twin then creates a session (201, Not403). + body: Some(r#"{}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/claims", + gate: GateClass::OwnerGate, + handler: "models::claim_model_release", + // A well-formed claim body; the owner twin passes the owner gate and + // fails the commit lookup (the seeded placeholder disk_path makes + // it a 500 today, a real on-disk repo would make it 400), which is + // still a Not403 twin. + body: Some(r#"{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","branch":"main"}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Session status: a signed stranger on the PUBLIC repo passes the read + // gate and hits require_repo_owner (403); the owner gets a 404 on the + // absent session (Not403). The read layer is the ReadGate row below. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::OwnerGate, + handler: "models::get_model_session", + body: None, + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Same path, READ layer: anon gets 401 (the route requires a signature), + // a signed non-reader of the private repo gets the existence-hiding 404, + // and the owner reads the session the fixture seeded as id "1". + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::ReadGate, + handler: "models::get_model_session", + body: None, + needs: &["model_session"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny401, + }, + // Release status: optional-signature read. The fixture seeds a published + // release on the private repo under commit 40 a's (the {sha} fill), so + // anon/stranger get the existence-hiding 404 and the owner gets a 200. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + gate: GateClass::ReadGate, + handler: "models::get_model_release", + body: None, + needs: &["model_release"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, // The read-gate handlers NOT driven here (deferred GET reads, read-gating // mutations, git smart-HTTP reads, the content-addressed read, and the // global list-filters) are no longer tracked by free-text prose: they are diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 0a23de3e..1507c164 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -288,11 +288,23 @@ short lifetimes reissued often are safer than one long-lived grant. ## Model hosting (experimental) -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 +Off by default: keep it off unless you intend to serve models, since it adds +storage, quota, and a background sweep to the node. When it is on, a model is +a public repo whose releases are signed manifests, and weights are stored as content-addressed blocks outside git. +The model routes mount only when hosting is enabled and a block store +initialized (the filesystem dir above, or the S3 bucket). They are the upload +session and block PUT endpoints, the release claim endpoint, and the release +status and reconstruction reads under +`/api/v1/repos/{owner}/{repo}/models/...`; with hosting off or no store they +answer as though the routes did not exist. + +For S3 operators: the multipart writer leaves incomplete uploads behind when +an abort cannot be confirmed. Give the `model-blocks/` prefix an +`AbortIncompleteMultipartUpload` lifecycle rule so abandoned parts do not +bill forever. + - `TWIGPINE_MODEL_HOSTING_ENABLED=false` - the master switch. - `TWIGPINE_MODEL_QUOTA_BYTES` - per-identity quota for claimed blocks (default 256 GiB). - `TWIGPINE_MODEL_NODE_QUOTA_BYTES` - total model bytes this node will hold (default 1 TiB).