From 7df3db5c683623d94d0371e19ddfbd539d0c0af0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:43:13 -0600 Subject: [PATCH 01/53] feat(node): add model hosting config and schema Adds the operator flags for open-weight model hosting (off by default) and the tables later work builds on: upload sessions, content-addressed blocks, releases, quota, and the durability outbox. Nothing reads or writes them yet, so a node with the flag off behaves exactly as before. --- .env.example | 22 +++ README.md | 1 + crates/twigpine-node/src/config.rs | 129 ++++++++++++++ crates/twigpine-node/src/db/mod.rs | 262 +++++++++++++++++++++++++++++ docs/RUN-A-NODE.md | 18 ++ 5 files changed, 432 insertions(+) diff --git a/.env.example b/.env.example index d18c7324..67d62708 100644 --- a/.env.example +++ b/.env.example @@ -464,3 +464,25 @@ ICAPTCHA_PUBKEY= ICAPTCHA_REQUIRED_LEVEL=3 # Base URL of the iCaptcha service. ICAPTCHA_URL=https://icaptcha.gitlawb.com + +# ── Model hosting (experimental, off by default) ────────────────────────── +# Signed model releases on public repos, with weights stored as +# content-addressed blocks outside git. Off by default; not yet usable end to +# end: this ships the storage and schema only, no publish or read routes yet. +TWIGPINE_MODEL_HOSTING_ENABLED=false +# Per-identity quota for claimed model blocks, in bytes (default 256 GiB). +TWIGPINE_MODEL_QUOTA_BYTES=274877906944 +# Total model bytes this node will hold, claimed plus open sessions (1 TiB). +TWIGPINE_MODEL_NODE_QUOTA_BYTES=1099511627776 +# Seconds an uploaded block may sit unclaimed before the sweep deletes it. +TWIGPINE_MODEL_UNCLAIMED_TTL_SECS=86400 +# Base lifetime of an upload session; each accepted block renews it. +TWIGPINE_MODEL_SESSION_TTL_SECS=43200 +# Optional cap on the sum of one identity's open upload sessions, in bytes. +# Unset means "use TWIGPINE_MODEL_QUOTA_BYTES". +#TWIGPINE_MODEL_MAX_SESSION_BYTES= +# Where model blocks live. Defaults to a model-blocks dir beside the data dir. +# Leave the bucket empty to use the filesystem; set it to store blocks in S3 +# using the same AWS_* endpoint/credentials as the Tigris repo backend. +TWIGPINE_BLOCKSTORE_DIR=./data/model-blocks +TWIGPINE_BLOCKSTORE_S3_BUCKET= diff --git a/README.md b/README.md index 107cc23b..16508f96 100644 --- a/README.md +++ b/README.md @@ -431,6 +431,7 @@ Important node settings: | `TWIGPINE_AUTO_SYNC` | Enable automatic sync from known peers. | | `TWIGPINE_RECONCILIATION_SWEEP` | Enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend (IPFS, Pinata, or both). Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. | | `TWIGPINE_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. | +| `TWIGPINE_MODEL_HOSTING_ENABLED` | Enable experimental model hosting (signed releases, block storage). Off by default; see `docs/RUN-A-NODE.md` for the quota and block-store knobs. | | `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | | `TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | | `TWIGPINE_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 728ec717..fa4e3c44 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -316,6 +316,79 @@ pub struct Config { #[arg(long, env = "TWIGPINE_MAX_PACK_BYTES", default_value_t = 2_147_483_648)] pub max_pack_bytes: usize, + /// Enable open-weight model hosting: signed release manifests on public + /// repos, with weights stored as content-addressed blocks outside git. + /// Off by default; when off the node behaves exactly as before. + #[arg(long, env = "TWIGPINE_MODEL_HOSTING_ENABLED", default_value_t = false)] + pub model_hosting_enabled: bool, + + /// Per-identity storage quota for claimed model blocks, in bytes. + /// Default: 256 GiB, enough for a 70B-class bf16 model. + #[arg( + long, + env = "TWIGPINE_MODEL_QUOTA_BYTES", + default_value_t = 274_877_906_944 + )] + pub model_quota_bytes: u64, + + /// Total model bytes this node will hold, in bytes: claimed blocks plus + /// blocks still sitting in open upload sessions. Default: 1 TiB. + #[arg( + long, + env = "TWIGPINE_MODEL_NODE_QUOTA_BYTES", + default_value_t = 1_099_511_627_776 + )] + pub model_node_quota_bytes: u64, + + /// Seconds an uploaded block may sit unclaimed (referenced by no accepted + /// release) before the sweep deletes it. Must exceed the session TTL so an + /// in-progress upload is never swept under its publisher. Default: 86400. + #[arg( + long, + env = "TWIGPINE_MODEL_UNCLAIMED_TTL_SECS", + default_value_t = 86_400 + )] + pub model_unclaimed_ttl_secs: u64, + + /// Base lifetime of an upload session, in seconds. The expiry slides: each + /// accepted block renews it, so a slow upload that keeps making progress + /// never loses its session. Default: 43200 (12 h). + #[arg( + long, + env = "TWIGPINE_MODEL_SESSION_TTL_SECS", + default_value_t = 43_200 + )] + pub model_session_ttl_secs: u64, + + /// Cap, in bytes, on the sum of one identity's open upload sessions. + /// Unset means "use the per-identity quota". + #[arg(long, env = "TWIGPINE_MODEL_MAX_SESSION_BYTES")] + pub model_max_session_bytes: Option, + + /// Directory where model content blocks are stored when the filesystem + /// backend is in use. Sibling of the repos directory under the node data + /// dir by default. + #[arg( + long, + env = "TWIGPINE_BLOCKSTORE_DIR", + default_value = "./data/model-blocks", + global = true + )] + pub blockstore_dir: PathBuf, + + /// S3-compatible bucket for model content blocks. Empty means the + /// filesystem backend at TWIGPINE_BLOCKSTORE_DIR. Uses the same endpoint + /// and credential environment the Tigris bucket uses + /// (AWS_ENDPOINT_URL_S3, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), so a + /// node already backed by Tigris needs only a bucket name here. + #[arg( + long, + env = "TWIGPINE_BLOCKSTORE_S3_BUCKET", + default_value = "", + global = true + )] + pub blockstore_s3_bucket: String, + /// Per-client-IP rate limit for `POST /api/v1/sync/trigger`, in requests per /// hour. `/sync/trigger` requires a signature and drives an O(peers) outbound /// fan-out per call, so it gets a tight bucket. `0` disables. Default: 60. @@ -1036,6 +1109,14 @@ impl Config { format!("{}:{}", self.host, self.port) } + /// Effective cap on the sum of one identity's open model upload sessions: + /// the explicit cap when set, else the per-identity quota (open sessions + /// may never exceed what the identity could claim). + pub fn effective_model_max_session_bytes(&self) -> u64 { + self.model_max_session_bytes + .unwrap_or(self.model_quota_bytes) + } + /// Resolve ~ in key_path pub fn resolved_key_path(&self) -> PathBuf { if !self.key_path_given { @@ -1316,6 +1397,54 @@ pub(crate) fn validate_web_url(raw: &str) -> Result<(), String> { mod tests { use super::*; + #[test] + fn model_hosting_is_off_by_default_with_expected_budgets() { + let config = Config::parse_from(["twigpine-node"]); + assert!(!config.model_hosting_enabled); + assert_eq!(config.model_quota_bytes, 256 << 30); + assert_eq!(config.model_node_quota_bytes, 1 << 40); + assert_eq!(config.model_unclaimed_ttl_secs, 86_400); + assert_eq!(config.model_session_ttl_secs, 43_200); + // An unset session cap falls back to the per-identity quota. + assert_eq!(config.model_max_session_bytes, None); + assert_eq!( + config.effective_model_max_session_bytes(), + config.model_quota_bytes + ); + assert_eq!(config.blockstore_dir, PathBuf::from("./data/model-blocks")); + assert_eq!(config.blockstore_s3_bucket, ""); + } + + #[test] + fn model_hosting_flags_parse() { + let config = Config::parse_from([ + "twigpine-node", + "--model-hosting-enabled", + "--model-quota-bytes", + "1024", + "--model-node-quota-bytes", + "4096", + "--model-unclaimed-ttl-secs", + "60", + "--model-session-ttl-secs", + "30", + "--model-max-session-bytes", + "2048", + "--blockstore-dir", + "/var/lib/node/blocks", + "--blockstore-s3-bucket", + "model-blocks", + ]); + assert!(config.model_hosting_enabled); + assert_eq!(config.model_quota_bytes, 1024); + assert_eq!(config.model_node_quota_bytes, 4096); + assert_eq!(config.model_unclaimed_ttl_secs, 60); + assert_eq!(config.model_session_ttl_secs, 30); + assert_eq!(config.effective_model_max_session_bytes(), 2048); + assert_eq!(config.blockstore_dir, PathBuf::from("/var/lib/node/blocks")); + assert_eq!(config.blockstore_s3_bucket, "model-blocks"); + } + #[test] fn upstream_mirror_worker_is_default_off_and_bounded() { let mut config = Config::parse_from(["twigpine-node"]); diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 87903f2b..486a3391 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2714,6 +2714,112 @@ const MIGRATIONS: &[Migration] = &[ "CREATE INDEX IF NOT EXISTS idx_repo_push_events_ref ON repo_push_events(repo_id, ref_name, seq DESC)", ], }, + Migration { + // v49: model hosting schema. Nothing reads or writes these tables yet; + // later work mounts upload sessions, release claims, and the + // durability outbox on top of them. Timestamps stay TEXT (RFC 3339), + // the convention every table above follows. + version: 49, + name: "model_hosting_schema", + stmts: &[ + // An upload session is a bearer capability under which a publisher + // streams content-addressed blocks. `bytes_received` bounds what an + // open session holds; `expires_at` slides forward on each accepted + // block so a slow upload that keeps making progress never loses + // its session. + r#"CREATE TABLE IF NOT EXISTS model_upload_sessions ( + id TEXT NOT NULL PRIMARY KEY, + owner_did TEXT NOT NULL, + repo_id TEXT NOT NULL REFERENCES repos(id), + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + bytes_received BIGINT NOT NULL DEFAULT 0, + state TEXT NOT NULL CHECK (state IN ('open', 'closed', 'expired')) + )"#, + // The expiry sweep walks open sessions whose deadline passed. + "CREATE INDEX IF NOT EXISTS idx_model_upload_sessions_expiry ON model_upload_sessions (state, expires_at)", + // Per-identity open-session byte totals are summed by owner. + "CREATE INDEX IF NOT EXISTS idx_model_upload_sessions_owner ON model_upload_sessions (owner_did, state)", + // A block is a sha256-addressed run of packed chunks. Its row + // existing is the node's record that the bytes are stored; + // `unreferenced_since` starts the grace clock once no release or + // open session references it. + r#"CREATE TABLE IF NOT EXISTS model_blocks ( + sha256 TEXT NOT NULL PRIMARY KEY CHECK (sha256 ~ '^[0-9a-f]{64}$'), + size BIGINT NOT NULL CHECK (size > 0), + created_at TEXT NOT NULL, + unreferenced_since TEXT + )"#, + // The sweep walks blocks whose grace clock is running. + "CREATE INDEX IF NOT EXISTS idx_model_blocks_unreferenced ON model_blocks (unreferenced_since) WHERE unreferenced_since IS NOT NULL", + r#"CREATE TABLE IF NOT EXISTS model_session_blocks ( + session_id TEXT NOT NULL REFERENCES model_upload_sessions(id), + block_sha256 TEXT NOT NULL REFERENCES model_blocks(sha256), + PRIMARY KEY (session_id, block_sha256) + )"#, + // Reverse membership: the sweep asks "does any session still hold + // this block?" per block, not per session. + "CREATE INDEX IF NOT EXISTS idx_model_session_blocks_block ON model_session_blocks (block_sha256)", + // A release is a signed manifest commit claimed against a repo. + // Unique on (repo, commit): the commit sha is the release id. The + // claim signature material is persisted the way status_claims + // persists it, so a replayed claim is a no-op instead of a second + // quota charge. + r#"CREATE TABLE IF NOT EXISTS model_releases ( + id BIGSERIAL PRIMARY KEY, + repo_id TEXT NOT NULL REFERENCES repos(id), + commit_sha TEXT NOT NULL, + branch TEXT NOT NULL, + publisher_did TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('verifying', 'published', 'rejected', 'withdrawn')), + manifest_sha256 TEXT NOT NULL, + reconstruction_sha256 TEXT, + failure_reason TEXT, + claim_signature TEXT NOT NULL, + claim_signature_input TEXT NOT NULL, + claim_signing_string TEXT NOT NULL, + claim_body BYTEA NOT NULL, + created_at TEXT NOT NULL, + published_at TEXT, + UNIQUE (repo_id, commit_sha) + )"#, + "CREATE INDEX IF NOT EXISTS idx_model_releases_publisher ON model_releases (publisher_did, state)", + // The read surface resolves a branch to its newest published + // release. + "CREATE INDEX IF NOT EXISTS idx_model_releases_repo_branch ON model_releases (repo_id, branch, state, id DESC)", + r#"CREATE TABLE IF NOT EXISTS model_release_blocks ( + release_id BIGINT NOT NULL REFERENCES model_releases(id), + block_sha256 TEXT NOT NULL REFERENCES model_blocks(sha256), + PRIMARY KEY (release_id, block_sha256) + )"#, + // Reverse membership: the sweeper asks "does any release still + // reference this block?", and quota is summed over the distinct + // blocks a DID's live releases reference. + "CREATE INDEX IF NOT EXISTS idx_model_release_blocks_block ON model_release_blocks (block_sha256)", + r#"CREATE TABLE IF NOT EXISTS model_quota_usage ( + did TEXT NOT NULL PRIMARY KEY, + bytes_used BIGINT NOT NULL DEFAULT 0 CHECK (bytes_used >= 0) + )"#, + // Durable outbox for pin and anchor work. One row per (release, + // kind, object), claimed and retried by a worker; provider_cid + // records the returned CID separately from the sha256 that keys + // the object, so the content address stays the resolver key. + r#"CREATE TABLE IF NOT EXISTS model_durability_jobs ( + id BIGSERIAL PRIMARY KEY, + release_id BIGINT NOT NULL REFERENCES model_releases(id), + kind TEXT NOT NULL CHECK (kind IN ('pin_block', 'pin_manifest', 'pin_reconstruction', 'pin_block_map', 'anchor')), + object_key TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'done', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + provider_cid TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE (release_id, kind, object_key) + )"#, + "CREATE INDEX IF NOT EXISTS idx_model_durability_jobs_pending ON model_durability_jobs (state, created_at)", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -14288,6 +14394,162 @@ mod migration_tests { .unwrap(); assert_eq!(cid, "QmLocalGenuine"); } + + // ── Model hosting schema (v49) ───────────────────────────────────────── + + const V49: i64 = 49; + + const MODEL_TABLES: &[&str] = &[ + "model_upload_sessions", + "model_blocks", + "model_session_blocks", + "model_releases", + "model_release_blocks", + "model_quota_usage", + "model_durability_jobs", + ]; + + async fn model_fixture_repo(db: &super::Db, id: &str) { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1, $2, 'did:key:zOwner', TRUE, 'main', + '2026-11-19T00:00:00+00:00', '2026-11-19T00:00:00+00:00', $3)", + ) + .bind(id) + .bind(format!("model-{id}")) + .bind(format!("/srv/repos/{id}.git")) + .execute(&db.pool) + .await + .unwrap(); + } + + async fn insert_model_release(db: &super::Db, repo_id: &str, commit: &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', 'did:key:zOwner', 'verifying', + $3, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", + ) + .bind(repo_id) + .bind(commit) + .bind("c".repeat(64)) + .execute(&db.pool) + .await + .unwrap(); + } + + /// A fresh database runs the whole chain and lands every model table. + #[sqlx::test] + async fn migration_v49_fresh_chain_creates_model_tables(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + + for table in MODEL_TABLES { + assert!(table_exists(&db, table).await, "{table} missing"); + } + } + + /// A node already at the previous version gains the same tables through + /// the runner, not just a fresh chain. Rolling back by dropping the v49 + /// objects keeps the test honest if the statements were ever appended to + /// an already-applied entry. + #[sqlx::test] + async fn migration_v49_upgrade_path_adds_model_tables(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + + for table in MODEL_TABLES.iter().rev() { + sqlx::query(&format!("DROP TABLE IF EXISTS {table}")) + .execute(&db.pool) + .await + .unwrap(); + } + sqlx::query("DELETE FROM schema_migrations WHERE version >= $1") + .bind(V49) + .execute(&db.pool) + .await + .unwrap(); + + db.migrate().await.unwrap(); + + for table in MODEL_TABLES { + assert!( + table_exists(&db, table).await, + "{table} missing after upgrade on an existing node" + ); + } + let recorded: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM schema_migrations WHERE version = $1") + .bind(V49) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(recorded, 1, "v49 must be recorded as applied"); + + // Idempotent re-run. + db.migrate().await.unwrap(); + } + + /// The release id is (repo, commit): a second claim of the same commit on + /// the same repo is a replay the schema refuses. + #[sqlx::test] + async fn model_releases_rejects_duplicate_repo_commit(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + model_fixture_repo(&db, "repo-model").await; + + insert_model_release(&db, "repo-model", SHA_A).await; + let second = 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 ('repo-model', $1, 'main', 'did:key:zOwner', 'verifying', + $2, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", + ) + .bind(SHA_A) + .bind("d".repeat(64)) + .execute(&db.pool) + .await; + assert!( + second.is_err(), + "a duplicate (repo, commit) release must violate the unique constraint" + ); + + // A different commit on the same repo is a different release. + insert_model_release(&db, "repo-model", SHA_B).await; + } + + /// The block table accepts only a 64-lowercase-hex content address: the + /// id is derived from the bytes everywhere it is used, so a malformed id + /// in the table would corrupt every reference to it. + #[sqlx::test] + async fn model_blocks_rejects_malformed_sha(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + + for bad in ["nothex", &"A".repeat(64), &"g".repeat(64), &"e".repeat(63)] { + let result = sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) + VALUES ($1, 10, '2026-11-19T00:00:00+00:00')", + ) + .bind(bad) + .execute(&db.pool) + .await; + assert!(result.is_err(), "block id {bad:?} must be rejected"); + } + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) + VALUES ($1, 10, '2026-11-19T00:00:00+00:00')", + ) + .bind("e".repeat(64)) + .execute(&db.pool) + .await + .unwrap(); + } } #[cfg(test)] diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 01fb488c..60792c8e 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -282,6 +282,24 @@ 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 +content-addressed blocks outside git. + +- `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). +- `TWIGPINE_MODEL_UNCLAIMED_TTL_SECS` - grace period before unclaimed blocks are swept (default 86400). +- `TWIGPINE_MODEL_SESSION_TTL_SECS` - base upload-session lifetime, renewed by each accepted block (default 43200). +- `TWIGPINE_MODEL_MAX_SESSION_BYTES` - optional cap on one identity's open sessions (defaults to the quota). +- `TWIGPINE_BLOCKSTORE_DIR` - where blocks live on disk (default `./data/model-blocks`). +- `TWIGPINE_BLOCKSTORE_S3_BUCKET` - set to store blocks in S3 instead; reuses the same `AWS_*` endpoint and credentials as the Tigris repo backend. + +--- + ## Operational checklist | Concern | Recommendation | From fc84e888f7bdc295a1f7c3149a9d514289eb0069 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:57:45 -0600 Subject: [PATCH 02/53] feat(node): add content-addressed BlockStore with fs and S3 backends A content-neutral store for verified, content-addressed objects: writes stream while hashing and become visible only when the bytes match the id (atomic link on fs, conditional complete on S3), reads are ranged, and a lost S3 answer reports Unknown rather than a false failure. Built only when model hosting is enabled, and a bad backend config fails closed. Kept deliberately separate from the whole-object archive store proposed elsewhere. --- crates/twigpine-node/src/auth/mod.rs | 1 + crates/twigpine-node/src/blockstore/fs.rs | 334 +++++++++++ crates/twigpine-node/src/blockstore/mod.rs | 151 +++++ crates/twigpine-node/src/blockstore/s3.rs | 640 +++++++++++++++++++++ crates/twigpine-node/src/lib.rs | 16 + crates/twigpine-node/src/state.rs | 3 + crates/twigpine-node/src/test_harness.rs | 1 + crates/twigpine-node/src/test_support.rs | 1 + 8 files changed, 1147 insertions(+) create mode 100644 crates/twigpine-node/src/blockstore/fs.rs create mode 100644 crates/twigpine-node/src/blockstore/mod.rs create mode 100644 crates/twigpine-node/src/blockstore/s3.rs diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index eae95884..24c09296 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -1303,6 +1303,7 @@ mod tests { crate::rate_limit::PerCallerConcurrency::with_default_max_keys(16), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), + block_store: None, } } diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs new file mode 100644 index 00000000..917186b2 --- /dev/null +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -0,0 +1,334 @@ +//! Filesystem block backend: objects under `///` with +//! staged writes in `/tmp/`. +//! +//! A write lands in a uniquely-named temp file, is fsynced, and becomes +//! visible only through a hard link to its content address, which is atomic +//! and refuses to overwrite: two publishers racing the same object get one +//! `Stored` and one `AlreadyPresent`, never a torn object. The temp file is +//! removed on every failure path, so a rejected body leaves nothing behind. + +use std::io; +use std::path::{Path, PathBuf}; + +use async_trait::async_trait; +use bytes::Bytes; +use futures::stream::BoxStream; +use futures::StreamExt; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; + +use super::{BlockId, BlockStore, BlockStoreError, PutOutcome}; + +pub struct FsBlockStore { + root: PathBuf, +} + +impl FsBlockStore { + pub fn new(root: PathBuf) -> io::Result { + std::fs::create_dir_all(root.join("tmp"))?; + Ok(Self { root }) + } + + fn content_path(&self, id: &BlockId) -> PathBuf { + let s = id.as_str(); + self.root.join(&s[..2]).join(&s[2..4]).join(s) + } + + fn temp_path(&self) -> PathBuf { + self.root + .join("tmp") + .join(format!("put-{}", uuid::Uuid::new_v4())) + } + + async fn cleanup(path: &Path) { + let _ = tokio::fs::remove_file(path).await; + } +} + +#[async_trait] +impl BlockStore for FsBlockStore { + async fn put_verified( + &self, + id: &BlockId, + mut body: BoxStream<'static, io::Result>, + max_len: u64, + ) -> Result { + let dest = self.content_path(id); + if dest.exists() { + return Ok(PutOutcome::AlreadyPresent); + } + + let tmp = self.temp_path(); + let mut file = match tokio::fs::File::create(&tmp).await { + Ok(f) => f, + Err(e) => return Err(e.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?; + len = len.saturating_add(chunk.len() as u64); + if len > max_len { + return Err(BlockStoreError::TooLarge(max_len)); + } + hasher.update(&chunk); + file.write_all(&chunk).await?; + } + Ok(()) + } + .await; + + if let Err(e) = result { + drop(file); + Self::cleanup(&tmp).await; + return Err(e); + } + if hex::encode(hasher.finalize()) != id.as_str() { + drop(file); + Self::cleanup(&tmp).await; + return Err(BlockStoreError::DigestMismatch); + } + // Flush before the link: a crash between link and write-back would + // leave a truncated object under a valid id. + if let Err(e) = file.sync_all().await { + drop(file); + Self::cleanup(&tmp).await; + return Err(e.into()); + } + drop(file); + + if let Some(parent) = dest.parent() { + if let Err(e) = tokio::fs::create_dir_all(parent).await { + Self::cleanup(&tmp).await; + return Err(e.into()); + } + } + // A hard link refuses to replace an existing object, which is what + // makes a same-content race benign rather than a torn write. + match tokio::fs::hard_link(&tmp, &dest).await { + Ok(()) => { + Self::cleanup(&tmp).await; + Ok(PutOutcome::Stored) + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + Self::cleanup(&tmp).await; + Ok(PutOutcome::AlreadyPresent) + } + Err(e) => { + Self::cleanup(&tmp).await; + Err(e.into()) + } + } + } + + async fn get_range( + &self, + id: &BlockId, + start: u64, + end_exclusive: u64, + ) -> Result>, BlockStoreError> { + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + let path = self.content_path(id); + let mut file = match tokio::fs::File::open(&path).await { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(BlockStoreError::NotFound), + Err(e) => return Err(e.into()), + }; + let len = file.metadata().await?.len(); + if start > end_exclusive || end_exclusive > len { + return Err(BlockStoreError::OutOfRange); + } + file.seek(io::SeekFrom::Start(start)).await?; + let limited = file.take(end_exclusive - start); + Ok(tokio_util::io::ReaderStream::new(limited).boxed()) + } + + async fn size(&self, id: &BlockId) -> Result, BlockStoreError> { + match tokio::fs::metadata(self.content_path(id)).await { + Ok(m) => Ok(Some(m.len())), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + } + + async fn delete(&self, id: &BlockId) -> Result<(), BlockStoreError> { + match tokio::fs::remove_file(self.content_path(id)).await { + Ok(()) => Ok(()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } + } + + fn backend_name(&self) -> &'static str { + "fs" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use sha2::Digest; + + fn id_of(bytes: &[u8]) -> BlockId { + BlockId::parse(&hex::encode(Sha256::digest(bytes))).unwrap() + } + + fn stream(bytes: Vec) -> BoxStream<'static, io::Result> { + futures::stream::iter(vec![Ok(Bytes::from(bytes))]).boxed() + } + + fn chunked_stream(parts: Vec>) -> BoxStream<'static, io::Result> { + futures::stream::iter(parts.into_iter().map(|p| Ok(Bytes::from(p)))).boxed() + } + + async fn collect(mut s: BoxStream<'static, io::Result>) -> Vec { + let mut out = Vec::new(); + while let Some(c) = s.next().await { + out.extend_from_slice(&c.unwrap()); + } + out + } + + fn store(dir: &tempfile::TempDir) -> FsBlockStore { + FsBlockStore::new(dir.path().join("blocks")).unwrap() + } + + #[tokio::test] + async fn put_get_size_roundtrip() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let body: Vec = (0..100_000u32).flat_map(|i| i.to_le_bytes()).collect(); + let id = id_of(&body); + assert_eq!( + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(), + PutOutcome::Stored + ); + assert_eq!(s.size(&id).await.unwrap(), Some(body.len() as u64)); + assert_eq!(s.backend_name(), "fs"); + // A second put of the same content is a no-op. + assert_eq!( + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(), + PutOutcome::AlreadyPresent + ); + } + + #[tokio::test] + async fn wrong_id_is_rejected_and_leaves_nothing() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let id = id_of(b"different bytes"); + let err = s + .put_verified(&id, stream(b"actual".to_vec()), u64::MAX) + .await + .unwrap_err(); + assert!(matches!(err, BlockStoreError::DigestMismatch)); + assert_eq!(s.size(&id).await.unwrap(), None); + // No temp file survives the failure. + assert_eq!( + std::fs::read_dir(dir.path().join("blocks/tmp")) + .unwrap() + .count(), + 0 + ); + } + + #[tokio::test] + async fn oversized_body_is_rejected_while_streaming() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let body = vec![0u8; 1024]; + let id = id_of(&body); + let err = s.put_verified(&id, stream(body), 512).await.unwrap_err(); + assert!(matches!(err, BlockStoreError::TooLarge(512))); + assert_eq!(s.size(&id).await.unwrap(), None); + } + + #[tokio::test] + async fn range_reads_return_exact_bytes() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let body: Vec = (0..255u8).collect(); + let id = id_of(&body); + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(); + + let got = collect(s.get_range(&id, 10, 20).await.unwrap()).await; + assert_eq!(got, body[10..20]); + + let got = collect(s.get_range(&id, 0, 255).await.unwrap()).await; + assert_eq!(got, body); + + assert!(matches!( + s.get_range(&id, 200, 300).await.map(|_| ()).unwrap_err(), + BlockStoreError::OutOfRange + )); + let missing = id_of(b"missing"); + assert!(matches!( + s.get_range(&missing, 0, 1).await.map(|_| ()).unwrap_err(), + BlockStoreError::NotFound + )); + } + + #[tokio::test] + async fn concurrent_puts_leave_one_object() { + let dir = tempfile::tempdir().unwrap(); + let s = std::sync::Arc::new(store(&dir)); + let body: Vec = (0..50_000u32).map(|i| (i % 251) as u8).collect(); + let id = id_of(&body); + let (a, b) = tokio::join!( + s.put_verified(&id, stream(body.clone()), u64::MAX), + s.put_verified(&id, stream(body.clone()), u64::MAX) + ); + assert!(a.is_ok() && b.is_ok()); + assert_eq!(s.size(&id).await.unwrap(), Some(body.len() as u64)); + let got = collect(s.get_range(&id, 0, body.len() as u64).await.unwrap()).await; + assert_eq!(got, body); + } + + #[tokio::test] + async fn delete_removes_and_is_idempotent() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let id = id_of(b"gone"); + s.put_verified(&id, stream(b"gone".to_vec()), u64::MAX) + .await + .unwrap(); + s.delete(&id).await.unwrap(); + assert_eq!(s.size(&id).await.unwrap(), None); + s.delete(&id).await.unwrap(); + } + + #[tokio::test] + async fn streamed_chunks_hash_the_whole_body() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let body: Vec = (0..10_000u32).map(|i| (i % 256) as u8).collect(); + let parts: Vec> = body.chunks(777).map(|c| c.to_vec()).collect(); + let id = id_of(&body); + s.put_verified(&id, chunked_stream(parts), u64::MAX) + .await + .unwrap(); + let got = collect(s.get_range(&id, 0, body.len() as u64).await.unwrap()).await; + assert_eq!(got, body); + } + + #[test] + fn block_id_shape() { + assert!(BlockId::parse(&"a".repeat(64)).is_ok()); + for bad in [ + "abc", + &"A".repeat(64), + &"g".repeat(64), + &"a".repeat(63), + &"a".repeat(65), + ] { + assert!(BlockId::parse(bad).is_err(), "{bad} must be rejected"); + } + } +} diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs new file mode 100644 index 00000000..fe88fd08 --- /dev/null +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -0,0 +1,151 @@ +//! Content-addressed block storage for model weights. +//! +//! A block is a sequence of content chunks packed into one object, named by +//! the sha256 of its bytes. The store is content-neutral: later content types +//! (datasets, assets) reuse it without a parallel access surface. +//! +//! Writes are verified, not trusted: a caller supplies the expected id and the +//! backend hashes the body as it streams, so a corrupted or malicious payload +//! is rejected and never becomes visible under its claimed name. Reads are +//! ranged, so a downloader resumes without re-serving whole blocks. + +use std::fmt; +use std::io; +use std::str::FromStr; +use std::sync::Arc; + +use async_trait::async_trait; +use bytes::Bytes; +use futures::stream::BoxStream; +use thiserror::Error; + +pub mod fs; +pub mod s3; + +/// A content address: exactly 64 lowercase hex characters, the sha256 of the +/// object's bytes. The shape is validated once at the boundary so every +/// backend can treat `id.as_str()` as a safe storage key fragment. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct BlockId(String); + +impl BlockId { + pub fn parse(s: &str) -> Result { + let valid = s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if valid { + Ok(Self(s.to_string())) + } else { + Err(BlockIdError) + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for BlockId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl FromStr for BlockId { + type Err = BlockIdError; + fn from_str(s: &str) -> Result { + Self::parse(s) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +#[error("a block id is exactly 64 lowercase hex characters")] +pub struct BlockIdError; + +/// What a verified write did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PutOutcome { + /// The object's bytes were verified and are now stored under its id. + Stored, + /// An object already exists under this id. Because the id is the content + /// hash, the stored bytes are the same bytes, so nothing was written. + AlreadyPresent, +} + +#[derive(Debug, Error)] +pub enum BlockStoreError { + /// The streamed body did not hash to the id it was written under. Nothing + /// was stored. + #[error("body does not hash to the expected block id")] + DigestMismatch, + /// The body exceeded the caller-supplied cap while streaming. Nothing was + /// stored. + #[error("body exceeds the {0}-byte limit")] + TooLarge(u64), + /// The requested byte range is outside the stored object. + #[error("requested range is outside the object")] + OutOfRange, + /// No object exists under this id. + #[error("no object under this block id")] + NotFound, + /// A remote write's outcome cannot be determined: the request may have + /// committed while its answer was lost. Callers must treat the object as + /// possibly present and resolve with `size()` before retrying, exactly the + /// vocabulary `git::publish` uses for an upload whose commit status is + /// unknown. + #[error("the write's outcome is unknown; check size() before retrying")] + Unknown, + #[error("i/o error: {0}")] + Io(#[from] io::Error), + #[error("backend error: {0}")] + Backend(String), +} + +#[async_trait] +pub trait BlockStore: Send + Sync { + /// Stream `body` into the store under `id`, hashing as it goes. The body + /// is never fully buffered. Fails with `TooLarge` the moment the body + /// exceeds `max_len`, with `DigestMismatch` when the bytes do not hash to + /// `id`, and leaves no object or temporary state behind on any failure. + async fn put_verified( + &self, + id: &BlockId, + body: BoxStream<'static, io::Result>, + max_len: u64, + ) -> Result; + + /// Stream bytes `[start, end_exclusive)` of the stored object. A range + /// past the end fails with `OutOfRange`; a missing object with `NotFound`. + async fn get_range( + &self, + id: &BlockId, + start: u64, + end_exclusive: u64, + ) -> Result>, BlockStoreError>; + + /// The stored object's length in bytes, or `None` when absent. + async fn size(&self, id: &BlockId) -> Result, BlockStoreError>; + + /// Remove the object. Deleting an absent object is not an error. + async fn delete(&self, id: &BlockId) -> Result<(), BlockStoreError>; + + /// Which backend this is ("fs" or "s3"), for logging and diagnostics. + fn backend_name(&self) -> &'static str; +} + +/// Build the configured backend, or `None` when model hosting is off. +/// +/// Fails closed: with the flag on, a backend that cannot be constructed is an +/// error the caller propagates, not a silent fall back to local disk (the +/// same posture purge-spam takes with the object store). +pub async fn build(config: &crate::config::Config) -> anyhow::Result>> { + if !config.model_hosting_enabled { + return Ok(None); + } + if !config.blockstore_s3_bucket.is_empty() { + let store = s3::S3BlockStore::new(&config.blockstore_s3_bucket).await?; + return Ok(Some(Arc::new(store))); + } + let store = fs::FsBlockStore::new(config.blockstore_dir.clone())?; + Ok(Some(Arc::new(store))) +} diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs new file mode 100644 index 00000000..d911f23d --- /dev/null +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -0,0 +1,640 @@ +//! S3-compatible block backend: objects under `model-blocks/v1//`, +//! written through multipart upload. +//! +//! The verified-write contract maps onto multipart cleanly: parts go up while +//! the body streams (never fully buffered), and the object becomes visible +//! only when `CompleteMultipartUpload` commits, which runs after the hash +//! check. A mismatch aborts the upload instead, so a bad body never leaves an +//! object under a valid-looking id. +//! +//! The one case multipart cannot answer is a lost response: a timeout after +//! the complete request was sent may still have committed the object. That is +//! reported as [`BlockStoreError::Unknown`], the same "maybe sent" vocabulary +//! `git::publish` uses, and the caller resolves it with a HEAD rather than +//! assuming the write failed. + +use std::io; + +use async_trait::async_trait; +use aws_sdk_s3::error::SdkError; +use aws_sdk_s3::primitives::ByteStream; +use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart}; +use aws_sdk_s3::Client as S3Client; +use bytes::Bytes; +use futures::stream::BoxStream; +use futures::StreamExt; +use sha2::{Digest, Sha256}; +#[cfg(test)] +use std::time::Duration; + +use super::{BlockId, BlockStore, BlockStoreError, PutOutcome}; + +/// Multipart part size. Larger than the 5 MiB floor so a 128 MiB block is a +/// handful of parts, small enough that one part's retry cost stays bounded. +const PART_SIZE: usize = 16 * 1024 * 1024; + +const KEY_PREFIX: &str = "model-blocks/v1"; + +pub struct S3BlockStore { + s3: S3Client, + bucket: String, +} + +impl S3BlockStore { + /// Create a client against the configured endpoint: the same + /// 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; + Ok(Self { + s3: S3Client::new(&config), + bucket: bucket.to_string(), + }) + } + + /// Build a client pointed at an arbitrary endpoint for tests. The + /// production constructor reads the endpoint from the environment, which + /// a test cannot steer; retries are disabled so a dead endpoint fails + /// fast instead of backing off for seconds. + #[cfg(test)] + fn for_testing(bucket: &str, endpoint: &str, timeout: std::time::Duration) -> Self { + use aws_sdk_s3::config::retry::RetryConfig; + use aws_sdk_s3::config::timeout::TimeoutConfig; + use aws_sdk_s3::config::{Credentials, Region}; + + let config = aws_sdk_s3::config::Config::builder() + .endpoint_url(endpoint) + .credentials_provider(Credentials::new("test", "test", None, None, "test")) + .region(Region::new("auto")) + .retry_config(RetryConfig::disabled()) + .timeout_config(TimeoutConfig::builder().operation_timeout(timeout).build()) + .behavior_version_latest() + .build(); + Self { + s3: S3Client::from_conf(config), + bucket: bucket.to_string(), + } + } + + fn key(id: &BlockId) -> String { + let s = id.as_str(); + format!("{KEY_PREFIX}/{}/{s}", &s[..2]) + } + + fn backend(err: E) -> BlockStoreError { + BlockStoreError::Backend(err.to_string()) + } + + async fn upload_one_part( + &self, + key: &str, + upload_id: &str, + number: i32, + bytes: Vec, + ) -> Result { + let out = self + .s3 + .upload_part() + .bucket(&self.bucket) + .key(key) + .upload_id(upload_id) + .part_number(number) + .body(ByteStream::from(bytes)) + .send() + .await + .map_err(Self::backend)?; + Ok(CompletedPart::builder() + .part_number(number) + .e_tag(out.e_tag().unwrap_or_default()) + .build()) + } + + async fn abort(&self, key: &str, upload_id: &str) { + if let Err(e) = self + .s3 + .abort_multipart_upload() + .bucket(&self.bucket) + .key(key) + .upload_id(upload_id) + .send() + .await + { + // An abort that fails leaves orphaned parts, which cost storage + // but never serve: the object is invisible until a complete + // commits, and only the upload's owner knows the parts' hashes. + tracing::warn!(key = %key, "multipart abort failed: {e}"); + } + } + + /// Classify a failed `CompleteMultipartUpload`: does the failure PROVE + /// the object was not committed? Only a refusal the server took before + /// storing (a 4xx) or a request that never left the client proves that; + /// anything else may have committed while the answer was lost, and the + /// honest answer is `Unknown`. Same rule as `git::tigris`'s dispatch + /// classifier, including the cautious fallback for the `#[non_exhaustive]` + /// error enum. + fn classify_complete_failure(err: &SdkError) -> BlockStoreError { + if let Some(status) = err.raw_response().map(|r| r.status().as_u16()) { + return if (400..500).contains(&status) { + Self::backend(format!("complete refused with status {status}")) + } else { + BlockStoreError::Unknown + }; + } + match err { + SdkError::ConstructionFailure(_) => Self::backend(err.to_string()), + _ => BlockStoreError::Unknown, + } + } +} + +#[async_trait] +impl BlockStore for S3BlockStore { + async fn put_verified( + &self, + id: &BlockId, + mut body: BoxStream<'static, io::Result>, + max_len: u64, + ) -> Result { + let key = Self::key(id); + if self.size(id).await?.is_some() { + return Ok(PutOutcome::AlreadyPresent); + } + + // A zero-length body cannot be a multipart upload, but it can be a + // valid (if useless) object under the empty-sha id. + let upload = self + .s3 + .create_multipart_upload() + .bucket(&self.bucket) + .key(&key) + .send() + .await + .map_err(Self::backend)?; + let upload_id = upload.upload_id().unwrap_or_default().to_string(); + + let mut hasher = Sha256::new(); + let mut len: u64 = 0; + let mut part_buf: Vec = Vec::with_capacity(PART_SIZE); + let mut parts: Vec = Vec::new(); + + // `part_buf` is taken and replaced on each flush, so only one part is + // ever resident, never the whole body. + let result: Result<(), BlockStoreError> = async { + while let Some(chunk) = body.next().await { + let chunk = chunk?; + len = len.saturating_add(chunk.len() as u64); + if len > max_len { + return Err(BlockStoreError::TooLarge(max_len)); + } + hasher.update(&chunk); + part_buf.extend_from_slice(&chunk); + if part_buf.len() >= PART_SIZE { + let staged = std::mem::take(&mut part_buf); + let number = (parts.len() + 1) as i32; + parts.push( + self.upload_one_part(&key, &upload_id, number, staged) + .await?, + ); + } + } + Ok(()) + } + .await; + + if let Err(e) = result { + self.abort(&key, &upload_id).await; + return Err(e); + } + if hex::encode(hasher.finalize()) != id.as_str() { + self.abort(&key, &upload_id).await; + return Err(BlockStoreError::DigestMismatch); + } + if !part_buf.is_empty() { + let staged = std::mem::take(&mut part_buf); + let number = (parts.len() + 1) as i32; + match self.upload_one_part(&key, &upload_id, number, staged).await { + Ok(part) => parts.push(part), + Err(e) => { + self.abort(&key, &upload_id).await; + return Err(e); + } + } + } + if parts.is_empty() { + // len == 0 and the hash matched, meaning id is the empty-sha. + self.abort(&key, &upload_id).await; + self.s3 + .put_object() + .bucket(&self.bucket) + .key(&key) + .body(ByteStream::from_static(b"")) + .send() + .await + .map_err(|e| { + if e.raw_response().is_none() { + BlockStoreError::Unknown + } else { + Self::backend(e) + } + })?; + return Ok(PutOutcome::Stored); + } + + let completed = CompletedMultipartUpload::builder() + .set_parts(Some(parts)) + .build(); + match self + .s3 + .complete_multipart_upload() + .bucket(&self.bucket) + .key(&key) + .upload_id(&upload_id) + .multipart_upload(completed) + .send() + .await + { + Ok(_) => Ok(PutOutcome::Stored), + Err(e) => { + let verdict = Self::classify_complete_failure(&e); + if !matches!(verdict, BlockStoreError::Unknown) { + self.abort(&key, &upload_id).await; + } + Err(verdict) + } + } + } + + async fn get_range( + &self, + id: &BlockId, + start: u64, + end_exclusive: u64, + ) -> Result>, BlockStoreError> { + if start >= end_exclusive { + return Err(BlockStoreError::OutOfRange); + } + let out = self + .s3 + .get_object() + .bucket(&self.bucket) + .key(Self::key(id)) + .range(format!("bytes={start}-{}", end_exclusive - 1)) + .send() + .await + .map_err(|e| { + if e.as_service_error().is_some_and(|s| s.is_no_such_key()) + || e.raw_response().map(|r| r.status().as_u16()) == Some(404) + { + return BlockStoreError::NotFound; + } + // S3 answers an unsatisfiable range with 416 InvalidRange. + if e.raw_response().map(|r| r.status().as_u16()) == Some(416) { + return BlockStoreError::OutOfRange; + } + Self::backend(e) + })?; + Ok(tokio_util::io::ReaderStream::new(out.body.into_async_read()).boxed()) + } + + async fn size(&self, id: &BlockId) -> Result, BlockStoreError> { + match self + .s3 + .head_object() + .bucket(&self.bucket) + .key(Self::key(id)) + .send() + .await + { + Ok(out) => Ok(out.content_length().map(|l| l as u64)), + Err(e) => { + let status = e.raw_response().map(|r| r.status().as_u16()); + if e.as_service_error().is_some_and(|s| s.is_not_found()) || status == Some(404) { + Ok(None) + } else { + Err(Self::backend(e)) + } + } + } + } + + async fn delete(&self, id: &BlockId) -> Result<(), BlockStoreError> { + self.s3 + .delete_object() + .bucket(&self.bucket) + .key(Self::key(id)) + .send() + .await + .map_err(Self::backend)?; + Ok(()) + } + + fn backend_name(&self) -> &'static str { + "s3" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::body::Bytes as AxBytes; + use axum::extract::{Query, State}; + use axum::http::{HeaderMap, StatusCode}; + use axum::response::Response; + use axum::routing::{delete, get, head, post, put}; + use axum::Router; + use sha2::Digest; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + /// A minimal in-memory S3 mock: just enough of the API surface the + /// backend calls (multipart create/part/complete/abort, put, get, head, + /// delete). No signature check; the SDK client is built with test + /// credentials and the point of the mock is protocol shape, not auth. + #[derive(Default)] + struct Objects { + map: Mutex>>, + parts: Mutex>>, + /// When set, the complete endpoint stores the object and then hangs + /// past the client's operation timeout, simulating a commit whose + /// answer was lost. + hang_on_complete: Mutex, + } + + async fn head_handler( + State(st): State>, + axum::extract::Path((_bucket, key)): axum::extract::Path<(String, String)>, + ) -> Response { + let objects = st.map.lock().unwrap(); + match objects.get(&key) { + Some(body) => Response::builder() + .status(StatusCode::OK) + .header("content-length", body.len().to_string()) + .body(axum::body::Body::empty()) + .unwrap(), + None => Response::builder() + .status(StatusCode::NOT_FOUND) + .body(axum::body::Body::empty()) + .unwrap(), + } + } + + async fn get_handler( + State(st): State>, + axum::extract::Path((_bucket, key)): axum::extract::Path<(String, String)>, + headers: HeaderMap, + ) -> Response { + let objects = st.map.lock().unwrap(); + let Some(body) = objects.get(&key) else { + return Response::builder() + .status(StatusCode::NOT_FOUND) + .body(axum::body::Body::from( + "NoSuchKey", + )) + .unwrap(); + }; + if let Some(range) = headers.get("range").and_then(|v| v.to_str().ok()) { + // bytes=- + let spec = range.trim_start_matches("bytes="); + let (a, b) = spec.split_once('-').unwrap(); + let (start, end): (usize, usize) = (a.parse().unwrap(), b.parse().unwrap()); + if end >= body.len() { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(axum::body::Body::from( + "InvalidRange", + )) + .unwrap(); + } + return Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .body(axum::body::Body::from(body[start..=end].to_vec())) + .unwrap(); + } + Response::builder() + .status(StatusCode::OK) + .body(axum::body::Body::from(body.clone())) + .unwrap() + } + + async fn put_handler( + State(st): State>, + axum::extract::Path((_bucket, key)): axum::extract::Path<(String, String)>, + Query(q): Query>, + body: AxBytes, + ) -> Response { + if let (Some(part), Some(_)) = ( + q.get("partNumber").and_then(|p| p.parse::().ok()), + q.get("uploadId"), + ) { + st.parts.lock().unwrap().insert((key, part), body.to_vec()); + return Response::builder() + .status(StatusCode::OK) + .header("etag", format!("etag-{part}")) + .body(axum::body::Body::empty()) + .unwrap(); + } + // Plain put (used by the zero-length object path). + st.map.lock().unwrap().insert(key, body.to_vec()); + Response::builder() + .status(StatusCode::OK) + .header("etag", "etag-0") + .body(axum::body::Body::empty()) + .unwrap() + } + + async fn post_handler( + State(st): State>, + axum::extract::Path((_bucket, key)): axum::extract::Path<(String, String)>, + Query(q): Query>, + body: AxBytes, + ) -> Response { + if q.contains_key("uploads") { + return Response::builder() + .status(StatusCode::OK) + .body(axum::body::Body::from( + "u-1", + )) + .unwrap(); + } + if q.contains_key("uploadId") { + // Assemble the object's parts in number order from the complete + // request's part list. + let text = String::from_utf8_lossy(&body); + let mut numbers: Vec = text + .match_indices("") + .map(|(i, _)| { + let rest = &text[i + 12..]; + rest[..rest.find('<').unwrap()].parse().unwrap() + }) + .collect(); + numbers.sort_unstable(); + let mut assembled = Vec::new(); + { + let parts = st.parts.lock().unwrap(); + for n in &numbers { + if let Some(p) = parts.get(&(key.clone(), *n)) { + assembled.extend_from_slice(p); + } + } + } + st.map.lock().unwrap().insert(key.clone(), assembled); + st.parts.lock().unwrap().retain(|(k, _), _| k != &key); + if *st.hang_on_complete.lock().unwrap() { + // The object is stored; the answer never arrives. + futures::future::pending::<()>().await; + } + return Response::builder() + .status(StatusCode::OK) + .body(axum::body::Body::from( + "final", + )) + .unwrap(); + } + Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(axum::body::Body::empty()) + .unwrap() + } + + async fn delete_handler( + State(st): State>, + axum::extract::Path((_bucket, key)): axum::extract::Path<(String, String)>, + Query(q): Query>, + ) -> Response { + if q.contains_key("uploadId") { + st.parts.lock().unwrap().retain(|(k, _), _| k != &key); + } else { + st.map.lock().unwrap().remove(&key); + } + Response::builder() + .status(StatusCode::NO_CONTENT) + .body(axum::body::Body::empty()) + .unwrap() + } + + /// Spawn the mock on an ephemeral port; returns (base_url, state). + async fn spawn_mock(hang_on_complete: bool) -> (String, Arc) { + let st = Arc::new(Objects { + hang_on_complete: Mutex::new(hang_on_complete), + ..Objects::default() + }); + let app = Router::new() + .route("/{bucket}/{*key}", get(get_handler)) + .route("/{bucket}/{*key}", put(put_handler)) + .route("/{bucket}/{*key}", post(post_handler)) + .route("/{bucket}/{*key}", head(head_handler)) + .route("/{bucket}/{*key}", delete(delete_handler)) + .with_state(st.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (format!("http://{addr}"), st) + } + + fn id_of(bytes: &[u8]) -> BlockId { + BlockId::parse(&hex::encode(Sha256::digest(bytes))).unwrap() + } + + fn stream(bytes: Vec) -> BoxStream<'static, io::Result> { + futures::stream::iter(vec![Ok(Bytes::from(bytes))]).boxed() + } + + async fn collect(mut s: BoxStream<'static, io::Result>) -> Vec { + let mut out = Vec::new(); + while let Some(c) = s.next().await { + out.extend_from_slice(&c.unwrap()); + } + out + } + + fn store(url: &str) -> S3BlockStore { + S3BlockStore::for_testing("blocks", url, Duration::from_secs(10)) + } + + #[tokio::test] + async fn put_size_get_delete_roundtrip() { + let (url, _st) = spawn_mock(false).await; + let s = store(&url); + let body: Vec = (0..200_000u32).map(|i| (i % 251) as u8).collect(); + let id = id_of(&body); + + assert_eq!( + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(), + PutOutcome::Stored + ); + assert_eq!(s.size(&id).await.unwrap(), Some(body.len() as u64)); + assert_eq!(s.backend_name(), "s3"); + assert_eq!( + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(), + PutOutcome::AlreadyPresent + ); + + let got = collect(s.get_range(&id, 1000, 2000).await.unwrap()).await; + assert_eq!(got, body[1000..2000]); + assert!(matches!( + s.get_range(&id, 0, body.len() as u64 + 1) + .await + .map(|_| ()) + .unwrap_err(), + BlockStoreError::OutOfRange | BlockStoreError::Backend(_) + )); + + s.delete(&id).await.unwrap(); + assert_eq!(s.size(&id).await.unwrap(), None); + } + + #[tokio::test] + async fn digest_mismatch_aborts_and_stores_nothing() { + let (url, st) = spawn_mock(false).await; + let s = store(&url); + let id = id_of(b"expected"); + let err = s + .put_verified(&id, stream(b"different".to_vec()), u64::MAX) + .await + .unwrap_err(); + assert!(matches!(err, BlockStoreError::DigestMismatch)); + assert_eq!(s.size(&id).await.unwrap(), None); + // The abort removed the staged parts. + assert!(st.parts.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn over_cap_aborts_while_streaming() { + let (url, _st) = spawn_mock(false).await; + let s = store(&url); + let body = vec![7u8; 4096]; + let id = id_of(&body); + let err = s.put_verified(&id, stream(body), 1024).await.unwrap_err(); + assert!(matches!(err, BlockStoreError::TooLarge(1024))); + assert_eq!(s.size(&id).await.unwrap(), None); + } + + /// A complete request that commits server-side but whose answer is lost + /// must report Unknown, and a later HEAD shows the object is there. The + /// cautious arm exists so a caller never treats a possibly-stored object + /// as definitely absent. + #[tokio::test] + async fn lost_complete_answer_reports_unknown_then_head_resolves() { + let (url, _st) = spawn_mock(true).await; + let s = S3BlockStore::for_testing("blocks", &url, Duration::from_millis(300)); + let body = vec![9u8; 1024]; + let id = id_of(&body); + let err = s + .put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap_err(); + assert!(matches!(err, BlockStoreError::Unknown), "got {err:?}"); + // The write actually committed server-side; a HEAD sees it. + assert_eq!( + store(&url).size(&id).await.unwrap(), + Some(body.len() as u64) + ); + } +} diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 2173aa00..d068d669 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -9,6 +9,7 @@ pub mod api; mod arweave; mod arweave_v2; pub mod auth; +pub mod blockstore; mod bootstrap; mod cert; pub mod config; @@ -402,6 +403,20 @@ pub async fn run() -> Result<()> { None }; + // Content-addressed model block storage. Built only when model hosting is + // enabled; a misconfigured backend is fatal (fail closed, like purge-spam's + // object store), because falling back to local disk would silently move a + // deployment's blocks somewhere they were never meant to live. + let block_store = crate::blockstore::build(&config) + .await + .context("model block storage failed to initialize")?; + if let Some(ref store) = block_store { + info!( + backend = store.backend_name(), + "model block storage enabled" + ); + } + // Advisory-lock connections come from their own pool: a write guard pins one // for its whole lifetime, and sharing the application pool would let a push // burst starve ordinary request handlers. @@ -621,6 +636,7 @@ pub async fn run() -> Result<()> { 200_000, ), git_bin: "git".to_string(), + block_store, }; // One-time re-encryption of any webhook HMAC secrets still resting as diff --git a/crates/twigpine-node/src/state.rs b/crates/twigpine-node/src/state.rs index 9deaef6c..6925d7f3 100644 --- a/crates/twigpine-node/src/state.rs +++ b/crates/twigpine-node/src/state.rs @@ -383,6 +383,9 @@ pub struct AppState { /// process-group teardown in handler tests without mutating the process-global /// PATH (#174). pub git_bin: String, + /// Content-addressed model block store. `None` unless model hosting is + /// enabled, so every read site must handle the flag-off shape. + pub block_store: Option>, } impl AppState { diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 45e03484..21ec3d8d 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -228,6 +228,7 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS 16, ), git_bin: "git".to_string(), + block_store: None, } } diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 15f44283..702f2155 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -156,6 +156,7 @@ fn build_state(db: Arc, pool: PgPool) -> AppState { ), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), + block_store: None, } } From 74209f42d073f2acc7208c6e9f09a876ea6fe516 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:02:54 -0600 Subject: [PATCH 03/53] feat(core): add content-defined chunking and reconstruction format Adds the shared model-block format: FastCDC chunking (8/64/128 KiB) that streams a reader, a packer that seals blocks at the 64 MiB target, and the versioned reconstruction object mapping files to block terms. Dedup reuses terms from prior reconstruction objects by chunk hash, so a fine-tune stores only the chunks that differ. Rebuild verifies every chunk and block hash as it writes. --- Cargo.lock | 13 +- crates/twigpine-core/Cargo.toml | 5 + crates/twigpine-core/src/lib.rs | 1 + crates/twigpine-core/src/model/chunking.rs | 252 +++++++ crates/twigpine-core/src/model/mod.rs | 24 + .../twigpine-core/src/model/reconstruction.rs | 648 ++++++++++++++++++ 6 files changed, 940 insertions(+), 3 deletions(-) create mode 100644 crates/twigpine-core/src/model/chunking.rs create mode 100644 crates/twigpine-core/src/model/mod.rs create mode 100644 crates/twigpine-core/src/model/reconstruction.rs diff --git a/Cargo.lock b/Cargo.lock index f8b87889..4dcc8899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2208,7 +2208,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -2701,7 +2701,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ab67060fc6b8ef687992d439ca0fa36e7ed17e9a0b16b25b601e8757df720de" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] @@ -3141,6 +3141,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "fastcdc" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0431c3132902a1bed6fe77dcfa5d03844e083f263b81288246a2d43dd7d4b2ad" + [[package]] name = "fastrand" version = "2.3.0" @@ -7458,6 +7464,7 @@ dependencies = [ "crypto_box", "curve25519-dalek 4.1.3", "ed25519-dalek 2.2.0", + "fastcdc", "hex", "multibase", "multihash", @@ -7960,7 +7967,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/crates/twigpine-core/Cargo.toml b/crates/twigpine-core/Cargo.toml index 867e9d11..aebd3f53 100644 --- a/crates/twigpine-core/Cargo.toml +++ b/crates/twigpine-core/Cargo.toml @@ -29,6 +29,11 @@ curve25519-dalek = "4" crypto_box = { version = "0.9", features = ["std", "chacha20"] } chacha20poly1305 = "0.10" +# Content-defined chunking (FastCDC, the 2020 algorithm variant) for the +# model-block format. Streaming over a reader, so memory stays proportional +# to the block size rather than the file size. +fastcdc = "5" + [dev-dependencies] tokio = { workspace = true } # Not optional here: the redirect matrix must run under a bare diff --git a/crates/twigpine-core/src/lib.rs b/crates/twigpine-core/src/lib.rs index d53b5ea2..ba0f19b8 100644 --- a/crates/twigpine-core/src/lib.rs +++ b/crates/twigpine-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod identity; pub mod identity_path; pub mod legacy_env; pub mod legacy_headers; +pub mod model; pub mod node_denial; // `url` is the one dependency here that drags a tail (idna, then the icu // crates), and twigpine-core is allowlisted to stay embeddable. Every client that diff --git a/crates/twigpine-core/src/model/chunking.rs b/crates/twigpine-core/src/model/chunking.rs new file mode 100644 index 00000000..dd517721 --- /dev/null +++ b/crates/twigpine-core/src/model/chunking.rs @@ -0,0 +1,252 @@ +//! Content-defined chunking and block packing. +//! +//! Chunking uses FastCDC (the 2020 algorithm variant) at 8 / 64 / 128 KiB +//! min / avg / max. The packer seals a block once the accumulated chunks +//! reach the 64 MiB target; since a chunk is at most 128 KiB, a sealed block +//! can never approach the 128 MiB hard cap, which exists to bound block size +//! if the chunk parameters ever change. + +use std::io::Read; + +use fastcdc::v2020::StreamCDC; + +use super::sha256_hex; + +pub const CHUNK_MIN: usize = 8 * 1024; +pub const CHUNK_AVG: usize = 64 * 1024; +pub const CHUNK_MAX: usize = 128 * 1024; +pub const BLOCK_TARGET: usize = 64 * 1024 * 1024; +pub const BLOCK_CAP: usize = 128 * 1024 * 1024; + +/// One content-defined chunk of a file. `data` is present while packing; the +/// id is the chunk's sha256, which is how the chunk dedups across files and +/// releases. +#[derive(Debug)] +pub struct Chunk { + pub sha256: String, + pub len: usize, + pub offset: u64, + pub data: Vec, +} + +/// A sealed block: a run of chunks and its content id. +#[derive(Debug)] +pub struct Block { + pub sha256: String, + pub chunks: Vec, + pub data: Vec, +} + +/// 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| { + let c = r?; + Ok(Chunk { + sha256: sha256_hex(&c.data), + len: c.data.len(), + offset: c.offset, + data: c.data, + }) + }) +} + +/// Pack the chunk stream into sealed blocks. Each yielded `Block` is a run of +/// chunks of at least `BLOCK_TARGET` bytes unless it is the tail of the +/// stream or the run was cut short to keep a block under the cap. Memory is +/// bounded by the block size. +pub struct BlockPacker>> { + chunks: I, + pending: Vec, + pending_bytes: usize, + done: bool, +} + +impl>> BlockPacker { + pub fn new(chunks: I) -> Self { + Self { + chunks, + pending: Vec::new(), + pending_bytes: 0, + done: false, + } + } + + /// Seal `pending` into a block when it holds anything. The caller owns the + /// returned chunks' data; a block's `data` is its bytes. + fn seal(&mut self) -> Option> { + if self.pending.is_empty() { + return None; + } + let chunks = std::mem::take(&mut self.pending); + self.pending_bytes = 0; + let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum()); + for c in &chunks { + data.extend_from_slice(&c.data); + } + Some(Ok(Block { + sha256: sha256_hex(&data), + chunks, + data, + })) + } +} + +impl>> Iterator for BlockPacker { + type Item = std::io::Result; + + fn next(&mut self) -> Option { + if self.done { + return None; + } + loop { + match self.chunks.next() { + Some(Ok(chunk)) => { + // A single chunk may exceed the target; it still joins the + // block under construction, and the cap check below is the + // only hard stop. Sealing before adding keeps any block at + // target + one chunk at most. + if self.pending_bytes >= BLOCK_TARGET + || self.pending_bytes + chunk.len > BLOCK_CAP + { + let sealed = self.seal(); + self.pending.push(chunk); + self.pending_bytes += self.pending.last().map(|c| c.len).unwrap_or(0); + return sealed; + } + self.pending_bytes += chunk.len; + self.pending.push(chunk); + } + Some(Err(e)) => { + self.done = true; + return Some(Err(e)); + } + None => { + self.done = true; + return self.seal(); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + /// Deterministic pseudo-random bytes: rand is a dependency of this crate + /// but a fixed-pattern generator makes the tests reproducible without a + /// seed constant. + fn gen_bytes(n: usize) -> Vec { + let mut v = Vec::with_capacity(n); + let mut x: u64 = 0x9e3779b97f4a7c15; + while v.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + v.extend_from_slice(&x.to_le_bytes()); + } + v.truncate(n); + v + } + + fn chunk_all(bytes: &[u8]) -> Vec { + chunk_reader(Cursor::new(bytes.to_vec())) + .collect::>() + .unwrap() + } + + #[test] + fn chunking_is_deterministic() { + let bytes = gen_bytes(3 * 1024 * 1024); + let a = chunk_all(&bytes); + let b = chunk_all(&bytes); + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b.iter()) { + assert_eq!(x.sha256, y.sha256); + assert_eq!(x.len, y.len); + assert_eq!(x.offset, y.offset); + } + } + + #[test] + fn chunk_sizes_stay_within_bounds() { + let bytes = gen_bytes(10 * 1024 * 1024); + let chunks = chunk_all(&bytes); + assert!(chunks.len() > 10); + for (i, c) in chunks.iter().enumerate() { + assert!(c.len <= CHUNK_MAX, "chunk {i} exceeds max"); + if i + 1 < chunks.len() { + // The final chunk may end before the min when the input runs out. + assert!(c.len >= CHUNK_MIN, "chunk {i} below min"); + } + } + } + + #[test] + fn a_small_edit_changes_only_early_chunks() { + let base = gen_bytes(20 * 1024 * 1024); + let mut edited = vec![0u8; 100]; + edited.extend_from_slice(&base); + + let base_ids: Vec = chunk_all(&base).iter().map(|c| c.sha256.clone()).collect(); + let edited_ids: Vec = chunk_all(&edited) + .iter() + .map(|c| c.sha256.clone()) + .collect(); + + let base_set: std::collections::HashSet<&String> = base_ids.iter().collect(); + let changed = edited_ids + .iter() + .filter(|id| !base_set.contains(id)) + .count(); + // 100 inserted bytes move the first few boundaries; the vast majority + // of a 20 MiB file still chunks identically. + assert!( + changed <= 4, + "{changed} changed chunks for a 100-byte prefix insert" + ); + } + + #[test] + fn packing_round_trips_bytes() { + // Small enough to exercise seals without a huge test file: multiple + // blocks only form past 64 MiB, so here we check boundary accounting + // on a tail block and byte identity end to end. + let bytes = gen_bytes(2 * 1024 * 1024 + 7); + let blocks: Vec = BlockPacker::new(chunk_reader(Cursor::new(bytes.clone()))) + .collect::>() + .unwrap(); + assert_eq!(blocks.len(), 1, "under-target input seals to a tail block"); + let reassembled: Vec = blocks + .iter() + .flat_map(|b| b.chunks.iter().flat_map(|c| c.data.clone())) + .collect(); + assert_eq!(reassembled, bytes); + assert_eq!(blocks[0].sha256, sha256_hex(&bytes)); + } + + #[test] + fn chunk_data_never_buffers_the_file() { + // The contract this format depends on: a reader is consumed a chunk + // at a time. Guard it by chunking a reader that would panic if read + // past its claimed end before the iterator asks for more. + struct Stingy { + left: usize, + } + impl Read for Stingy { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = buf.len().min(self.left); + self.left -= n; + buf[..n].fill(1); + Ok(n) + } + } + let mut it = chunk_reader(Stingy { + left: 3 * CHUNK_MAX, + }); + let first = it.next().unwrap().unwrap(); + assert!(first.len <= CHUNK_MAX); + } +} diff --git a/crates/twigpine-core/src/model/mod.rs b/crates/twigpine-core/src/model/mod.rs new file mode 100644 index 00000000..f8dd1cc8 --- /dev/null +++ b/crates/twigpine-core/src/model/mod.rs @@ -0,0 +1,24 @@ +//! Model hosting formats shared by the node and the CLI: content-defined +//! chunking, block packing, the reconstruction object, and the signed +//! release manifest. +//! +//! Files are split by content, not by size: chunk boundaries land where the +//! bytes say they land, so appending or editing part of a weight file leaves +//! every other chunk identical. Chunks are the dedup unit; blocks (sequences +//! of chunks sealed near a target size) are the storage unit. Both are named +//! by the sha256 of their bytes, computed by whoever holds them and +//! recomputed by the node on receipt. + +pub mod chunking; +pub mod reconstruction; + +/// The schema tag carried by the reconstruction object defined here. Unknown +/// tags are rejected on parse so a reader never silently misreads a later +/// format. +pub const RECONSTRUCTION_SCHEMA_V1: &str = "gitlawb/model-reconstruction/v1"; + +/// Lowercase hex sha256 of some bytes. +pub fn sha256_hex(bytes: &[u8]) -> String { + use sha2::Digest; + hex::encode(sha2::Sha256::digest(bytes)) +} diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs new file mode 100644 index 00000000..e66d39a8 --- /dev/null +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -0,0 +1,648 @@ +//! The reconstruction object: versioned JSON mapping each chunk-stored file +//! to the block terms that rebuild it. +//! +//! A term names a block by its sha256 and a half-open range of that block's +//! chunk list; a file is its terms in order. Each block's own entry lists +//! every chunk's sha256 and length, so byte offsets inside a block are prefix +//! sums and the format carries no redundant offset column. +//! +//! The schema string is part of the signed surface: a reader rejects a tag it +//! does not know rather than guessing at a later layout. + +use std::collections::HashMap; +use std::io::{Read, Write}; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::chunking::{chunk_reader, Block, BLOCK_TARGET}; +use super::{sha256_hex, RECONSTRUCTION_SCHEMA_V1}; + +#[derive(Debug, Error)] +pub enum ModelError { + #[error("unsupported reconstruction schema {0:?}")] + UnknownSchema(String), + #[error("invalid reconstruction: {0}")] + Invalid(String), + #[error("hash mismatch: {0}")] + HashMismatch(String), + #[error("i/o error: {0}")] + Io(#[from] std::io::Error), + #[error("json error: {0}")] + Json(#[from] serde_json::Error), +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Term { + /// sha256 of the block this term reads from. + pub block: String, + /// Half-open index range into that block's `chunks` list. + pub chunk_start: u32, + pub chunk_end: u32, + /// File bytes this term contributes: the sum of its chunks' lengths. + pub length: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct FileEntry { + pub path: String, + pub size: u64, + pub sha256: String, + pub terms: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ChunkMeta { + pub sha256: String, + pub len: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct BlockEntry { + pub sha256: String, + pub size: u64, + pub chunks: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Reconstruction { + pub schema: String, + pub files: Vec, + pub blocks: Vec, +} + +impl Reconstruction { + pub fn new() -> Self { + Self { + schema: RECONSTRUCTION_SCHEMA_V1.to_string(), + files: Vec::new(), + blocks: Vec::new(), + } + } + + /// Parse and validate a stored object. Unknown schema tags are refused: + /// misreading a later layout silently is worse than failing. + pub fn parse(bytes: &[u8]) -> Result { + let this: Reconstruction = serde_json::from_slice(bytes)?; + if this.schema != RECONSTRUCTION_SCHEMA_V1 { + return Err(ModelError::UnknownSchema(this.schema)); + } + this.validate()?; + Ok(this) + } + + pub fn to_bytes(&self) -> Result, ModelError> { + Ok(serde_json::to_vec(self)?) + } + + /// Structural sanity: terms index real blocks, chunk ranges are ordered, + /// and each file's terms sum to its declared size. + pub fn validate(&self) -> Result<(), ModelError> { + let blocks: HashMap<&str, &BlockEntry> = + self.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect(); + for file in &self.files { + let mut total = 0u64; + for term in &file.terms { + if term.chunk_start >= term.chunk_end { + return Err(ModelError::Invalid(format!( + "{}: empty chunk range in term for block {}", + file.path, term.block + ))); + } + let block = blocks.get(term.block.as_str()).ok_or_else(|| { + ModelError::Invalid(format!( + "{}: term names unknown block {}", + file.path, term.block + )) + })?; + if term.chunk_end as usize > block.chunks.len() { + return Err(ModelError::Invalid(format!( + "{}: chunk range {}..{} exceeds block {} with {} chunks", + file.path, + term.chunk_start, + term.chunk_end, + term.block, + block.chunks.len() + ))); + } + let span: u64 = block.chunks[term.chunk_start as usize..term.chunk_end as usize] + .iter() + .map(|c| c.len) + .sum(); + if span != term.length { + return Err(ModelError::Invalid(format!( + "{}: term length {span} != declared {}", + file.path, term.length + ))); + } + total += term.length; + } + if total != file.size { + return Err(ModelError::Invalid(format!( + "{}: terms cover {total} bytes, file declares {}", + file.path, file.size + ))); + } + } + Ok(()) + } + + fn block_index(&self) -> HashMap<&str, &BlockEntry> { + self.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect() + } +} + +impl Default for Reconstruction { + fn default() -> Self { + Self::new() + } +} + +/// 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)] +pub struct DedupIndex { + /// chunk sha256 -> (block sha256, chunk index inside that block) + by_chunk: HashMap, +} + +impl DedupIndex { + pub fn new() -> Self { + Self::default() + } + + pub fn from_reconstructions(priors: &[&Reconstruction]) -> Self { + let mut idx = Self::new(); + for rec in priors { + idx.add(rec); + } + idx + } + + pub fn add(&mut self, rec: &Reconstruction) { + for block in &rec.blocks { + for (i, chunk) in block.chunks.iter().enumerate() { + // First writer wins: two priors carrying the same chunk are + // interchangeable, so keep the earliest. + idx_insert( + &mut self.by_chunk, + chunk.sha256.clone(), + (block.sha256.clone(), i as u32), + ); + } + } + } +} + +fn idx_insert(map: &mut HashMap, k: String, v: (String, u32)) { + map.entry(k).or_insert(v); +} + +/// Seal a staged run of new chunks into one block and append its term and +/// block-table entry. +fn seal_staged( + staged: &mut Vec, + terms: &mut Vec, + block_entries: &mut Vec, + new_blocks: &mut Vec, +) { + if staged.is_empty() { + return; + } + let chunks = std::mem::take(staged); + let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum::()); + for c in &chunks { + data.extend_from_slice(&c.data); + } + let block = Block { + sha256: sha256_hex(&data), + chunks, + data, + }; + terms.push(Term { + block: block.sha256.clone(), + chunk_start: 0, + chunk_end: block.chunks.len() as u32, + length: block.data.len() as u64, + }); + block_entries.push(BlockEntry { + sha256: block.sha256.clone(), + size: block.data.len() as u64, + chunks: block + .chunks + .iter() + .map(|c| ChunkMeta { + sha256: c.sha256.clone(), + len: c.len as u64, + }) + .collect(), + }); + new_blocks.push(block); +} + +/// What `pack_file` produced: the file's entry, the new blocks to store and +/// upload, and the block entries the reconstruction object must carry. +pub struct PackedFile { + pub file: FileEntry, + pub new_blocks: Vec, + pub block_entries: Vec, +} + +/// Chunk and pack one file, reusing terms for chunks a prior reconstruction +/// already holds (`dedup`). `path` is the repo-relative path recorded in the +/// entry. +pub fn pack_file( + path: &str, + reader: R, + dedup: &DedupIndex, +) -> std::io::Result { + let mut file_hasher = sha2::Sha256::new(); + use sha2::Digest; + + let mut terms: Vec = Vec::new(); + let mut new_blocks: Vec = Vec::new(); + let mut block_entries: Vec = Vec::new(); + // Chunks not found in `dedup`, staged until the staging run seals into a + // block (at the target size, on a reused-chunk boundary, or at EOF). + let mut staged: Vec = Vec::new(); + let mut staged_bytes: usize = 0; + let mut file_size: u64 = 0; + + for chunk in chunk_reader(reader) { + let chunk = chunk?; + file_hasher.update(&chunk.data); + file_size += chunk.len as u64; + if let Some((block_sha, idx)) = dedup.by_chunk.get(&chunk.sha256) { + seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); + // Extend the previous term when it already reads the chunk before + // this one in the same block: a shared run stays a single term. + match terms.last_mut() { + Some(t) if t.block == *block_sha && t.chunk_end == *idx => { + t.chunk_end = idx + 1; + t.length += chunk.len as u64; + } + _ => terms.push(Term { + block: block_sha.clone(), + chunk_start: *idx, + chunk_end: idx + 1, + length: chunk.len as u64, + }), + } + } else { + staged_bytes += chunk.len; + staged.push(chunk); + if staged_bytes >= BLOCK_TARGET { + seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); + } + } + } + seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); + + let file = FileEntry { + path: path.to_string(), + size: file_size, + sha256: hex::encode(file_hasher.finalize()), + terms, + }; + Ok(PackedFile { + file, + new_blocks, + block_entries, + }) +} + +/// Byte-range mapping: which slices of which blocks serve file bytes +/// `[start, end_exclusive)`. Each slice is a contiguous run of whole or +/// clipped chunks inside one block. +#[derive(Debug, PartialEq, Eq)] +pub struct BlockSlice { + pub block: String, + /// Byte offset of the slice inside the block's chunk bytes. + pub offset: u64, + pub len: u64, +} + +pub fn map_file_range( + file: &FileEntry, + rec: &Reconstruction, + start: u64, + end_exclusive: u64, +) -> Result, ModelError> { + if start > end_exclusive || end_exclusive > file.size { + return Err(ModelError::Invalid(format!( + "range {start}..{end_exclusive} outside {} bytes of {}", + file.size, file.path + ))); + } + let blocks = rec.block_index(); + let mut out: Vec = Vec::new(); + let mut cursor = 0u64; + for term in &file.terms { + let block = blocks + .get(term.block.as_str()) + .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; + let term_end = cursor + term.length; + if term_end <= start || cursor >= end_exclusive { + cursor = term_end; + continue; + } + // Byte offset of each chunk inside the block, as a prefix sum. + let mut block_off = 0u64; + for (i, chunk) in block.chunks.iter().enumerate() { + block_off += chunk.len; + if i < term.chunk_start as usize { + continue; + } + if i >= term.chunk_end as usize { + break; + } + // This chunk covers file bytes [chunk_lo, chunk_hi). + let chunk_hi = cursor + chunk.len; + let chunk_lo = cursor; + cursor = chunk_hi; + let s = start.max(chunk_lo); + let e = end_exclusive.min(chunk_hi); + if s < e { + let off = block_off - chunk.len + (s - chunk_lo); + match out.last_mut() { + // Adjacent slices in the same block merge into one read. + Some(slice) if slice.block == term.block && slice.offset + slice.len == off => { + let slice: &mut BlockSlice = slice; + slice.len += e - s; + } + _ => out.push(BlockSlice { + block: term.block.clone(), + offset: off, + len: e - s, + }), + } + } + } + cursor = term_end; + } + Ok(out) +} + +/// Rebuild a file's bytes from its terms, verifying every chunk's hash and +/// the whole-file digest. `fetch` returns a block's bytes by id (a +/// BlockStore range read or a cache hit on the caller's side). +pub fn rebuild_file( + file: &FileEntry, + rec: &Reconstruction, + fetch: &mut dyn FnMut(&str) -> std::io::Result>, + out: &mut W, +) -> Result { + use sha2::Digest; + let blocks = rec.block_index(); + let mut file_hasher = sha2::Sha256::new(); + let mut written = 0u64; + for term in &file.terms { + let block = blocks + .get(term.block.as_str()) + .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; + let bytes = fetch(&term.block)?; + if sha256_hex(&bytes) != term.block { + return Err(ModelError::HashMismatch(format!( + "block {} content does not hash to its id", + term.block + ))); + } + let mut off = 0usize; + for (i, chunk) in block.chunks.iter().enumerate() { + let next = off + chunk.len as usize; + if i >= term.chunk_start as usize && i < term.chunk_end as usize { + let data = bytes.get(off..next).ok_or_else(|| { + ModelError::Invalid(format!( + "block {} shorter than its chunk table", + term.block + )) + })?; + if sha256_hex(data) != chunk.sha256 { + return Err(ModelError::HashMismatch(format!( + "chunk {} in block {}", + chunk.sha256, term.block + ))); + } + out.write_all(data)?; + file_hasher.update(data); + written += chunk.len; + } + off = next; + } + } + if written != file.size { + return Err(ModelError::Invalid(format!( + "{}: rebuilt {written} bytes, declared {}", + file.path, file.size + ))); + } + let digest = hex::encode(file_hasher.finalize()); + if digest != file.sha256 { + return Err(ModelError::HashMismatch(format!( + "{}: rebuilt bytes do not hash to the manifest id", + file.path + ))); + } + Ok(written) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn gen_bytes(n: usize, seed: u64) -> Vec { + let mut v = Vec::with_capacity(n); + let mut x = seed; + while v.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + v.extend_from_slice(&x.to_le_bytes()); + } + v.truncate(n); + v + } + + fn pack(path: &str, bytes: &[u8]) -> (Reconstruction, PackedFile) { + let dedup = DedupIndex::new(); + let packed = pack_file(path, Cursor::new(bytes.to_vec()), &dedup).unwrap(); + let mut rec = Reconstruction::new(); + rec.files.push(packed.file.clone()); + rec.blocks.extend(packed.block_entries.clone()); + (rec, packed) + } + + #[test] + fn pack_then_rebuild_is_byte_identical() { + let bytes = gen_bytes(3 * 1024 * 1024 + 13, 7); + let (rec, packed) = pack("model.safetensors", &bytes); + rec.validate().unwrap(); + let store: HashMap> = packed + .new_blocks + .iter() + .map(|b| (b.sha256.clone(), b.data.clone())) + .collect(); + let mut out = Vec::new(); + let n = rebuild_file( + &packed.file, + &rec, + &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut out, + ) + .unwrap(); + assert_eq!(n as usize, bytes.len()); + assert_eq!(out, bytes); + } + + #[test] + fn reconstruction_round_trips_json_and_rejects_unknown_schema() { + let bytes = gen_bytes(600_000, 11); + let (rec, _) = pack("weights.bin", &bytes); + let parsed = Reconstruction::parse(&rec.to_bytes().unwrap()).unwrap(); + assert_eq!(parsed, rec); + + let mut bad = rec.clone(); + bad.schema = "gitlawb/model-reconstruction/v99".to_string(); + assert!(matches!( + Reconstruction::parse(&bad.to_bytes().unwrap()), + Err(ModelError::UnknownSchema(_)) + )); + } + + #[test] + fn dedup_reuses_prior_chunks_without_new_blocks() { + // A fine-tune sharing most of the base's bytes: only the changed + // chunks seal into new blocks, the rest become terms into the prior + // reconstruction's blocks. + let base = gen_bytes(4 * 1024 * 1024, 23); + let (base_rec, base_packed) = pack("base.safetensors", &base); + assert_eq!(base_packed.new_blocks.len(), 1); + + let mut tuned = base.clone(); + // Overwrite a 300 KiB region in the middle: FastCDC boundaries + // resync within a few chunks. + for b in tuned.iter_mut().skip(2 * 1024 * 1024).take(300 * 1024) { + *b = b.wrapping_add(1); + } + + let dedup = DedupIndex::from_reconstructions(&[&base_rec]); + let packed = pack_file("tuned.safetensors", Cursor::new(tuned.clone()), &dedup).unwrap(); + let mut rec = Reconstruction::new(); + // The block table carries prior blocks too: terms point at them, so + // the object must list them for offsets to resolve. + rec.blocks.extend(base_rec.blocks.iter().cloned()); + rec.blocks.extend(packed.block_entries.clone()); + rec.files.push(packed.file.clone()); + rec.validate().unwrap(); + + let reused_chunks: usize = packed + .file + .terms + .iter() + .filter(|t| t.block == base_rec.blocks[0].sha256) + .map(|t| (t.chunk_end - t.chunk_start) as usize) + .sum(); + let total_chunks: usize = packed + .file + .terms + .iter() + .map(|t| (t.chunk_end - t.chunk_start) as usize) + .sum(); + assert!( + reused_chunks * 10 >= total_chunks * 8, + "expected most chunks reused, got {reused_chunks}/{total_chunks}" + ); + assert!( + packed.new_blocks.len() <= 1, + "changed chunks should seal into at most one new block" + ); + + let store: HashMap> = base_packed + .new_blocks + .iter() + .chain(packed.new_blocks.iter()) + .map(|b| (b.sha256.clone(), b.data.clone())) + .collect(); + let mut out = Vec::new(); + rebuild_file( + &packed.file, + &rec, + &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut out, + ) + .unwrap(); + assert_eq!(out, tuned); + } + + #[test] + fn range_mapping_hits_the_middle_of_a_block() { + // Build a 10-chunk block synthetically so the middle-subrange case is + // exact, not dependent on where FastCDC happens to cut. + let chunk_bytes: Vec> = (0..10) + .map(|i| gen_bytes(100 + i * 10, i as u64 + 1)) + .collect(); + let chunks: Vec = chunk_bytes + .iter() + .map(|c| ChunkMeta { + sha256: sha256_hex(c), + len: c.len() as u64, + }) + .collect(); + let block_data: Vec = chunk_bytes.concat(); + let block_sha = sha256_hex(&block_data); + // A file whose whole content is one term referencing chunks 3..6 of + // a 10-chunk block: the shape dedup produces when a prior release + // already stored the surrounding chunks. + let term_len: u64 = chunks[3..6].iter().map(|c| c.len).sum(); + let prefix: u64 = chunks[..3].iter().map(|c| c.len).sum(); + let file_bytes: Vec = chunk_bytes[3..6].concat(); + let file = FileEntry { + path: "f".into(), + size: term_len, + sha256: sha256_hex(&file_bytes), + terms: vec![Term { + block: block_sha.clone(), + chunk_start: 3, + chunk_end: 6, + length: term_len, + }], + }; + let rec = Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.into(), + files: vec![file.clone()], + blocks: vec![BlockEntry { + sha256: block_sha.clone(), + size: block_data.len() as u64, + chunks, + }], + }; + rec.validate().unwrap(); + + // A middle range of the file maps to the middle of the block: the + // slice offset includes the prefix sum of chunks 0..3 that the term + // skips. + let want = file.size - 10; + let slices = map_file_range(&file, &rec, 10, want).unwrap(); + let served: u64 = slices.iter().map(|s| s.len).sum(); + assert_eq!(served, want - 10); + assert_eq!(slices[0].offset, prefix + 10); + // And the served bytes equal the file bytes. + let mut got = Vec::new(); + for s in &slices { + got.extend_from_slice(&block_data[s.offset as usize..(s.offset + s.len) as usize]); + } + assert_eq!(got, file_bytes[10..want as usize]); + } + + #[test] + fn rebuild_rejects_a_corrupt_block() { + let bytes = gen_bytes(300_000, 31); + let (rec, packed) = pack("f", &bytes); + let mut out = Vec::new(); + let err = + rebuild_file(&packed.file, &rec, &mut |_id| Ok(vec![0u8; 16]), &mut out).unwrap_err(); + assert!(matches!(err, ModelError::HashMismatch(_))); + } +} From 1ba7e05cb2c67ad15476bfbf78aed8ace8b5b848 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:03:57 -0600 Subject: [PATCH 04/53] feat(core): add signed model release manifest format Adds gitlawb/model-release/v1: the manifest a release commit carries, its detached Ed25519 signature over a domain tag plus the exact manifest bytes, format detection (safetensors, GGUF, pickle, text, other), and verification anchored on a caller-supplied DID so a forged manifest naming another publisher fails. A frozen v1 fixture guards the format against silent change. --- crates/twigpine-core/src/model/manifest.rs | 402 ++++++++++++++++++ crates/twigpine-core/src/model/mod.rs | 1 + .../fixtures/model-release-v1/manifest.json | 1 + .../fixtures/model-release-v1/manifest.sig | 1 + .../fixtures/model-release-v1/publisher.did | 1 + 5 files changed, 406 insertions(+) create mode 100644 crates/twigpine-core/src/model/manifest.rs create mode 100644 crates/twigpine-core/tests/fixtures/model-release-v1/manifest.json create mode 100644 crates/twigpine-core/tests/fixtures/model-release-v1/manifest.sig create mode 100644 crates/twigpine-core/tests/fixtures/model-release-v1/publisher.did diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs new file mode 100644 index 00000000..ce9f9202 --- /dev/null +++ b/crates/twigpine-core/src/model/manifest.rs @@ -0,0 +1,402 @@ +//! The signed model release manifest (`gitlawb/model-release/v1`). +//! +//! A release is a git commit carrying `.twigpine/model-release.json` (these +//! bytes) and `.twigpine/model-release.sig` (a detached Ed25519 signature). +//! The signature covers the domain tag `gitlawb-model-release-sig/v1\n` +//! followed by the exact manifest bytes: no canonicalization, so a signer and +//! a verifier can never drift over JSON re-serialization, and the version tag +//! lives inside the signed bytes the way the ref cert's does. +//! +//! Verification anchors on a DID the caller supplies, never the manifest's +//! `publisher_did` field: a key read from inside the artifact only proves +//! self-consistency, and anyone can mint a keypair and name its DID. The +//! manifest's field is still checked for equality so a manifest naming one +//! publisher cannot pass for another. + +use std::fmt; +use std::str::FromStr; + +use ed25519_dalek::{Signature, Signer, SigningKey}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::did::Did; + +pub const MANIFEST_SCHEMA_V1: &str = "gitlawb/model-release/v1"; + +/// Domain separation tag prepended to the manifest bytes before signing, so +/// a release signature cannot be replayed as a signature over the same bytes +/// in some other protocol. +pub const SIGNING_DOMAIN: &[u8] = b"gitlawb-model-release-sig/v1\n"; + +/// The exact bytes a publisher signs: the domain tag, then the manifest +/// bytes verbatim. +pub fn signing_input(manifest_bytes: &[u8]) -> Vec { + let mut v = Vec::with_capacity(SIGNING_DOMAIN.len() + manifest_bytes.len()); + v.extend_from_slice(SIGNING_DOMAIN); + v.extend_from_slice(manifest_bytes); + v +} + +#[derive(Debug, Error)] +pub enum ManifestError { + #[error("unsupported manifest schema {0:?}")] + UnknownSchema(String), + #[error("manifest names publisher {found}, expected {expected}")] + PublisherMismatch { expected: String, found: String }, + #[error("invalid publisher DID: {0}")] + Did(String), + #[error("invalid signature encoding: {0}")] + SignatureEncoding(String), + #[error("signature does not verify against the expected publisher")] + BadSignature, + #[error("json error: {0}")] + Json(#[from] serde_json::Error), +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum FileFormat { + Safetensors, + Gguf, + Pickle, + Text, + Other, +} + +impl fmt::Display for FileFormat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let s = match self { + FileFormat::Safetensors => "safetensors", + FileFormat::Gguf => "gguf", + FileFormat::Pickle => "pickle", + FileFormat::Text => "text", + FileFormat::Other => "other", + }; + f.write_str(s) + } +} + +/// Where a manifest-listed file's bytes live. Files under the chunking +/// threshold stay ordinary git blobs; larger ones are reconstructed from +/// content blocks. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum StorageKind { + Git, + Chunked, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ManifestFile { + pub path: String, + pub size: u64, + pub sha256: String, + pub format: FileFormat, + pub storage: StorageKind, +} + +/// A publisher's claimed parent release. The node records and displays it; +/// it does not prove the weights derive from the parent. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ParentRef { + pub repo: String, + pub commit: String, + pub manifest_sha256: String, +} + +/// Pointer at the reconstruction object (itself stored as a content block). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ReconstructionRef { + pub sha256: String, + pub size: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Manifest { + pub schema: String, + /// `"owner/name"` on the node. + pub repo: String, + pub publisher_did: String, + pub license: String, + #[serde(default)] + pub parent: Option, + pub files: Vec, + #[serde(default)] + pub reconstruction: Option, +} + +impl Manifest { + pub fn to_bytes(&self) -> Result, ManifestError> { + Ok(serde_json::to_vec(self)?) + } + + /// Parse only the schema tag, for version dispatch. A manifest whose tag + /// is unknown is refused before any field is trusted. + pub fn parse(bytes: &[u8]) -> Result { + #[derive(Deserialize)] + struct Tag { + schema: String, + } + let tag: Tag = serde_json::from_slice(bytes)?; + match tag.schema.as_str() { + MANIFEST_SCHEMA_V1 => Ok(serde_json::from_slice(bytes)?), + other => Err(ManifestError::UnknownSchema(other.to_string())), + } + } +} + +/// Sign `manifest_bytes` (already serialized) and return the detached +/// signature as base64 standard, no trailing newline: the exact contents of +/// the `.sig` file. +pub fn sign(key: &SigningKey, manifest_bytes: &[u8]) -> String { + use base64::{engine::general_purpose::STANDARD, Engine}; + let sig = key.sign(&signing_input(manifest_bytes)); + STANDARD.encode(sig.to_bytes()) +} + +/// Verify `sig_text` (the `.sig` file's contents) over `manifest_bytes` +/// against `expected_did`, a DID the caller resolved from outside the +/// manifest. Fails when the manifest names a different publisher, when the +/// schema version is unknown, and when the signature does not verify. +/// Returns the parsed manifest on success. +pub fn verify( + manifest_bytes: &[u8], + sig_text: &str, + expected_did: &Did, +) -> Result { + let manifest = Manifest::parse(manifest_bytes)?; + if manifest.publisher_did != expected_did.to_string() { + return Err(ManifestError::PublisherMismatch { + expected: expected_did.to_string(), + found: manifest.publisher_did, + }); + } + let publisher = + Did::from_str(&manifest.publisher_did).map_err(|e| ManifestError::Did(e.to_string()))?; + let key = publisher + .to_verifying_key() + .map_err(|e| ManifestError::Did(e.to_string()))?; + + use base64::{engine::general_purpose::STANDARD, Engine}; + let sig_bytes = STANDARD + .decode(sig_text.trim()) + .map_err(|e| ManifestError::SignatureEncoding(e.to_string()))?; + let sig_array: [u8; 64] = sig_bytes + .try_into() + .map_err(|_| ManifestError::SignatureEncoding("signature must be 64 bytes".into()))?; + let sig = Signature::from_bytes(&sig_array); + // Strict verification, the same posture the attestation verifier takes. + key.verify_strict(&signing_input(manifest_bytes), &sig) + .map_err(|_| ManifestError::BadSignature)?; + Ok(manifest) +} + +/// Classify a file's format from its leading bytes and path. Honest +/// detection, not a security gate: pickle is flagged so consumers can be +/// warned, never refused. +pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { + if first_bytes.starts_with(b"GGUF") { + return FileFormat::Gguf; + } + // Raw pickle: the protocol opcode 0x80 followed by the version byte. + if first_bytes.len() >= 2 && first_bytes[0] == 0x80 && (2..=5).contains(&first_bytes[1]) { + return FileFormat::Pickle; + } + let lower = path.to_ascii_lowercase(); + let ext = lower.rsplit('.').next().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; + } + // safetensors: an 8-byte little-endian header length followed by '{'. + if first_bytes.len() >= 9 + && u64::from_le_bytes(first_bytes[..8].try_into().unwrap()) > 0 + && first_bytes[8] == b'{' + { + return FileFormat::Safetensors; + } + if matches!( + ext, + "json" | "txt" | "md" | "py" | "jinja" | "model" | "yaml" | "yml" + ) { + return FileFormat::Text; + } + FileFormat::Other +} + +#[cfg(test)] +mod tests { + use super::*; + + fn keypair(seed: u8) -> (SigningKey, Did) { + let key = SigningKey::from_bytes(&[seed; 32]); + let did = Did::from_verifying_key(&key.verifying_key()); + (key, did) + } + + fn sample_manifest(did: &Did) -> Manifest { + Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "alice/llm".to_string(), + publisher_did: did.to_string(), + license: "apache-2.0".to_string(), + parent: None, + files: vec![ + ManifestFile { + path: "model.safetensors".into(), + size: 1024, + sha256: "a".repeat(64), + format: FileFormat::Safetensors, + storage: StorageKind::Chunked, + }, + ManifestFile { + path: "config.json".into(), + size: 256, + sha256: "b".repeat(64), + format: FileFormat::Text, + storage: StorageKind::Git, + }, + ], + reconstruction: Some(ReconstructionRef { + sha256: "c".repeat(64), + size: 512, + }), + } + } + + #[test] + fn a_manifest_signed_by_the_owner_verifies() { + let (key, did) = keypair(1); + let bytes = sample_manifest(&did).to_bytes().unwrap(); + let sig = sign(&key, &bytes); + let parsed = verify(&bytes, &sig, &did).unwrap(); + assert_eq!(parsed.publisher_did, did.to_string()); + assert_eq!(parsed.files.len(), 2); + } + + #[test] + fn a_manifest_naming_another_publisher_fails() { + // Signed by key Y but naming DID X. Verification takes the + // expected DID from the caller, so naming X does not help Y's key. + let (key_y, _did_y) = keypair(2); + let (_key_x, did_x) = keypair(3); + let mut manifest = sample_manifest(&did_x); + manifest.publisher_did = did_x.to_string(); + let bytes = manifest.to_bytes().unwrap(); + let sig = sign(&key_y, &bytes); + // Verified against X's DID: publisher matches, but Y's signature + // does not. + assert!(matches!( + verify(&bytes, &sig, &did_x), + Err(ManifestError::BadSignature) + )); + // Verified against the signer Y: the named publisher X mismatches. + let did_y = Did::from_verifying_key(&key_y.verifying_key()); + assert!(matches!( + verify(&bytes, &sig, &did_y), + Err(ManifestError::PublisherMismatch { .. }) + )); + } + + #[test] + fn a_forged_fully_populated_manifest_fails() { + // A well-formed manifest naming the real owner but signed by a fresh + // keypair must fail: the field is data, not the verifying key. + let (_owner_key, owner_did) = keypair(4); + let (forger, _forger_did) = keypair(5); + let bytes = sample_manifest(&owner_did).to_bytes().unwrap(); + let sig = sign(&forger, &bytes); + assert!(matches!( + verify(&bytes, &sig, &owner_did), + Err(ManifestError::BadSignature) + )); + } + + #[test] + fn one_changed_byte_invalidates_the_signature() { + let (key, did) = keypair(6); + let mut bytes = sample_manifest(&did).to_bytes().unwrap(); + let sig = sign(&key, &bytes); + bytes[10] ^= 1; + assert!(verify(&bytes, &sig, &did).is_err()); + } + + #[test] + fn unknown_schema_is_rejected_before_signature_work() { + let (key, did) = keypair(7); + let mut manifest = sample_manifest(&did); + manifest.schema = "gitlawb/model-release/v99".into(); + let bytes = manifest.to_bytes().unwrap(); + let sig = sign(&key, &bytes); + assert!(matches!( + verify(&bytes, &sig, &did), + Err(ManifestError::UnknownSchema(_)) + )); + } + + #[test] + fn format_detection() { + // safetensors: 8-byte LE header length then '{'. + let mut st = 5u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{\"a\":0}"); + assert_eq!(detect_format(&st, "m.safetensors"), FileFormat::Safetensors); + assert_eq!(detect_format(b"GGUF\x01rest", "m.gguf"), FileFormat::Gguf); + assert_eq!(detect_format(b"\x80\x04x", "torch.bin"), FileFormat::Pickle); + assert_eq!( + detect_format(b"PK\x03\x04z", "pytorch_model.bin"), + FileFormat::Pickle + ); + // A zip that is NOT a checkpoint extension is not called pickle. + assert_eq!( + detect_format(b"PK\x03\x04z", "archive.zip"), + FileFormat::Other + ); + assert_eq!(detect_format(b"{\"a\":1}", "config.json"), FileFormat::Text); + assert_eq!(detect_format(b"", "tokenizer.model"), FileFormat::Text); + assert_eq!( + detect_format(b"\x00\x01\x02", "blob.weird"), + FileFormat::Other + ); + } + + /// Regenerate the frozen fixture (run once, deliberately): + /// `cargo test -p twigpine-core manifest_frozen_fixture_write -- --ignored` + #[test] + #[ignore = "writes the fixture files; run only when regenerating"] + fn manifest_frozen_fixture_write() { + let (key, did) = keypair(42); + let bytes = sample_manifest(&did).to_bytes().unwrap(); + let dir = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/model-release-v1" + ); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(format!("{dir}/manifest.json"), &bytes).unwrap(); + std::fs::write(format!("{dir}/manifest.sig"), sign(&key, &bytes)).unwrap(); + std::fs::write(format!("{dir}/publisher.did"), did.to_string()).unwrap(); + eprintln!("wrote fixture for {did} to {dir}"); + } + + #[test] + fn the_frozen_v1_fixture_still_verifies() { + let dir = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/model-release-v1" + ); + let bytes = std::fs::read(format!("{dir}/manifest.json")).unwrap(); + let sig = std::fs::read_to_string(format!("{dir}/manifest.sig")).unwrap(); + let did = Did::from_str( + std::fs::read_to_string(format!("{dir}/publisher.did")) + .unwrap() + .trim(), + ) + .unwrap(); + let parsed = verify(&bytes, &sig, &did).unwrap(); + assert_eq!(parsed.repo, "alice/llm"); + // And the frozen signature rejects tampering. + let mut tampered = bytes.clone(); + *tampered.last_mut().unwrap() ^= 1; + assert!(verify(&tampered, &sig, &did).is_err()); + } +} diff --git a/crates/twigpine-core/src/model/mod.rs b/crates/twigpine-core/src/model/mod.rs index f8dd1cc8..e687b768 100644 --- a/crates/twigpine-core/src/model/mod.rs +++ b/crates/twigpine-core/src/model/mod.rs @@ -10,6 +10,7 @@ //! recomputed by the node on receipt. pub mod chunking; +pub mod manifest; pub mod reconstruction; /// The schema tag carried by the reconstruction object defined here. Unknown diff --git a/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.json b/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.json new file mode 100644 index 00000000..0a2d2126 --- /dev/null +++ b/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.json @@ -0,0 +1 @@ +{"schema":"gitlawb/model-release/v1","repo":"alice/llm","publisher_did":"did:key:z6MkgAnvkP45uNxwCKeNdt6wrYkEjpYX4f7Nrd8MQqFL8Fbn","license":"apache-2.0","parent":null,"files":[{"path":"model.safetensors","size":1024,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","format":"safetensors","storage":"chunked"},{"path":"config.json","size":256,"sha256":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","format":"text","storage":"git"}],"reconstruction":{"sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","size":512}} \ No newline at end of file diff --git a/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.sig b/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.sig new file mode 100644 index 00000000..b30b30e1 --- /dev/null +++ b/crates/twigpine-core/tests/fixtures/model-release-v1/manifest.sig @@ -0,0 +1 @@ +dri5eq548Bth3n7iqOI6Z2fsD5TLmD5bK1Ru/svQNhMnFz0EGaexMIe0uZ+HMLgmVWC6dSccbpfXlbNmS7r1Cw== \ No newline at end of file diff --git a/crates/twigpine-core/tests/fixtures/model-release-v1/publisher.did b/crates/twigpine-core/tests/fixtures/model-release-v1/publisher.did new file mode 100644 index 00000000..db73a6f5 --- /dev/null +++ b/crates/twigpine-core/tests/fixtures/model-release-v1/publisher.did @@ -0,0 +1 @@ +did:key:z6MkgAnvkP45uNxwCKeNdt6wrYkEjpYX4f7Nrd8MQqFL8Fbn \ No newline at end of file From 259f7a19753a759683b2f1a75815a772051a34de Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:29:41 -0600 Subject: [PATCH 05/53] fix(core): pack new chunks into full blocks across reused runs Sealing the staged block on every dedup hit turned a fine-tune with scattered edits into one tiny block per changed region, multiplying the object and pin count that blocks exist to keep low. New chunks now accumulate into a single pending block that seals only at the target size or at EOF; their terms carry a placeholder block id that is patched in when the block seals. Also classify sentencepiece .model files as binary rather than text: tokenizer.model is a protobuf, so it now falls through to `other`. --- crates/twigpine-core/src/model/manifest.rs | 7 +- .../twigpine-core/src/model/reconstruction.rs | 111 ++++++++++++++---- 2 files changed, 94 insertions(+), 24 deletions(-) diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index ce9f9202..88a3f196 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -218,7 +218,9 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { } if matches!( ext, - "json" | "txt" | "md" | "py" | "jinja" | "model" | "yaml" | "yml" + // `tokenizer.model` is deliberately absent: it is a sentencepiece + // protobuf, so it falls through to `other` like the binaries. + "json" | "txt" | "md" | "py" | "jinja" | "yaml" | "yml" ) { return FileFormat::Text; } @@ -353,7 +355,8 @@ mod tests { FileFormat::Other ); assert_eq!(detect_format(b"{\"a\":1}", "config.json"), FileFormat::Text); - assert_eq!(detect_format(b"", "tokenizer.model"), FileFormat::Text); + // Sentencepiece models are protobufs, not text. + assert_eq!(detect_format(b"", "tokenizer.model"), FileFormat::Other); assert_eq!( detect_format(b"\x00\x01\x02", "blob.weird"), FileFormat::Other diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index e66d39a8..556b2bb2 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -199,18 +199,19 @@ fn idx_insert(map: &mut HashMap, k: String, v: (String, u map.entry(k).or_insert(v); } -/// Seal a staged run of new chunks into one block and append its term and -/// block-table entry. -fn seal_staged( - staged: &mut Vec, +/// Seal the accumulating block of new chunks: patch its id into the terms +/// written while it was still open, then append the block-table entry and +/// queue the bytes for upload. +fn seal_pending( + pending: &mut Vec, terms: &mut Vec, block_entries: &mut Vec, new_blocks: &mut Vec, ) { - if staged.is_empty() { + if pending.is_empty() { return; } - let chunks = std::mem::take(staged); + let chunks = std::mem::take(pending); let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum::()); for c in &chunks { data.extend_from_slice(&c.data); @@ -220,12 +221,13 @@ fn seal_staged( chunks, data, }; - terms.push(Term { - block: block.sha256.clone(), - chunk_start: 0, - chunk_end: block.chunks.len() as u32, - length: block.data.len() as u64, - }); + // Terms for new chunks were written with an empty placeholder id + // because the block hash is not known until it seals. + for term in terms.iter_mut() { + if term.block.is_empty() { + term.block = block.sha256.clone(); + } + } block_entries.push(BlockEntry { sha256: block.sha256.clone(), size: block.data.len() as u64, @@ -263,10 +265,12 @@ pub fn pack_file( let mut terms: Vec = Vec::new(); let mut new_blocks: Vec = Vec::new(); let mut block_entries: Vec = Vec::new(); - // Chunks not found in `dedup`, staged until the staging run seals into a - // block (at the target size, on a reused-chunk boundary, or at EOF). - let mut staged: Vec = Vec::new(); - let mut staged_bytes: usize = 0; + // Chunks not found in `dedup` accumulate into one pending block that + // seals only at the target size or EOF. Sealing on every reused-chunk + // boundary would scatter a fine-tune's edits into one tiny block each, + // multiplying the object and pin count blocks exist to keep low. + let mut pending: Vec = Vec::new(); + let mut pending_bytes: usize = 0; let mut file_size: u64 = 0; for chunk in chunk_reader(reader) { @@ -274,7 +278,6 @@ pub fn pack_file( file_hasher.update(&chunk.data); file_size += chunk.len as u64; if let Some((block_sha, idx)) = dedup.by_chunk.get(&chunk.sha256) { - seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); // Extend the previous term when it already reads the chunk before // this one in the same block: a shared run stays a single term. match terms.last_mut() { @@ -290,14 +293,31 @@ pub fn pack_file( }), } } else { - staged_bytes += chunk.len; - staged.push(chunk); - if staged_bytes >= BLOCK_TARGET { - seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); + // The term indexes into the pending block at the position the + // chunk will hold once the block seals; the id is patched then. + let idx = pending.len() as u32; + let len = chunk.len as u64; + pending_bytes += chunk.len; + pending.push(chunk); + match terms.last_mut() { + Some(t) if t.block.is_empty() => { + t.chunk_end = idx + 1; + t.length += len; + } + _ => terms.push(Term { + block: String::new(), + chunk_start: idx, + chunk_end: idx + 1, + length: len, + }), + } + if pending_bytes >= BLOCK_TARGET { + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut new_blocks); + pending_bytes = 0; } } } - seal_staged(&mut staged, &mut terms, &mut block_entries, &mut new_blocks); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut new_blocks); let file = FileEntry { path: path.to_string(), @@ -576,6 +596,53 @@ mod tests { assert_eq!(out, tuned); } + #[test] + fn scattered_edits_share_one_new_block() { + // A fine-tune whose edits are spread across the file: every run of + // changed chunks lands in the same pending block, so the object and + // pin count does not grow with the number of edited regions. + let base = gen_bytes(20 * 1024 * 1024, 41); + let (base_rec, base_packed) = pack("model.safetensors", &base); + let region = (base.len() - 200_000) / 50; + let mut tuned = base.clone(); + for i in 0..50 { + let at = 50_000 + i * region; + for b in tuned.iter_mut().skip(at).take(4_096) { + *b = b.wrapping_add(7); + } + } + + let dedup = DedupIndex::from_reconstructions(&[&base_rec]); + let packed = pack_file("tuned.safetensors", Cursor::new(tuned.clone()), &dedup).unwrap(); + assert_eq!( + packed.new_blocks.len(), + 1, + "scattered edits must seal into one new block, not one per run" + ); + + let mut rec = Reconstruction::new(); + rec.blocks.extend(base_rec.blocks.iter().cloned()); + rec.blocks.extend(packed.block_entries.clone()); + rec.files.push(packed.file.clone()); + rec.validate().unwrap(); + + let store: HashMap> = base_packed + .new_blocks + .iter() + .chain(packed.new_blocks.iter()) + .map(|b| (b.sha256.clone(), b.data.clone())) + .collect(); + let mut out = Vec::new(); + rebuild_file( + &packed.file, + &rec, + &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut out, + ) + .unwrap(); + assert_eq!(out, tuned); + } + #[test] fn range_mapping_hits_the_middle_of_a_block() { // Build a 10-chunk block synthetically so the middle-subrange case is From 03e555829765e13f4cce1214a04991bb55f8496b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:31:31 -0600 Subject: [PATCH 06/53] perf(core): rebuild files from chunk ranges, not whole blocks Fetching an entire block per term re-read up to 64 MiB every time a file's terms revisited a block or named a middle chunk range. The fetcher is now a range read over the term's chunk span, computed from the same prefix-sum walk map_file_range uses. Blocks are hash-verified when stored, so verification keeps the per-chunk hashes plus the whole-file digest and drops the whole-block hash check. --- .../twigpine-core/src/model/reconstruction.rs | 167 +++++++++++++----- 1 file changed, 122 insertions(+), 45 deletions(-) diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 556b2bb2..36523c3e 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -343,6 +343,36 @@ pub struct BlockSlice { pub len: u64, } +/// Byte offset of each chunk inside a block, as a prefix sum over the +/// chunk table: `offsets[i]` is where chunk `i`'s bytes begin. +fn chunk_offsets(block: &BlockEntry) -> Vec { + block + .chunks + .iter() + .scan(0u64, |off, c| { + let start = *off; + *off += c.len; + Some(start) + }) + .collect() +} + +/// Byte range inside a block covering the chunks a term names. +fn term_span(block: &BlockEntry, term: &Term) -> Result<(u64, u64), ModelError> { + let start = term.chunk_start as usize; + let end = term.chunk_end as usize; + if start >= end || end > block.chunks.len() { + return Err(ModelError::Invalid(format!( + "term chunk range {start}..{end} outside block {} with {} chunks", + term.block, + block.chunks.len() + ))); + } + let offsets = chunk_offsets(block); + let len: u64 = block.chunks[start..end].iter().map(|c| c.len).sum(); + Ok((offsets[start], len)) +} + pub fn map_file_range( file: &FileEntry, rec: &Reconstruction, @@ -367,24 +397,17 @@ pub fn map_file_range( cursor = term_end; continue; } - // Byte offset of each chunk inside the block, as a prefix sum. - let mut block_off = 0u64; - for (i, chunk) in block.chunks.iter().enumerate() { - block_off += chunk.len; - if i < term.chunk_start as usize { - continue; - } - if i >= term.chunk_end as usize { - break; - } + let offsets = chunk_offsets(block); + for i in term.chunk_start as usize..term.chunk_end as usize { + let chunk = &block.chunks[i]; // This chunk covers file bytes [chunk_lo, chunk_hi). - let chunk_hi = cursor + chunk.len; let chunk_lo = cursor; + let chunk_hi = cursor + chunk.len; cursor = chunk_hi; let s = start.max(chunk_lo); let e = end_exclusive.min(chunk_hi); if s < e { - let off = block_off - chunk.len + (s - chunk_lo); + let off = offsets[i] + (s - chunk_lo); match out.last_mut() { // Adjacent slices in the same block merge into one read. Some(slice) if slice.block == term.block && slice.offset + slice.len == off => { @@ -405,12 +428,15 @@ pub fn map_file_range( } /// Rebuild a file's bytes from its terms, verifying every chunk's hash and -/// the whole-file digest. `fetch` returns a block's bytes by id (a -/// BlockStore range read or a cache hit on the caller's side). +/// the whole-file digest. `fetch` is a range read returning exactly `len` +/// bytes starting at `offset` inside the named block (a BlockStore range +/// read or a cache hit on the caller's side). The block id itself is not +/// re-verified here: blocks are hash-verified when stored, and the chunk +/// hashes cover the bytes this file actually uses. pub fn rebuild_file( file: &FileEntry, rec: &Reconstruction, - fetch: &mut dyn FnMut(&str) -> std::io::Result>, + fetch: &mut dyn FnMut(&str, u64, u64) -> std::io::Result>, out: &mut W, ) -> Result { use sha2::Digest; @@ -421,34 +447,28 @@ pub fn rebuild_file( let block = blocks .get(term.block.as_str()) .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; - let bytes = fetch(&term.block)?; - if sha256_hex(&bytes) != term.block { - return Err(ModelError::HashMismatch(format!( - "block {} content does not hash to its id", - term.block + let (offset, span_len) = term_span(block, term)?; + let bytes = fetch(&term.block, offset, span_len)?; + if bytes.len() as u64 != span_len { + return Err(ModelError::Invalid(format!( + "range read on block {} returned {} of {span_len} bytes", + term.block, + bytes.len() ))); } - let mut off = 0usize; - for (i, chunk) in block.chunks.iter().enumerate() { - let next = off + chunk.len as usize; - if i >= term.chunk_start as usize && i < term.chunk_end as usize { - let data = bytes.get(off..next).ok_or_else(|| { - ModelError::Invalid(format!( - "block {} shorter than its chunk table", - term.block - )) - })?; - if sha256_hex(data) != chunk.sha256 { - return Err(ModelError::HashMismatch(format!( - "chunk {} in block {}", - chunk.sha256, term.block - ))); - } - out.write_all(data)?; - file_hasher.update(data); - written += chunk.len; + let mut rel = 0usize; + for chunk in &block.chunks[term.chunk_start as usize..term.chunk_end as usize] { + let data = &bytes[rel..rel + chunk.len as usize]; + if sha256_hex(data) != chunk.sha256 { + return Err(ModelError::HashMismatch(format!( + "chunk {} in block {}", + chunk.sha256, term.block + ))); } - off = next; + out.write_all(data)?; + file_hasher.update(data); + written += chunk.len; + rel += chunk.len as usize; } } if written != file.size { @@ -508,7 +528,10 @@ mod tests { let n = rebuild_file( &packed.file, &rec, - &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut |id, off, len| { + let block = store.get(id).expect("block"); + Ok(block[off as usize..(off + len) as usize].to_vec()) + }, &mut out, ) .unwrap(); @@ -589,7 +612,10 @@ mod tests { rebuild_file( &packed.file, &rec, - &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut |id, off, len| { + let block = store.get(id).expect("block"); + Ok(block[off as usize..(off + len) as usize].to_vec()) + }, &mut out, ) .unwrap(); @@ -636,7 +662,10 @@ mod tests { rebuild_file( &packed.file, &rec, - &mut |id| Ok(store.get(id).cloned().expect("block")), + &mut |id, off, len| { + let block = store.get(id).expect("block"); + Ok(block[off as usize..(off + len) as usize].to_vec()) + }, &mut out, ) .unwrap(); @@ -708,8 +737,56 @@ mod tests { let bytes = gen_bytes(300_000, 31); let (rec, packed) = pack("f", &bytes); let mut out = Vec::new(); - let err = - rebuild_file(&packed.file, &rec, &mut |_id| Ok(vec![0u8; 16]), &mut out).unwrap_err(); + let err = rebuild_file( + &packed.file, + &rec, + &mut |_id, _off, len| Ok(vec![0u8; len as usize]), + &mut out, + ) + .unwrap_err(); assert!(matches!(err, ModelError::HashMismatch(_))); } + + #[test] + fn rebuild_fetches_only_the_bytes_the_file_needs() { + // Terms can revisit one block or name a middle chunk range: the + // fetcher must serve each term's span, never whole blocks, so the + // bytes read equal the file size rather than a multiple of it. + let base = gen_bytes(4 * 1024 * 1024, 53); + let (base_rec, base_packed) = pack("base.safetensors", &base); + let mut tuned = base.clone(); + for b in tuned.iter_mut().skip(1024 * 1024).take(64 * 1024) { + *b = b.wrapping_add(3); + } + + let dedup = DedupIndex::from_reconstructions(&[&base_rec]); + let packed = pack_file("tuned.safetensors", Cursor::new(tuned.clone()), &dedup).unwrap(); + let mut rec = Reconstruction::new(); + rec.blocks.extend(base_rec.blocks.iter().cloned()); + rec.blocks.extend(packed.block_entries.clone()); + rec.files.push(packed.file.clone()); + rec.validate().unwrap(); + + let store: HashMap> = base_packed + .new_blocks + .iter() + .chain(packed.new_blocks.iter()) + .map(|b| (b.sha256.clone(), b.data.clone())) + .collect(); + let mut fetched = 0u64; + let mut out = Vec::new(); + rebuild_file( + &packed.file, + &rec, + &mut |id, off, len| { + fetched += len; + let block = store.get(id).expect("block"); + Ok(block[off as usize..(off + len) as usize].to_vec()) + }, + &mut out, + ) + .unwrap(); + assert_eq!(out, tuned); + assert_eq!(fetched, packed.file.size); + } } From b794a7c5ea66eb185c579bae348610748ce1bde6 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:39:47 -0600 Subject: [PATCH 07/53] fix(node): fsync the block directory after linking A hard link is atomic but not durable: a crash after reporting Stored could lose the entry while the content survives as an orphan. Fsync the destination directory after a successful link, and when the / levels were just created, fsync each parent so their entries persist too. Unix only; other platforms keep the link as the best guarantee. --- crates/twigpine-node/src/blockstore/fs.rs | 36 ++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 917186b2..1a4d5dca 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -45,6 +45,20 @@ impl FsBlockStore { } } +/// Fsync a directory so a name created inside it survives a crash: after +/// `Stored`, a link that only exists in the page cache is a lost write. +#[cfg(unix)] +async fn fsync_dir(dir: &Path) -> io::Result<()> { + tokio::fs::File::open(dir).await?.sync_all().await +} + +/// Directory fsync is a unix durability primitive; elsewhere the link is +/// the best guarantee available. +#[cfg(not(unix))] +async fn fsync_dir(_: &Path) -> io::Result<()> { + Ok(()) +} + #[async_trait] impl BlockStore for FsBlockStore { async fn put_verified( @@ -98,16 +112,30 @@ impl BlockStore for FsBlockStore { } drop(file); - if let Some(parent) = dest.parent() { - if let Err(e) = tokio::fs::create_dir_all(parent).await { - Self::cleanup(&tmp).await; - return Err(e.into()); + let dir = dest.parent().expect("content path has two levels"); + let fresh_dirs = !dir.exists(); + if let Err(e) = tokio::fs::create_dir_all(dir).await { + Self::cleanup(&tmp).await; + return Err(e.into()); + } + if fresh_dirs { + // The new / levels are themselves names in a parent + // directory; persist each level's entry. + for ancestor in [dir.parent().unwrap_or(&self.root), self.root.as_path()] { + if let Err(e) = fsync_dir(ancestor).await { + Self::cleanup(&tmp).await; + return Err(e.into()); + } } } // A hard link refuses to replace an existing object, which is what // 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 { + Self::cleanup(&tmp).await; + return Err(e.into()); + } Self::cleanup(&tmp).await; Ok(PutOutcome::Stored) } From d7d744dddb76f922e9b199f77327905bf14df3c3 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:40:09 -0600 Subject: [PATCH 08/53] style(core): apply rustfmt to the seal call sites --- crates/twigpine-core/src/model/reconstruction.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 36523c3e..b70a81fe 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -312,12 +312,22 @@ pub fn pack_file( }), } if pending_bytes >= BLOCK_TARGET { - seal_pending(&mut pending, &mut terms, &mut block_entries, &mut new_blocks); + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &mut new_blocks, + ); pending_bytes = 0; } } } - seal_pending(&mut pending, &mut terms, &mut block_entries, &mut new_blocks); + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &mut new_blocks, + ); let file = FileEntry { path: path.to_string(), From 16d0a305070a5fbc2d83606adffa18e46f05f956 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:51:03 -0600 Subject: [PATCH 09/53] style(core): satisfy clippy in packing and rebuild Slice parameter, iterator loop, and a fetch type alias; no behavior change. --- crates/twigpine-core/src/model/reconstruction.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index b70a81fe..bddb52c5 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -204,7 +204,7 @@ fn idx_insert(map: &mut HashMap, k: String, v: (String, u /// queue the bytes for upload. fn seal_pending( pending: &mut Vec, - terms: &mut Vec, + terms: &mut [Term], block_entries: &mut Vec, new_blocks: &mut Vec, ) { @@ -408,8 +408,10 @@ pub fn map_file_range( continue; } let offsets = chunk_offsets(block); - for i in term.chunk_start as usize..term.chunk_end as usize { - let chunk = &block.chunks[i]; + for (i, chunk) in block.chunks[term.chunk_start as usize..term.chunk_end as usize] + .iter() + .enumerate() + { // This chunk covers file bytes [chunk_lo, chunk_hi). let chunk_lo = cursor; let chunk_hi = cursor + chunk.len; @@ -417,7 +419,7 @@ pub fn map_file_range( let s = start.max(chunk_lo); let e = end_exclusive.min(chunk_hi); if s < e { - let off = offsets[i] + (s - chunk_lo); + let off = offsets[term.chunk_start as usize + i] + (s - chunk_lo); match out.last_mut() { // Adjacent slices in the same block merge into one read. Some(slice) if slice.block == term.block && slice.offset + slice.len == off => { @@ -437,6 +439,10 @@ pub fn map_file_range( Ok(out) } +/// A range read over a stored block: `fetch(block_id, offset, len)` returns +/// exactly `len` bytes starting at `offset`. +pub type BlockRangeFetch<'a> = dyn FnMut(&str, u64, u64) -> std::io::Result> + 'a; + /// Rebuild a file's bytes from its terms, verifying every chunk's hash and /// the whole-file digest. `fetch` is a range read returning exactly `len` /// bytes starting at `offset` inside the named block (a BlockStore range @@ -446,7 +452,7 @@ pub fn map_file_range( pub fn rebuild_file( file: &FileEntry, rec: &Reconstruction, - fetch: &mut dyn FnMut(&str, u64, u64) -> std::io::Result>, + fetch: &mut BlockRangeFetch<'_>, out: &mut W, ) -> Result { use sha2::Digest; From 26e577d7d37b9c919124b2087245d73030c8a2e0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:24:39 -0600 Subject: [PATCH 10/53] refactor: simplify model hosting foundation Reuse crate::cid::sha256_hex instead of a module-local copy; drop the unused BlockPacker/BLOCK_CAP (pack_file does the packing), the unused FileFormat Display impl, and a one-line entry/or_insert wrapper; share the tests' byte generator; verify releases against the caller's DID directly instead of re-parsing the proven-equal manifest field; and fold the duplicated multipart part-flush into one helper. --- crates/twigpine-core/src/model/chunking.rs | 127 +----------------- crates/twigpine-core/src/model/manifest.rs | 33 ++--- crates/twigpine-core/src/model/mod.rs | 20 ++- .../twigpine-core/src/model/reconstruction.rs | 30 +---- crates/twigpine-node/src/blockstore/s3.rs | 36 +++-- crates/twigpine-node/src/config.rs | 1 - 6 files changed, 58 insertions(+), 189 deletions(-) diff --git a/crates/twigpine-core/src/model/chunking.rs b/crates/twigpine-core/src/model/chunking.rs index dd517721..190c1e58 100644 --- a/crates/twigpine-core/src/model/chunking.rs +++ b/crates/twigpine-core/src/model/chunking.rs @@ -1,10 +1,8 @@ //! Content-defined chunking and block packing. //! //! Chunking uses FastCDC (the 2020 algorithm variant) at 8 / 64 / 128 KiB -//! min / avg / max. The packer seals a block once the accumulated chunks -//! reach the 64 MiB target; since a chunk is at most 128 KiB, a sealed block -//! can never approach the 128 MiB hard cap, which exists to bound block size -//! if the chunk parameters ever change. +//! min / avg / max. Packing into blocks lives in `reconstruction::pack_file`, +//! which seals at the 64 MiB target or end of stream. use std::io::Read; @@ -16,7 +14,6 @@ pub const CHUNK_MIN: usize = 8 * 1024; pub const CHUNK_AVG: usize = 64 * 1024; pub const CHUNK_MAX: usize = 128 * 1024; pub const BLOCK_TARGET: usize = 64 * 1024 * 1024; -pub const BLOCK_CAP: usize = 128 * 1024 * 1024; /// One content-defined chunk of a file. `data` is present while packing; the /// id is the chunk's sha256, which is how the chunk dedups across files and @@ -51,105 +48,13 @@ pub fn chunk_reader(reader: R) -> impl Iterator>> { - chunks: I, - pending: Vec, - pending_bytes: usize, - done: bool, -} - -impl>> BlockPacker { - pub fn new(chunks: I) -> Self { - Self { - chunks, - pending: Vec::new(), - pending_bytes: 0, - done: false, - } - } - - /// Seal `pending` into a block when it holds anything. The caller owns the - /// returned chunks' data; a block's `data` is its bytes. - fn seal(&mut self) -> Option> { - if self.pending.is_empty() { - return None; - } - let chunks = std::mem::take(&mut self.pending); - self.pending_bytes = 0; - let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum()); - for c in &chunks { - data.extend_from_slice(&c.data); - } - Some(Ok(Block { - sha256: sha256_hex(&data), - chunks, - data, - })) - } -} - -impl>> Iterator for BlockPacker { - type Item = std::io::Result; - - fn next(&mut self) -> Option { - if self.done { - return None; - } - loop { - match self.chunks.next() { - Some(Ok(chunk)) => { - // A single chunk may exceed the target; it still joins the - // block under construction, and the cap check below is the - // only hard stop. Sealing before adding keeps any block at - // target + one chunk at most. - if self.pending_bytes >= BLOCK_TARGET - || self.pending_bytes + chunk.len > BLOCK_CAP - { - let sealed = self.seal(); - self.pending.push(chunk); - self.pending_bytes += self.pending.last().map(|c| c.len).unwrap_or(0); - return sealed; - } - self.pending_bytes += chunk.len; - self.pending.push(chunk); - } - Some(Err(e)) => { - self.done = true; - return Some(Err(e)); - } - None => { - self.done = true; - return self.seal(); - } - } - } - } -} - #[cfg(test)] mod tests { use super::*; + use crate::model::gen_bytes; use std::io::Cursor; - /// Deterministic pseudo-random bytes: rand is a dependency of this crate - /// but a fixed-pattern generator makes the tests reproducible without a - /// seed constant. - fn gen_bytes(n: usize) -> Vec { - let mut v = Vec::with_capacity(n); - let mut x: u64 = 0x9e3779b97f4a7c15; - while v.len() < n { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - v.extend_from_slice(&x.to_le_bytes()); - } - v.truncate(n); - v - } + const SEED: u64 = 0x9e3779b97f4a7c15; fn chunk_all(bytes: &[u8]) -> Vec { chunk_reader(Cursor::new(bytes.to_vec())) @@ -159,7 +64,7 @@ mod tests { #[test] fn chunking_is_deterministic() { - let bytes = gen_bytes(3 * 1024 * 1024); + let bytes = gen_bytes(3 * 1024 * 1024, SEED); let a = chunk_all(&bytes); let b = chunk_all(&bytes); assert_eq!(a.len(), b.len()); @@ -172,7 +77,7 @@ mod tests { #[test] fn chunk_sizes_stay_within_bounds() { - let bytes = gen_bytes(10 * 1024 * 1024); + let bytes = gen_bytes(10 * 1024 * 1024, SEED); let chunks = chunk_all(&bytes); assert!(chunks.len() > 10); for (i, c) in chunks.iter().enumerate() { @@ -186,7 +91,7 @@ mod tests { #[test] fn a_small_edit_changes_only_early_chunks() { - let base = gen_bytes(20 * 1024 * 1024); + let base = gen_bytes(20 * 1024 * 1024, SEED); let mut edited = vec![0u8; 100]; edited.extend_from_slice(&base); @@ -209,24 +114,6 @@ mod tests { ); } - #[test] - fn packing_round_trips_bytes() { - // Small enough to exercise seals without a huge test file: multiple - // blocks only form past 64 MiB, so here we check boundary accounting - // on a tail block and byte identity end to end. - let bytes = gen_bytes(2 * 1024 * 1024 + 7); - let blocks: Vec = BlockPacker::new(chunk_reader(Cursor::new(bytes.clone()))) - .collect::>() - .unwrap(); - assert_eq!(blocks.len(), 1, "under-target input seals to a tail block"); - let reassembled: Vec = blocks - .iter() - .flat_map(|b| b.chunks.iter().flat_map(|c| c.data.clone())) - .collect(); - assert_eq!(reassembled, bytes); - assert_eq!(blocks[0].sha256, sha256_hex(&bytes)); - } - #[test] fn chunk_data_never_buffers_the_file() { // The contract this format depends on: a reader is consumed a chunk diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index 88a3f196..90cac811 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -13,9 +13,6 @@ //! manifest's field is still checked for equality so a manifest naming one //! publisher cannot pass for another. -use std::fmt; -use std::str::FromStr; - use ed25519_dalek::{Signature, Signer, SigningKey}; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -64,19 +61,6 @@ pub enum FileFormat { Other, } -impl fmt::Display for FileFormat { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match self { - FileFormat::Safetensors => "safetensors", - FileFormat::Gguf => "gguf", - FileFormat::Pickle => "pickle", - FileFormat::Text => "text", - FileFormat::Other => "other", - }; - f.write_str(s) - } -} - /// Where a manifest-listed file's bytes live. Files under the chunking /// threshold stay ordinary git blobs; larger ones are reconstructed from /// content blocks. @@ -172,9 +156,9 @@ pub fn verify( found: manifest.publisher_did, }); } - let publisher = - Did::from_str(&manifest.publisher_did).map_err(|e| ManifestError::Did(e.to_string()))?; - let key = publisher + // The named publisher was just proven equal to the caller-supplied DID, + // so the key comes from that DID rather than a second parse of the field. + let key = expected_did .to_verifying_key() .map_err(|e| ManifestError::Did(e.to_string()))?; @@ -389,12 +373,11 @@ mod tests { ); let bytes = std::fs::read(format!("{dir}/manifest.json")).unwrap(); let sig = std::fs::read_to_string(format!("{dir}/manifest.sig")).unwrap(); - let did = Did::from_str( - std::fs::read_to_string(format!("{dir}/publisher.did")) - .unwrap() - .trim(), - ) - .unwrap(); + let did: Did = std::fs::read_to_string(format!("{dir}/publisher.did")) + .unwrap() + .trim() + .parse() + .unwrap(); let parsed = verify(&bytes, &sig, &did).unwrap(); assert_eq!(parsed.repo, "alice/llm"); // And the frozen signature rejects tampering. diff --git a/crates/twigpine-core/src/model/mod.rs b/crates/twigpine-core/src/model/mod.rs index e687b768..cf969d0a 100644 --- a/crates/twigpine-core/src/model/mod.rs +++ b/crates/twigpine-core/src/model/mod.rs @@ -9,6 +9,8 @@ //! by the sha256 of their bytes, computed by whoever holds them and //! recomputed by the node on receipt. +pub(crate) use crate::cid::sha256_hex; + pub mod chunking; pub mod manifest; pub mod reconstruction; @@ -18,8 +20,18 @@ pub mod reconstruction; /// format. pub const RECONSTRUCTION_SCHEMA_V1: &str = "gitlawb/model-reconstruction/v1"; -/// Lowercase hex sha256 of some bytes. -pub fn sha256_hex(bytes: &[u8]) -> String { - use sha2::Digest; - hex::encode(sha2::Sha256::digest(bytes)) +/// Deterministic pseudo-random bytes for tests: `rand` is a dependency of +/// this crate, but a fixed-pattern generator keeps the tests reproducible. +#[cfg(test)] +pub(crate) fn gen_bytes(n: usize, seed: u64) -> Vec { + let mut v = Vec::with_capacity(n); + let mut x = seed; + while v.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + v.extend_from_slice(&x.to_le_bytes()); + } + v.truncate(n); + v } diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index bddb52c5..70d2a33e 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::io::{Read, Write}; use serde::{Deserialize, Serialize}; +use sha2::Digest; use thiserror::Error; use super::chunking::{chunk_reader, Block, BLOCK_TARGET}; @@ -185,20 +186,14 @@ impl DedupIndex { for (i, chunk) in block.chunks.iter().enumerate() { // First writer wins: two priors carrying the same chunk are // interchangeable, so keep the earliest. - idx_insert( - &mut self.by_chunk, - chunk.sha256.clone(), - (block.sha256.clone(), i as u32), - ); + self.by_chunk + .entry(chunk.sha256.clone()) + .or_insert((block.sha256.clone(), i as u32)); } } } } -fn idx_insert(map: &mut HashMap, k: String, v: (String, u32)) { - map.entry(k).or_insert(v); -} - /// Seal the accumulating block of new chunks: patch its id into the terms /// written while it was still open, then append the block-table entry and /// queue the bytes for upload. @@ -260,7 +255,6 @@ pub fn pack_file( dedup: &DedupIndex, ) -> std::io::Result { let mut file_hasher = sha2::Sha256::new(); - use sha2::Digest; let mut terms: Vec = Vec::new(); let mut new_blocks: Vec = Vec::new(); @@ -455,7 +449,6 @@ pub fn rebuild_file( fetch: &mut BlockRangeFetch<'_>, out: &mut W, ) -> Result { - use sha2::Digest; let blocks = rec.block_index(); let mut file_hasher = sha2::Sha256::new(); let mut written = 0u64; @@ -506,21 +499,9 @@ pub fn rebuild_file( #[cfg(test)] mod tests { use super::*; + use crate::model::gen_bytes; use std::io::Cursor; - fn gen_bytes(n: usize, seed: u64) -> Vec { - let mut v = Vec::with_capacity(n); - let mut x = seed; - while v.len() < n { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - v.extend_from_slice(&x.to_le_bytes()); - } - v.truncate(n); - v - } - fn pack(path: &str, bytes: &[u8]) -> (Reconstruction, PackedFile) { let dedup = DedupIndex::new(); let packed = pack_file(path, Cursor::new(bytes.to_vec()), &dedup).unwrap(); @@ -740,7 +721,6 @@ mod tests { let served: u64 = slices.iter().map(|s| s.len).sum(); assert_eq!(served, want - 10); assert_eq!(slices[0].offset, prefix + 10); - // And the served bytes equal the file bytes. let mut got = Vec::new(); for s in &slices { got.extend_from_slice(&block_data[s.offset as usize..(s.offset + s.len) as usize]); diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index d911f23d..5621c669 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -109,6 +109,20 @@ impl S3BlockStore { .build()) } + /// Upload the bytes accumulated in `part_buf` as the next part. + async fn flush_part( + &self, + key: &str, + upload_id: &str, + part_buf: &mut Vec, + parts: &mut Vec, + ) -> Result<(), BlockStoreError> { + let staged = std::mem::take(part_buf); + let number = (parts.len() + 1) as i32; + parts.push(self.upload_one_part(key, upload_id, number, staged).await?); + Ok(()) + } + async fn abort(&self, key: &str, upload_id: &str) { if let Err(e) = self .s3 @@ -190,12 +204,8 @@ impl BlockStore for S3BlockStore { hasher.update(&chunk); part_buf.extend_from_slice(&chunk); if part_buf.len() >= PART_SIZE { - let staged = std::mem::take(&mut part_buf); - let number = (parts.len() + 1) as i32; - parts.push( - self.upload_one_part(&key, &upload_id, number, staged) - .await?, - ); + self.flush_part(&key, &upload_id, &mut part_buf, &mut parts) + .await?; } } Ok(()) @@ -211,14 +221,12 @@ impl BlockStore for S3BlockStore { return Err(BlockStoreError::DigestMismatch); } if !part_buf.is_empty() { - let staged = std::mem::take(&mut part_buf); - let number = (parts.len() + 1) as i32; - match self.upload_one_part(&key, &upload_id, number, staged).await { - Ok(part) => parts.push(part), - Err(e) => { - self.abort(&key, &upload_id).await; - return Err(e); - } + if let Err(e) = self + .flush_part(&key, &upload_id, &mut part_buf, &mut parts) + .await + { + self.abort(&key, &upload_id).await; + return Err(e); } } if parts.is_empty() { diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index fa4e3c44..bb56a020 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1405,7 +1405,6 @@ mod tests { assert_eq!(config.model_node_quota_bytes, 1 << 40); assert_eq!(config.model_unclaimed_ttl_secs, 86_400); assert_eq!(config.model_session_ttl_secs, 43_200); - // An unset session cap falls back to the per-identity quota. assert_eq!(config.model_max_session_bytes, None); assert_eq!( config.effective_model_max_session_bytes(), From 6c5431bfdefde675103fade3eccaa35b0f3d3be9 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:54:51 -0600 Subject: [PATCH 11/53] fix(node): align S3 range reads with the BlockStore contract get_range disagreed across backends on both edge axes: fs accepted an empty range and rejected an end past the object size, while S3 rejected the empty range and let S3 clamp an over-long end to EOF, silently returning a short body. Callers cannot depend on either behavior being stable across backends. The S3 backend now resolves the object size with HEAD first, maps a missing object to NotFound, enforces the same bounds fs does, and serves an empty in-bounds range without a GET. The trait documents the contract explicitly, and a shared parity test pins the edge cases on both backends. --- crates/twigpine-node/src/blockstore/fs.rs | 7 ++ crates/twigpine-node/src/blockstore/mod.rs | 86 +++++++++++++++++++++- crates/twigpine-node/src/blockstore/s3.rs | 19 ++++- 3 files changed, 109 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 1a4d5dca..61da56b1 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -303,6 +303,13 @@ mod tests { )); } + #[tokio::test] + async fn range_edge_contract_matches_the_trait() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + crate::blockstore::parity::get_range_edge_contract(&s).await; + } + #[tokio::test] async fn concurrent_puts_leave_one_object() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs index fe88fd08..4a89325d 100644 --- a/crates/twigpine-node/src/blockstore/mod.rs +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -114,8 +114,11 @@ pub trait BlockStore: Send + Sync { max_len: u64, ) -> Result; - /// Stream bytes `[start, end_exclusive)` of the stored object. A range - /// past the end fails with `OutOfRange`; a missing object with `NotFound`. + /// Stream bytes `[start, end_exclusive)` of the stored object. An empty + /// range (`start == end_exclusive`) succeeds with an empty stream; + /// `start > end_exclusive` or an `end_exclusive` past the object size + /// fails with `OutOfRange`; a missing object fails with `NotFound`. + /// Backends must honor this contract identically. async fn get_range( &self, id: &BlockId, @@ -149,3 +152,82 @@ pub async fn build(config: &crate::config::Config) -> anyhow::Result = (0..10_000u32).map(|i| (i % 251) as u8).collect(); + let id = BlockId::parse(&hex::encode(Sha256::digest(&body))).unwrap(); + let put_body = futures::stream::iter(vec![Ok(Bytes::from(body.clone()))]).boxed(); + store.put_verified(&id, put_body, u64::MAX).await.unwrap(); + let size = body.len() as u64; + + async fn collect(mut s: BoxStream<'static, io::Result>) -> Vec { + let mut out = Vec::new(); + while let Some(c) = s.next().await { + out.extend_from_slice(&c.unwrap()); + } + out + } + + // Empty ranges are in bounds: at offset 0 and at the end. + assert!(collect(store.get_range(&id, 0, 0).await.unwrap()) + .await + .is_empty()); + assert!(collect(store.get_range(&id, size, size).await.unwrap()) + .await + .is_empty()); + // The whole object is the largest legal range. + assert_eq!( + collect(store.get_range(&id, 0, size).await.unwrap()).await, + body + ); + // One byte past the end is out of bounds, from any start. + assert!(matches!( + store + .get_range(&id, 0, size + 1) + .await + .map(|_| ()) + .unwrap_err(), + BlockStoreError::OutOfRange + )); + assert!(matches!( + store + .get_range(&id, 10, size + 1) + .await + .map(|_| ()) + .unwrap_err(), + BlockStoreError::OutOfRange + )); + // A reversed range is out of bounds. + assert!(matches!( + store.get_range(&id, 20, 10).await.map(|_| ()).unwrap_err(), + BlockStoreError::OutOfRange + )); + // A missing object is NotFound, even for an empty range. + let missing = BlockId::parse(&"0".repeat(64)).unwrap(); + assert!(matches!( + store + .get_range(&missing, 0, 1) + .await + .map(|_| ()) + .unwrap_err(), + BlockStoreError::NotFound + )); + assert!(matches!( + store + .get_range(&missing, 0, 0) + .await + .map(|_| ()) + .unwrap_err(), + BlockStoreError::NotFound + )); + } +} diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index 5621c669..afafdbc2 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -279,9 +279,19 @@ impl BlockStore for S3BlockStore { start: u64, end_exclusive: u64, ) -> Result>, BlockStoreError> { - if start >= end_exclusive { + // Bounds come from a HEAD, not from the GET's range answer: S3 + // clamps an over-long end to the object size instead of failing, + // which would silently return fewer bytes than fs does. + let size = match self.size(id).await? { + Some(size) => size, + None => return Err(BlockStoreError::NotFound), + }; + if start > end_exclusive || end_exclusive > size { return Err(BlockStoreError::OutOfRange); } + if start == end_exclusive { + return Ok(futures::stream::empty().boxed()); + } let out = self .s3 .get_object() @@ -598,6 +608,13 @@ mod tests { assert_eq!(s.size(&id).await.unwrap(), None); } + #[tokio::test] + async fn range_edge_contract_matches_the_trait() { + let (url, _st) = spawn_mock(false).await; + let s = store(&url); + crate::blockstore::parity::get_range_edge_contract(&s).await; + } + #[tokio::test] async fn digest_mismatch_aborts_and_stores_nothing() { let (url, st) = spawn_mock(false).await; From 31140ff715fd67cc05216a76f3affb452c6b8ba8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:10:22 -0600 Subject: [PATCH 12/53] feat(node): add model upload sessions, release claims, and reclamation --- crates/twigpine-node/src/api/mod.rs | 13 + crates/twigpine-node/src/api/models.rs | 361 ++++++++ crates/twigpine-node/src/api/status/mod.rs | 4 +- crates/twigpine-node/src/db/mod.rs | 30 +- crates/twigpine-node/src/db/model_queries.rs | 888 +++++++++++++++++++ crates/twigpine-node/src/git/store.rs | 2 +- crates/twigpine-node/src/lib.rs | 11 + crates/twigpine-node/src/models/claim.rs | 272 ++++++ crates/twigpine-node/src/models/mod.rs | 173 ++++ crates/twigpine-node/src/models/sweep.rs | 80 ++ crates/twigpine-node/src/models/verify.rs | 307 +++++++ crates/twigpine-node/src/server.rs | 72 +- crates/twigpine-node/src/test_harness.rs | 54 +- crates/twigpine-node/tests/deny_harness.rs | 18 + crates/twigpine-node/tests/support/probe.rs | 15 + crates/twigpine-node/tests/support/routes.rs | 78 ++ 16 files changed, 2369 insertions(+), 9 deletions(-) create mode 100644 crates/twigpine-node/src/api/models.rs create mode 100644 crates/twigpine-node/src/db/model_queries.rs create mode 100644 crates/twigpine-node/src/models/claim.rs create mode 100644 crates/twigpine-node/src/models/mod.rs create mode 100644 crates/twigpine-node/src/models/sweep.rs create mode 100644 crates/twigpine-node/src/models/verify.rs diff --git a/crates/twigpine-node/src/api/mod.rs b/crates/twigpine-node/src/api/mod.rs index 75a560be..5d69fadd 100644 --- a/crates/twigpine-node/src/api/mod.rs +++ b/crates/twigpine-node/src/api/mod.rs @@ -13,6 +13,7 @@ pub mod events; pub mod ipfs; pub mod issues; pub mod labels; +pub mod models; pub mod peers; pub mod profiles; pub mod protect; @@ -219,6 +220,7 @@ mod authz_guard { let repos = include_str!("repos.rs"); let register = include_str!("register.rs"); let ipfs = include_str!("ipfs.rs"); + let models = include_str!("models.rs"); // (source, handler, expected gate marker) let rows: &[(&str, &str, &str)] = &[ @@ -323,6 +325,14 @@ mod authz_guard { (visibility, "remove_visibility", "require_owner("), (visibility, "list_visibility", "authorize_repo_read("), (visibility, "list_visibility", "require_owner("), + // Model hosting writes: session open and claim are owner-only + // behind the shared read gate; the unsigned block PUT read-gates + // as the session's owner. + (models, "open_model_session", "authorize_repo_read("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "authorize_repo_read("), + (models, "claim_model_release", "require_repo_owner("), + (models, "put_model_block", "authorize_repo_read("), ]; // Rows above prove each visibility handler calls authorize_repo_read and @@ -352,6 +362,8 @@ mod authz_guard { (issues, "close_issue", "did_matches("), (protect, "protect_branch", "did_matches("), (protect, "unprotect_branch", "did_matches("), + (models, "open_model_session", "require_repo_owner("), + (models, "claim_model_release", "require_repo_owner("), ] { let body = fn_body(src, func); let gate = body.find("authorize_repo_read(").expect("gate marker"); @@ -1194,6 +1206,7 @@ mod tests { async fn t() { let _ = did_matches(x, y); } } (include_str!("events.rs"), "events.rs"), (include_str!("issues.rs"), "issues.rs"), (include_str!("labels.rs"), "labels.rs"), + (include_str!("models.rs"), "models.rs"), (include_str!("protect.rs"), "protect.rs"), (include_str!("pulls.rs"), "pulls.rs"), (include_str!("replicas.rs"), "replicas.rs"), diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs new file mode 100644 index 00000000..e916da1b --- /dev/null +++ b/crates/twigpine-node/src/api/models.rs @@ -0,0 +1,361 @@ +//! Open-weight model hosting routes: signed upload-session open, unsigned +//! bearer-session block ingest, signed release claim, and the publisher +//! status reads. Mounted only when the operator enables model hosting; every +//! handler re-checks `state.block_store` so a disabled node answers the same +//! not-found as an unmounted route. + +use axum::extract::{Path, Request, State}; +use axum::http::HeaderMap; +use axum::response::IntoResponse; +use axum::{Extension, Json}; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::json; + +use crate::api::{authorize_repo_read, require_repo_owner}; +use crate::auth::{AuthenticatedDid, SignatureMaterial}; +use crate::blockstore::{BlockId, BlockStoreError}; +use crate::db::{RepoRecord, VisibilityRule}; +use crate::error::{AppError, Result}; +use crate::models; +use crate::state::AppState; + +/// `X-Twigpine-Model-Session`: the bearer credential on block PUTs. The +/// session id is a 256-bit random capability minted at session open; there +/// is no HTTP signature on the PUT because a 64 MiB signed body would have +/// to be buffered whole to verify. +pub const SESSION_HEADER: &str = "x-twigpine-model-session"; + +fn hosting_enabled(state: &AppState) -> Result<()> { + if state.block_store.is_some() { + Ok(()) + } else { + Err(AppError::NotFound( + "model hosting is not enabled on this node".into(), + )) + } +} + +/// Model hosting only serves fully public repositories: a private repo, or +/// a public one carrying any path-scoped visibility rule, refuses with a +/// clear 4xx rather than partially publishing. +fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { + if !record.is_public || !rules.is_empty() { + return Err(AppError::BadRequest( + "model hosting requires a fully public repository".into(), + )); + } + Ok(()) +} + +#[derive(Debug, Deserialize, Default)] +pub struct OpenSessionBody { + /// Optional commit sha of the declared parent release. Informational at + /// open time; the claim re-anchors the parent through the manifest. + #[serde(default)] + pub parent_release: Option, +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/sessions` — open an upload +/// session. Owner-only (a session writes bytes the owner is billed for) on a +/// fully public repo. +pub async fn open_model_session( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + _body: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + let session = models::open_session( + &state.db, + caller, + &record.id, + state.config.model_session_ttl_secs, + ) + .await?; + Ok(( + axum::http::StatusCode::CREATED, + Json(json!({ + "session_id": session.id, + "expires_at": session.expires_at, + })), + )) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/sessions/{id}` — owner-only +/// session status. +pub async fn get_model_session( + State(state): State, + Path((owner, name, id)): Path<(String, String, String)>, + Extension(auth): Extension, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, _rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + let session = models::load_session(&state.db, &id) + .await? + .filter(|s| s.repo_id == record.id) + .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; + Ok(Json(json!({ + "session_id": session.id, + "state": session.state, + "bytes_received": session.bytes_received, + "expires_at": session.expires_at, + }))) +} + +/// PUT `/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}` — stream one +/// content block under a session bearer. Unsigned by design (see +/// [`SESSION_HEADER`]); the gate resolves the session, then runs the repo +/// read check as the session's owner so a repo turned private or withheld +/// mid-upload stops accepting bytes. +pub async fn put_model_block( + State(state): State, + Path((owner, name, sha)): Path<(String, String, String)>, + headers: HeaderMap, + request: Request, +) -> Result> { + hosting_enabled(&state)?; + let Some(session_id) = headers + .get(SESSION_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + else { + return Err(AppError::Unauthorized( + "a model block PUT requires the session header".into(), + )); + }; + let pool = &state.db; + let Some(session) = models::load_session(pool, &session_id).await? else { + return Err(AppError::NotFound("model upload session not found".into())); + }; + // authorize_repo_read 404s a repo the session owner can no longer read; + // the session-to-repo binding check below keeps foreign-session PUTs + // indistinguishable from a missing session. + let (record, _rules) = + authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; + if session.repo_id != record.id + || session.state != "open" + || session.expires_at <= models::ts_now() + { + return Err(AppError::NotFound("model upload session not found".into())); + } + let block_id = + BlockId::parse(&sha).map_err(|e| AppError::BadRequest(format!("block id: {e}")))?; + let declared: u64 = headers + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .ok_or_else(|| AppError::BadRequest("Content-Length is required".into()))?; + if declared == 0 || declared > models::MAX_BLOCK_BYTES { + return Err(AppError::BadRequest(format!( + "block bodies are 1..{} bytes", + models::MAX_BLOCK_BYTES + ))); + } + + // Admission before any byte is stored: the conditional update is the + // atomic charge against both the per-identity session cap and the + // node-wide quota, and it slides the session expiry in the same write. + let session_cap = state.config.effective_model_max_session_bytes() as i64; + let node_cap = state.config.model_node_quota_bytes as i64; + let Some(_) = models::admit_bytes( + pool, + &session.id, + declared as i64, + state.config.model_session_ttl_secs, + session_cap, + node_cap, + ) + .await? + else { + // Not admitted: re-check whether the session died (404 hides the + // session) or a cap refused (named quota). + let session = models::load_session(pool, &session_id) + .await? + .filter(|s| s.state == "open" && s.expires_at > models::ts_now()); + return match session { + None => Err(AppError::NotFound("model upload session not found".into())), + Some(_) => Err(AppError::TooManyRequests(format!( + "the upload would exceed a model storage cap \ + (session cap {session_cap} bytes, node cap {node_cap} bytes)" + ))), + }; + }; + + let store = state.block_store.clone().expect("checked above"); + let stream = request + .into_body() + .into_data_stream() + .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); + let outcome = store + .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) + .await; + let outcome = match outcome { + Ok(o) => o, + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(match e { + BlockStoreError::DigestMismatch => { + AppError::BadRequest(format!("block body does not hash to the named id {sha}")) + } + BlockStoreError::TooLarge(cap) => { + AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + } + BlockStoreError::Unknown => AppError::Conflict( + "the write's outcome is unknown; check the object before retrying".into(), + ), + other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), + }); + } + }; + let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. + + let size = store + .size(&block_id) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")))? + .unwrap_or(declared); + let duplicate = models::record_block(pool, &session.id, &sha, size, declared as i64).await?; + let fresh = models::load_session(pool, &session.id).await?; + Ok(Json(json!({ + "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), + "duplicate": duplicate, + "expires_at": fresh.map(|s| s.expires_at).unwrap_or_default(), + }))) +} + +#[derive(Debug, Deserialize)] +pub struct ClaimBody { + pub commit: String, + pub branch: String, +} + +fn release_view(r: &models::ReleaseRow) -> serde_json::Value { + json!({ + "release_id": r.id, + "commit": r.commit_sha, + "branch": r.branch, + "state": r.state, + "manifest_sha256": r.manifest_sha256, + "failure_reason": r.failure_reason, + "created_at": r.created_at, + "published_at": r.published_at, + }) +} + +/// POST `/api/v1/repos/{owner}/{repo}/models/claims` — claim a pushed commit +/// as a model release. Runs the ordered KTD5 checks; a replay resolves to the +/// original row via the persisted request digest. +pub async fn claim_model_release( + State(state): State, + Path((owner, name)): Path<(String, String)>, + Extension(auth): Extension, + material: Option>, + Json(body): Json, +) -> Result> { + hosting_enabled(&state)?; + let caller = &auth.0; + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; + require_repo_owner(&record, caller)?; + require_fully_public(&record, &rules)?; + + let Some(Extension(material)) = material else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its signature material" + ))); + }; + let Some(body_bytes) = material.body.clone() else { + return Err(AppError::Internal(anyhow::anyhow!( + "claim route is missing its persisted request body" + ))); + }; + crate::api::status::require_body_bound_signature(&material, &body_bytes)?; + if body.commit.len() != 40 || !body.commit.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(AppError::BadRequest("commit must be a 40-hex sha".into())); + } + let material = models::claim::ClaimMaterial { + request_digest: crate::api::status::request_digest(&material, &body_bytes), + signature: material.signature, + signature_input: material.signature_input, + signing_string: material.signing_string, + body: body_bytes.to_vec(), + }; + let release = models::claim::claim_release( + &state, + &record, + caller, + &body.commit, + &body.branch, + &material, + ) + .await?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}` — release +/// status. Same read gate as the repo's other listing surfaces: anonymous on +/// a public repo, 404 where the caller cannot read. +pub async fn get_model_release( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result> { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + let (record, _rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + let release = models::release_by_commit(&state.db, &record.id, &commit) + .await? + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + Ok(Json(release_view(&release))) +} + +/// GET `/api/v1/repos/{owner}/{repo}/models/releases/{commit}/reconstruction` +/// — the reconstruction object of a published release, for publisher-side +/// dedup (KTD6). The repo read gate applies, plus the current-public check: +/// once a repo stops being fully public it stops serving model objects, +/// owner included. +pub async fn get_model_reconstruction( + State(state): State, + Path((owner, name, commit)): Path<(String, String, String)>, + auth: Option>, +) -> Result { + hosting_enabled(&state)?; + let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + let (record, rules) = + authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; + if !record.is_public || !rules.is_empty() { + return Err(AppError::NotFound("model release not found".into())); + } + let release = models::release_by_commit(&state.db, &record.id, &commit) + .await? + .filter(|r| r.state == "published") + .ok_or_else(|| AppError::NotFound("model release not found".into()))?; + let (manifest_bytes, manifest) = models::claim::read_verified_manifest( + &state.git_bin, + &std::path::PathBuf::from(&record.disk_path), + &release.commit_sha, + &record.owner_did, + ) + .await?; + let _ = manifest_bytes; + let Some(rec_ref) = &manifest.reconstruction else { + return Err(AppError::NotFound( + "release has no reconstruction object".into(), + )); + }; + let store = state.block_store.clone().expect("checked above"); + let bytes = models::read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; + Ok(( + [(axum::http::header::CONTENT_TYPE, "application/octet-stream")], + bytes, + )) +} diff --git a/crates/twigpine-node/src/api/status/mod.rs b/crates/twigpine-node/src/api/status/mod.rs index ab736a80..7fe8cf21 100644 --- a/crates/twigpine-node/src/api/status/mod.rs +++ b/crates/twigpine-node/src/api/status/mod.rs @@ -278,7 +278,7 @@ pub async fn create_status( /// /// A 400, not a 500: the material is exactly what the client signed, and what /// they signed does not cover what they sent. -fn require_body_bound_signature( +pub(crate) fn require_body_bound_signature( material: &crate::auth::SignatureMaterial, body: &[u8], ) -> Result<()> { @@ -317,7 +317,7 @@ fn require_body_bound_signature( /// This is not a nonce, and deliberately so. A nonce table needs pruning and a /// pruning window is a second replay window; the claim row IS the record of what /// was accepted, so uniqueness on it is self-maintaining. -fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { +pub(crate) fn request_digest(material: &crate::auth::SignatureMaterial, body: &[u8]) -> String { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); for part in [ diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 486a3391..0fe0d0d9 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -529,6 +529,8 @@ pub struct MarkerCleanup { /// spellings, and tests + the recovery drain all use them so a typo on one /// side or the other cannot silently mismatch the other. #[allow(dead_code)] // constants are used by tests + the next-slice handler +pub mod model_queries; + pub mod pending_state { #[allow(dead_code)] pub const PREPARED: &str = "prepared"; @@ -2820,6 +2822,30 @@ const MIGRATIONS: &[Migration] = &[ "CREATE INDEX IF NOT EXISTS idx_model_durability_jobs_pending ON model_durability_jobs (state, created_at)", ], }, + Migration { + version: 50, + name: "model_release_claim_digest_and_cascades", + stmts: &[ + // Replayed claims resolve by request digest instead of writing a + // second row, mirroring status_claims' dedupe. + "ALTER TABLE model_releases ADD COLUMN IF NOT EXISTS claim_request_digest TEXT", + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_request_digest ON model_releases (claim_request_digest) WHERE claim_request_digest IS NOT NULL", + // One in-flight verification per publisher: claim admission's + // check is check-then-act under the advisory lock, and this index + // is the backstop that makes a bug there still fail closed. + "CREATE UNIQUE INDEX IF NOT EXISTS idx_model_releases_one_verifying ON model_releases (publisher_did) WHERE state = 'verifying'", + // A deleted repo takes its sessions, releases, and links with it. + // The FK constraints are re-declared with ON DELETE CASCADE; the + // names are Postgres defaults (table_column_fkey). + "ALTER TABLE model_upload_sessions DROP CONSTRAINT IF EXISTS model_upload_sessions_repo_id_fkey, ADD CONSTRAINT model_upload_sessions_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_session_id_fkey, ADD CONSTRAINT model_session_blocks_session_id_fkey FOREIGN KEY (session_id) REFERENCES model_upload_sessions(id) ON DELETE CASCADE", + "ALTER TABLE model_session_blocks DROP CONSTRAINT IF EXISTS model_session_blocks_block_sha256_fkey, ADD CONSTRAINT model_session_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_releases DROP CONSTRAINT IF EXISTS model_releases_repo_id_fkey, ADD CONSTRAINT model_releases_repo_id_fkey FOREIGN KEY (repo_id) REFERENCES repos(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_release_id_fkey, ADD CONSTRAINT model_release_blocks_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + "ALTER TABLE model_release_blocks DROP CONSTRAINT IF EXISTS model_release_blocks_block_sha256_fkey, ADD CONSTRAINT model_release_blocks_block_sha256_fkey FOREIGN KEY (block_sha256) REFERENCES model_blocks(sha256) ON DELETE CASCADE", + "ALTER TABLE model_durability_jobs DROP CONSTRAINT IF EXISTS model_durability_jobs_release_id_fkey, ADD CONSTRAINT model_durability_jobs_release_id_fkey FOREIGN KEY (release_id) REFERENCES model_releases(id) ON DELETE CASCADE", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -14430,7 +14456,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ($1, $2, 'main', 'did:key:zOwner', 'verifying', + VALUES ($1, $2, 'main', 'did:key:zOwner', 'published', $3, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(repo_id) @@ -14507,7 +14533,7 @@ mod migration_tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'verifying', + VALUES ('repo-model', $1, 'main', 'did:key:zOwner', 'published', $2, 'sig', 'input', 'signing', '\\x00', '2026-11-19T00:00:00+00:00')", ) .bind(SHA_A) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs new file mode 100644 index 00000000..9a5a1eb6 --- /dev/null +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -0,0 +1,888 @@ +//! Model-hosting queries. Timestamps follow the repo convention: rfc3339 +//! text in TEXT columns, written and compared through the helpers here. + +#[cfg(any(test, feature = "test-harness"))] +use sqlx::PgPool; +use sqlx::{Postgres, Transaction}; + +use super::{Db, Result}; + +fn ts_now() -> String { + chrono::Utc::now().to_rfc3339() +} + +fn ts_from_now(secs: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() +} + +#[derive(Debug, Clone)] +pub struct ModelSession { + pub id: String, + pub owner_did: String, + pub repo_id: String, + pub expires_at: String, + pub bytes_received: i64, + pub state: String, +} + +type SessionTuple = (String, String, String, String, i64, String); + +const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; + +impl From for ModelSession { + fn from(t: SessionTuple) -> Self { + ModelSession { + id: t.0, + owner_did: t.1, + repo_id: t.2, + expires_at: t.3, + bytes_received: t.4, + state: t.5, + } + } +} + +#[derive(Debug, Clone)] +pub struct ModelRelease { + pub id: i64, + pub repo_id: String, + pub commit_sha: String, + pub branch: String, + pub publisher_did: String, + pub state: String, + pub manifest_sha256: String, + pub failure_reason: Option, + pub created_at: String, + pub published_at: Option, + pub request_digest: Option, +} + +#[allow(clippy::type_complexity)] +pub type ReleaseTuple = ( + i64, + String, + String, + String, + String, + String, + String, + Option, + String, + Option, + Option, +); + +impl From for ModelRelease { + fn from(t: ReleaseTuple) -> Self { + ModelRelease { + id: t.0, + repo_id: t.1, + commit_sha: t.2, + branch: t.3, + publisher_did: t.4, + state: t.5, + manifest_sha256: t.6, + failure_reason: t.7, + created_at: t.8, + published_at: t.9, + request_digest: t.10, + } + } +} + +pub const RELEASE_COLS: &str = "id, repo_id, commit_sha, branch, publisher_did, \ + state, manifest_sha256, failure_reason, created_at, published_at, \ + claim_request_digest"; + +/// Fields of the signed claim persisted on the release row (the status-claim +/// pattern: the row is the replay ledger). +pub struct ClaimPersist { + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, + pub request_digest: String, +} + +impl Db { + pub async fn model_open_session( + &self, + owner_did: &str, + repo_id: &str, + ttl_secs: u64, + ) -> Result { + let id = hex::encode(rand::random::<[u8; 32]>()); + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1, $2, $3, $4, $5, 0, 'open') + RETURNING {SESSION_COLS}" + )) + .bind(&id) + .bind(owner_did) + .bind(repo_id) + .bind(ts_now()) + .bind(ts_from_now(ttl_secs as i64)) + .fetch_one(&self.pool) + .await?; + Ok(row.into()) + } + + pub async fn model_load_session(&self, id: &str) -> Result> { + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "SELECT {SESSION_COLS} FROM model_upload_sessions WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Atomically admit `claimed` bytes against the caller's per-identity + /// open-session cap and the node-wide quota, sliding expiry forward in + /// the same update. `None` when the session is closed, expired, or a cap + /// would be exceeded; the caller re-reads the session to pick the honest + /// denial. + pub async fn model_admit_bytes( + &self, + session_id: &str, + claimed: i64, + ttl_secs: u64, + session_cap: i64, + node_cap: i64, + ) -> Result> { + let row = sqlx::query_as::<_, SessionTuple>(&format!( + "UPDATE model_upload_sessions s + SET bytes_received = s.bytes_received + $1, + expires_at = $2 + WHERE s.id = $3 + AND s.state = 'open' + AND s.expires_at > $4 + AND s.bytes_received + $1 + COALESCE(( + SELECT SUM(o.bytes_received) FROM model_upload_sessions o + WHERE o.owner_did = s.owner_did AND o.state = 'open' AND o.id <> s.id + ), 0) <= $5 + AND COALESCE((SELECT SUM(q.bytes_used) FROM model_quota_usage q), 0) + + COALESCE(( + SELECT SUM(o2.bytes_received) FROM model_upload_sessions o2 + WHERE o2.state = 'open' + ), 0) + + $1 <= $6 + RETURNING {SESSION_COLS}" + )) + .bind(claimed) + .bind(ts_from_now(ttl_secs as i64)) + .bind(session_id) + .bind(ts_now()) + .bind(session_cap) + .bind(node_cap) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + /// Refund an admitted charge when the store or the bookkeeping fails. + /// Best-effort under races; an expired session frees the bytes anyway. + pub async fn model_refund_bytes(&self, session_id: &str, bytes: i64) -> Result<()> { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(bytes) + .bind(session_id) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Book the stored block against the session in one transaction. `true` + /// when this PUT was a duplicate within the session (the admission + /// credit was refunded). + pub async fn model_record_block( + &self, + session_id: &str, + block_sha: &str, + size: u64, + admitted: i64, + ) -> Result { + let mut tx = self.pool.begin().await?; + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at, unreferenced_since) + VALUES ($1, $2, $3, $3) + ON CONFLICT (sha256) DO NOTHING", + ) + .bind(block_sha) + .bind(size as i64) + .bind(ts_now()) + .execute(&mut *tx) + .await?; + let linked = sqlx::query( + "INSERT INTO model_session_blocks (session_id, block_sha256) + VALUES ($1, $2) + ON CONFLICT (session_id, block_sha256) DO NOTHING", + ) + .bind(session_id) + .bind(block_sha) + .execute(&mut *tx) + .await? + .rows_affected(); + if linked == 0 { + sqlx::query( + "UPDATE model_upload_sessions + SET bytes_received = GREATEST(bytes_received - $1, 0) + WHERE id = $2", + ) + .bind(admitted) + .bind(session_id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(linked == 0) + } + + pub async fn model_release_by_commit( + &self, + repo_id: &str, + commit: &str, + ) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_release_by_id(&self, id: i64) -> Result> { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE id = $1" + )) + .bind(id) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(Into::into)) + } + + pub async fn model_begin(&self) -> Result> { + Ok(self.pool.begin().await?) + } + + // ── claim transaction steps ─────────────────────────────────────────── + + pub async fn model_tx_advisory_lock( + &self, + tx: &mut Transaction<'_, Postgres>, + key: i64, + ) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(&mut **tx) + .await?; + Ok(()) + } + + pub async fn model_tx_release_by_digest( + &self, + tx: &mut Transaction<'_, Postgres>, + digest: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases WHERE claim_request_digest = $1" + )) + .bind(digest) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + pub async fn model_tx_release_by_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_as::<_, ReleaseTuple>(&format!( + "SELECT {RELEASE_COLS} FROM model_releases + WHERE repo_id = $1 AND commit_sha = $2" + )) + .bind(repo_id) + .bind(commit) + .fetch_optional(&mut **tx) + .await? + .map(Into::into)) + } + + /// Lock and return the present subset of `shas` (`FOR UPDATE` so a + /// racing sweep cannot delete a block mid-claim). + pub async fn model_tx_lock_present_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result> { + if shas.is_empty() { + return Ok(Vec::new()); + } + Ok( + sqlx::query_scalar("SELECT sha256 FROM model_blocks WHERE sha256 = ANY($1) FOR UPDATE") + .bind(shas) + .fetch_all(&mut **tx) + .await?, + ) + } + + pub async fn model_tx_session_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + owner_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sb.block_sha256 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE s.owner_did = $1 AND s.state = 'open'", + ) + .bind(owner_did) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_publisher_release_blocks( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.publisher_did = $1 AND r.state IN ('verifying', 'published')", + ) + .bind(publisher_did) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_release_blocks_at_commit( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + ) -> Result> { + Ok(sqlx::query_scalar( + "SELECT rb.block_sha256 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE r.repo_id = $1 AND r.commit_sha = $2 AND r.state = 'published'", + ) + .bind(repo_id) + .bind(commit) + .fetch_all(&mut **tx) + .await?) + } + + pub async fn model_tx_has_verifying( + &self, + tx: &mut Transaction<'_, Postgres>, + publisher_did: &str, + ) -> Result { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT id FROM model_releases + WHERE publisher_did = $1 AND state = 'verifying' LIMIT 1", + ) + .bind(publisher_did) + .fetch_optional(&mut **tx) + .await? + .is_some()) + } + + /// Bytes of `shas` not already referenced by any live release: the + /// first-claimer-pays charge. + pub async fn model_tx_unclaimed_bytes( + &self, + tx: &mut Transaction<'_, Postgres>, + shas: &[String], + ) -> Result { + if shas.is_empty() { + return Ok(0); + } + Ok(sqlx::query_scalar::<_, Option>( + "SELECT SUM(b.size) FROM model_blocks b + WHERE b.sha256 = ANY($1) + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published'))", + ) + .bind(shas) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + /// Atomic per-identity reservation; `None` when the cap would be + /// exceeded. + pub async fn model_tx_reserve_quota( + &self, + tx: &mut Transaction<'_, Postgres>, + did: &str, + delta: i64, + cap: i64, + ) -> Result> { + Ok(sqlx::query_scalar::<_, i64>( + "INSERT INTO model_quota_usage (did, bytes_used) VALUES ($1, $2) + ON CONFLICT (did) DO UPDATE + SET bytes_used = model_quota_usage.bytes_used + $2 + WHERE model_quota_usage.bytes_used + $2 <= $3 + RETURNING bytes_used", + ) + .bind(did) + .bind(delta) + .bind(cap) + .fetch_optional(&mut **tx) + .await?) + } + + /// Node-wide used bytes: claimed quota plus every open session's bytes. + pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions + WHERE state = 'open'), 0)", + ) + .fetch_one(&mut **tx) + .await? + .unwrap_or(0)) + } + + #[allow(clippy::too_many_arguments)] + pub async fn model_tx_insert_release( + &self, + tx: &mut Transaction<'_, Postgres>, + repo_id: &str, + commit: &str, + branch: &str, + publisher_did: &str, + manifest_sha256: &str, + reconstruction_sha256: Option<&str>, + claim: &ClaimPersist, + ) -> Result { + let row = sqlx::query_as::<_, ReleaseTuple>(&format!( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + reconstruction_sha256, claim_signature, claim_signature_input, + claim_signing_string, claim_body, claim_request_digest, created_at) + VALUES ($1,$2,$3,$4,'verifying',$5,$6,$7,$8,$9,$10,$11,$12) + RETURNING {RELEASE_COLS}" + )) + .bind(repo_id) + .bind(commit) + .bind(branch) + .bind(publisher_did) + .bind(manifest_sha256) + .bind(reconstruction_sha256) + .bind(&claim.signature) + .bind(&claim.signature_input) + .bind(&claim.signing_string) + .bind(&claim.body) + .bind(&claim.request_digest) + .bind(ts_now()) + .fetch_one(&mut **tx) + .await?; + Ok(row.into()) + } + + /// Link `sha` to the release and drop it from the publisher's open + /// sessions, so the same bytes stop counting twice node-wide. + pub async fn model_tx_link_release_block( + &self, + tx: &mut Transaction<'_, Postgres>, + release_id: i64, + publisher_did: &str, + sha: &str, + ) -> Result<()> { + sqlx::query( + "INSERT INTO model_release_blocks (release_id, block_sha256) + VALUES ($1, $2) ON CONFLICT DO NOTHING", + ) + .bind(release_id) + .bind(sha) + .execute(&mut **tx) + .await?; + sqlx::query( + "DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE s.id = sb.session_id AND s.owner_did = $1 + AND s.state = 'open' AND sb.block_sha256 = $2", + ) + .bind(publisher_did) + .bind(sha) + .execute(&mut **tx) + .await?; + Ok(()) + } + + pub async fn model_tx_recount_open_session_bytes( + &self, + tx: &mut Transaction<'_, Postgres>, + owner_did: &str, + ) -> Result<()> { + sqlx::query( + "UPDATE model_upload_sessions s + SET bytes_received = COALESCE(( + SELECT SUM(b.size) FROM model_session_blocks sb + JOIN model_blocks b ON b.sha256 = sb.block_sha256 + WHERE sb.session_id = s.id), 0) + WHERE s.owner_did = $1 AND s.state = 'open'", + ) + .bind(owner_did) + .execute(&mut **tx) + .await?; + Ok(()) + } + + // ── verification ─────────────────────────────────────────────────────── + + pub async fn model_mark_published(&self, release_id: i64) -> Result<()> { + sqlx::query( + "UPDATE model_releases + SET state = 'published', published_at = $2 + WHERE id = $1 AND state = 'verifying'", + ) + .bind(release_id) + .bind(ts_now()) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Reject: mark the release, drop its refs, and refund the publisher the + /// bytes no other live release still references. + pub async fn model_reject_release(&self, release_id: i64, reason: &str) -> Result<()> { + let mut tx = self.pool.begin().await?; + let released: Option<(String,)> = sqlx::query_as( + "UPDATE model_releases + SET state = 'rejected', failure_reason = $2 + WHERE id = $1 AND state = 'verifying' + RETURNING publisher_did", + ) + .bind(release_id) + .bind(reason) + .fetch_optional(&mut *tx) + .await?; + let Some((publisher,)) = released else { + tx.commit().await?; + return Ok(()); + }; + let freed: i64 = sqlx::query_scalar::<_, Option>( + "SELECT COALESCE(SUM(b.size), 0) FROM model_blocks b + JOIN model_release_blocks rb ON rb.block_sha256 = b.sha256 + WHERE rb.release_id = $1 + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks r2 + JOIN model_releases r ON r.id = r2.release_id + WHERE r2.block_sha256 = b.sha256 AND r2.release_id <> $1 + AND r.state IN ('verifying', 'published'))", + ) + .bind(release_id) + .fetch_one(&mut *tx) + .await? + .unwrap_or(0); + sqlx::query("DELETE FROM model_release_blocks WHERE release_id = $1") + .bind(release_id) + .execute(&mut *tx) + .await?; + if freed > 0 { + sqlx::query( + "UPDATE model_quota_usage SET bytes_used = GREATEST(bytes_used - $2, 0) + WHERE did = $1", + ) + .bind(&publisher) + .bind(freed) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(()) + } + + pub async fn model_verifying_ids(&self, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases WHERE state = 'verifying' + ORDER BY created_at LIMIT $1", + ) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + // ── sweep ────────────────────────────────────────────────────────────── + + pub async fn model_expire_sessions(&self) -> Result> { + Ok(sqlx::query_scalar( + "UPDATE model_upload_sessions SET state = 'expired' + WHERE state = 'open' AND expires_at <= $1 + RETURNING id", + ) + .bind(ts_now()) + .fetch_all(&self.pool) + .await?) + } + + pub async fn model_drop_session_blocks(&self, session_id: &str) -> Result<()> { + sqlx::query("DELETE FROM model_session_blocks WHERE session_id = $1") + .bind(session_id) + .execute(&self.pool) + .await?; + Ok(()) + } + + /// Stamp `unreferenced_since` on blocks that lost every live reference, + /// and clear it on blocks that regained one. Returns rows marked. + pub async fn model_remark_liveness(&self) -> Result { + let marked = sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = $1 + WHERE b.unreferenced_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open')", + ) + .bind(ts_now()) + .execute(&self.pool) + .await? + .rows_affected(); + sqlx::query( + "UPDATE model_blocks b SET unreferenced_since = NULL + WHERE b.unreferenced_since IS NOT NULL + AND (EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = b.sha256 + AND r.state IN ('verifying', 'published')) + OR EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = b.sha256 AND s.state = 'open'))", + ) + .execute(&self.pool) + .await?; + Ok(marked) + } + + pub async fn model_stale_blocks(&self, grace_secs: i64, limit: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT sha256 FROM model_blocks + WHERE unreferenced_since < $1 + LIMIT $2", + ) + .bind(ts_from_now(-grace_secs)) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + + /// Under the same row lock the claim path takes, confirm the block is + /// still unreferenced. The caller keeps the transaction open across the + /// store delete, then calls `model_tx_delete_block_row`. + pub async fn model_tx_block_still_dead( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + ) -> Result { + Ok(sqlx::query_scalar::<_, bool>( + "SELECT NOT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = $1 + AND r.state IN ('verifying', 'published')) + AND NOT EXISTS ( + SELECT 1 FROM model_session_blocks sb + JOIN model_upload_sessions s ON s.id = sb.session_id + WHERE sb.block_sha256 = $1 AND s.state = 'open') + FROM model_blocks b + WHERE b.sha256 = $1 FOR UPDATE", + ) + .bind(sha) + .fetch_optional(&mut **tx) + .await? + .unwrap_or(false)) + } + + pub async fn model_tx_delete_block_row( + &self, + tx: &mut Transaction<'_, Postgres>, + sha: &str, + ) -> Result<()> { + sqlx::query("DELETE FROM model_blocks WHERE sha256 = $1") + .bind(sha) + .execute(&mut **tx) + .await?; + Ok(()) + } +} + +/// The PgPool behind a `Db`, for test fixtures that seed rows directly. +#[cfg(any(test, feature = "test-harness"))] +pub fn test_pool(db: &Db) -> &PgPool { + db.pool() +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn migrated(pool: sqlx::PgPool) -> Db { + let db = Db::for_testing(pool.clone()); + db.run_migrations().await.unwrap(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ('r1', 'repo', 'did:owner', TRUE, 'main', 't', 't', '/r1')", + ) + .execute(&pool) + .await + .unwrap(); + db + } + + #[sqlx::test] + async fn admit_bytes_enforces_session_cap_and_slides_expiry(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let first = db + .model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); + assert_eq!(first.bytes_received, 100); + assert!(first.expires_at > s.expires_at || first.expires_at == s.expires_at); + // Over the per-identity session cap: refused. + assert!(db + .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) + .await + .unwrap() + .is_none()); + // Within the cap still admits. + assert!(db + .model_admit_bytes(&s.id, 900, 3600, 1000, 10_000) + .await + .unwrap() + .is_some()); + } + + #[sqlx::test] + async fn record_block_refunds_duplicate_within_session(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "a".repeat(64); + assert!(!db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + // Same block again: duplicate, admission refunded. + assert!(db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); + let s2 = db.model_load_session(&s.id).await.unwrap().unwrap(); + assert_eq!(s2.bytes_received, 0); + } + + #[sqlx::test] + async fn expire_then_sweep_marks_and_deletes_dead_blocks(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "b".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + // Blocks are born stamped; while the session is open, remarking + // clears the stamp. + db.model_remark_liveness().await.unwrap(); + let stamp: Option = + sqlx::query_scalar("SELECT unreferenced_since FROM model_blocks WHERE sha256 = $1") + .bind(&sha) + .fetch_one(&pool) + .await + .unwrap(); + assert!(stamp.is_none()); + + // Force the session expired and drop its links. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_expire_sessions().await.unwrap(), + vec![s.id.clone()] + ); + db.model_drop_session_blocks(&s.id).await.unwrap(); + + // The block is now unreferenced: marked, then deletable past grace. + assert_eq!(db.model_remark_liveness().await.unwrap(), 1); + sqlx::query("UPDATE model_blocks SET unreferenced_since = $1 WHERE sha256 = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + db.model_stale_blocks(3600, 10).await.unwrap(), + vec![sha.clone()] + ); + let mut tx = db.model_begin().await.unwrap(); + assert!(db.model_tx_block_still_dead(&mut tx, &sha).await.unwrap()); + db.model_tx_delete_block_row(&mut tx, &sha).await.unwrap(); + tx.commit().await.unwrap(); + } + + #[sqlx::test] + async fn release_blocks_keep_a_block_alive(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let sha = "c".repeat(64); + sqlx::query("INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 5, 't')") + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1','c1','main','did:owner','published','m','s','i','ss','\\x00','t') + RETURNING id", + ) + .execute(&pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar("SELECT id FROM model_releases WHERE repo_id = 'r1'") + .fetch_one(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1,$2)") + .bind(rid) + .bind(&sha) + .execute(&pool) + .await + .unwrap(); + // Live release reference: the block never goes stale. + assert_eq!(db.model_remark_liveness().await.unwrap(), 0); + assert!(db.model_stale_blocks(-1, 10).await.unwrap().is_empty()); + let mut tx = db.model_begin().await.unwrap(); + assert!(!db.model_tx_block_still_dead(&mut tx, &sha).await.unwrap()); + tx.commit().await.unwrap(); + } +} diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index bfedeb72..e330c0c1 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -348,7 +348,7 @@ pub async fn delete_marker_bounded( /// serving) or a live push's admission permits, lease, and write lock. /// `kill_on_drop(true)` makes the timeout real for these plumbing commands /// (no helper processes to reparent, unlike receive-pack's pack-objects). -async fn run_git_bounded( +pub(crate) async fn run_git_bounded( git_bin: &str, repo_path: &Path, args: &[&str], diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index d068d669..881632ec 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -22,6 +22,7 @@ mod graphql; mod icaptcha; mod ipfs_pin; mod metrics; +pub mod models; mod operator; mod p2p; mod pinata; @@ -914,6 +915,16 @@ pub async fn run() -> Result<()> { // with the one-shot reconcile/drain on backlog rows. let _due_request_worker = spawn_due_request_worker(&state); + // Model hosting workers (verify + sweep) only run while the operator + // flag is on; the block store is the flag's live form. + let mut model_workers = Vec::new(); + if state.block_store.is_some() { + model_workers.push(tokio::spawn(models::verify::run_verify_worker( + state.clone(), + ))); + model_workers.push(tokio::spawn(models::sweep::run_sweep_worker(state.clone()))); + } + // `into_make_service_with_connect_info` exposes the socket peer address as // `ConnectInfo` so the push limiter can key on the real client // when no trusted proxy header applies (see `rate_limit::client_key`). diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs new file mode 100644 index 00000000..5d92cca8 --- /dev/null +++ b/crates/twigpine-node/src/models/claim.rs @@ -0,0 +1,272 @@ +//! Release claim: the commit point. The ordered checks from KTD5 run here; +//! the check-then-act tail (other-verifying probe, quota reservation, release +//! insert) runs inside one transaction under the claim advisory lock. + +use twigpine_core::model::manifest::Manifest; + +use crate::db::model_queries::ClaimPersist; +use crate::db::RepoRecord; +use crate::error::AppError; +use crate::state::AppState; + +use super::{ReleaseRow, CLAIM_LOCK_KEY}; + +/// Everything the handler verified about the signed request, threaded so the +/// release row is the replay ledger: a replayed claim resolves by request +/// digest to the original row instead of writing a second one. +pub struct ClaimMaterial { + pub request_digest: String, + pub signature: String, + pub signature_input: String, + pub signing_string: String, + pub body: Vec, +} + +fn bad_request(msg: impl Into) -> AppError { + AppError::BadRequest(msg.into()) +} + +/// Read `commit:path` bytes from the repo on disk, bounded. +pub(crate) async fn git_show( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + path: &str, +) -> Result>, AppError> { + let spec = format!("{commit}:{path}"); + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["show", &spec], + b"", + std::time::Duration::from_secs(30), + "git show", + ) + .await + .map_err(AppError::Internal)?; + if out.status.success() { + return Ok(Some(out.stdout)); + } + match out.status.code() { + // Path missing inside a real commit: honest absence. + Some(128) => Ok(None), + _ => Err(AppError::Internal(anyhow::anyhow!( + "git show {spec} failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))), + } +} + +/// Whether commit `sha` resolves in the repo. +pub async fn commit_exists( + git_bin: &str, + disk_path: &std::path::Path, + sha: &str, +) -> Result { + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["cat-file", "-e", &format!("{sha}^{{commit}}")], + b"", + std::time::Duration::from_secs(30), + "git cat-file", + ) + .await + .map_err(AppError::Internal)?; + Ok(out.status.success()) +} + +/// Read and anchor-verify the release manifest at `commit`. The verifying key +/// comes from the repo owner DID (the independent anchor), never the artifact. +pub(crate) async fn read_verified_manifest( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, + owner_did: &str, +) -> Result<(Vec, Manifest), AppError> { + let manifest_bytes = git_show(git_bin, disk_path, commit, ".twigpine/model-release.json") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.json"))?; + let sig_text = git_show(git_bin, disk_path, commit, ".twigpine/model-release.sig") + .await? + .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; + let sig_text = + String::from_utf8(sig_text).map_err(|_| bad_request("model-release.sig is not utf-8"))?; + let did: twigpine_core::did::Did = owner_did + .parse() + .map_err(|_| bad_request("repo owner DID does not resolve"))?; + let manifest = twigpine_core::model::manifest::verify(&manifest_bytes, &sig_text, &did) + .map_err(|e| bad_request(format!("manifest signature rejected: {e}")))?; + Ok((manifest_bytes, manifest)) +} + +/// Claim `commit` on `branch` as a model release. The handler has already +/// proven the feature flag, the owner gate, and full publicity; everything +/// from the manifest read down runs here. +pub async fn claim_release( + state: &AppState, + record: &RepoRecord, + caller: &str, + commit: &str, + branch: &str, + material: &ClaimMaterial, +) -> Result { + let db = &state.db; + let disk_path = std::path::PathBuf::from(&record.disk_path); + + // The pushed commit must exist and carry the signed manifest. + if !commit_exists(&state.git_bin, &disk_path, commit).await? { + return Err(bad_request("commit not found in this repository")); + } + let (manifest_bytes, manifest) = + read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; + let m_sha = super::manifest_sha256(&manifest_bytes); + let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); + let blocks = super::referenced_blocks(state, &manifest).await?; + + let mut tx = db.model_begin().await?; + db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; + + // Replay by request digest, then idempotent re-claim by (repo, commit): + // both return the original row. + if let Some(existing) = db + .model_tx_release_by_digest(&mut tx, &material.request_digest) + .await? + { + tx.commit().await?; + return Ok(existing); + } + if let Some(existing) = db + .model_tx_release_by_commit(&mut tx, &record.id, commit) + .await? + { + tx.commit().await?; + return Ok(existing); + } + + // Lock the referenced block rows so a racing sweep cannot delete one + // mid-claim, and require each to exist. + if !blocks.is_empty() { + let present = db.model_tx_lock_present_blocks(&mut tx, &blocks).await?; + if let Some(missing) = blocks.iter().find(|b| !present.contains(b)) { + return Err(bad_request(format!( + "manifest references block {} which is not stored on this node", + &missing[..16] + ))); + } + } + + // Authorization: every referenced block must arrive through the caller's + // open session, a live release of the caller's, or the declared parent. + let caller_session_blocks = db.model_tx_session_blocks(&mut tx, caller).await?; + let caller_release_blocks = db + .model_tx_publisher_release_blocks(&mut tx, caller) + .await?; + let parent_blocks: Vec = match &manifest.parent { + None => Vec::new(), + Some(parent) => { + let (powner, pname) = parent + .repo + .split_once('/') + .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; + // A parent only confers blocks while its repo is fully public: + // a withdrawn parent cannot launder references. + let (precord, prules) = + crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; + if !precord.is_public || !prules.is_empty() { + return Err(bad_request( + "declared parent's repo is no longer fully public", + )); + } + let rows = db + .model_tx_release_blocks_at_commit(&mut tx, &precord.id, &parent.commit) + .await?; + if rows.is_empty() { + return Err(bad_request( + "declared parent is not a published release on this node", + )); + } + rows + } + }; + for b in &blocks { + let allowed = caller_session_blocks.contains(b) + || caller_release_blocks.contains(b) + || parent_blocks.contains(b); + if !allowed { + return Err(bad_request(format!( + "block {} is not reachable through an open session, a prior \ + release, or the declared parent", + &b[..16] + ))); + } + } + + // One verifying release per publisher. + if db.model_tx_has_verifying(&mut tx, caller).await? { + return Err(AppError::Conflict( + "another release is still verifying; wait for it to settle".into(), + )); + } + + // New bytes are the distinct blocks not already claimed by any live + // release anywhere: first claimer pays, dedup stays free. + let new_bytes = db.model_tx_unclaimed_bytes(&mut tx, &blocks).await?; + + // Per-identity quota, atomically. + let did_cap = state.config.model_quota_bytes as i64; + let admitted = db + .model_tx_reserve_quota(&mut tx, caller, new_bytes, did_cap) + .await?; + if new_bytes > 0 && admitted.is_none() { + return Err(bad_request(format!( + "per-publisher model quota ({did_cap} bytes) would be exceeded" + ))); + } + + // Node-wide quota in the same transaction: claimed bytes plus open + // session bytes. + let node_cap = state.config.model_node_quota_bytes as i64; + let node_total = db.model_tx_node_used(&mut tx).await?; + if node_total > node_cap { + return Err(AppError::TooManyRequests(format!( + "node model storage cap ({node_cap} bytes) would be exceeded" + ))); + } + + let persist = ClaimPersist { + signature: material.signature.clone(), + signature_input: material.signature_input.clone(), + signing_string: material.signing_string.clone(), + body: material.body.clone(), + request_digest: material.request_digest.clone(), + }; + let row = db + .model_tx_insert_release( + &mut tx, + &record.id, + commit, + branch, + caller, + &m_sha, + rec_sha.as_deref(), + &persist, + ) + .await?; + let release_id = row.id; + + for b in &blocks { + // Claimed blocks leave the caller's open sessions' charge: the + // release now carries them, so session bytes stop double-counting. + db.model_tx_link_release_block(&mut tx, release_id, caller, b) + .await?; + } + db.model_tx_recount_open_session_bytes(&mut tx, caller) + .await?; + + tx.commit().await?; + Ok(row) +} diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs new file mode 100644 index 00000000..ee45d2b5 --- /dev/null +++ b/crates/twigpine-node/src/models/mod.rs @@ -0,0 +1,173 @@ +//! Open-weight model hosting: upload sessions, release claims, verification, +//! and reclamation. Feature-gated by `model_hosting_enabled`; the routes are +//! mounted only when `state.block_store` is `Some`, and every handler +//! re-checks it. +//! +//! All SQL lives in `crate::db::model_queries` as typed `Db` methods; the +//! free functions here are the thin `&Db`-taking seams the handlers and +//! workers share. + +pub mod claim; +pub mod sweep; +pub mod verify; + +use std::sync::Arc; + +use crate::db::model_queries::{ModelRelease, ModelSession}; +use crate::db::Db; +use crate::error::AppError; +use crate::state::AppState; + +/// Transport + store hard cap on one block (KTD1: 64 MiB target, 128 MiB cap). +pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; + +/// Advisory-lock key serializing claim admission: the "one verifying release +/// per publisher" check and the quota reservations are check-then-act, so the +/// lock is what makes them safe under racing claims. +pub(crate) const CLAIM_LOCK_KEY: i64 = 0x6D6F64656C636C61; // "modelcla" + +pub type SessionRow = ModelSession; +pub type ReleaseRow = ModelRelease; + +/// rfc3339 UTC `secs` from now: the repo's TEXT timestamp convention. +pub fn ts_from_now(secs: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() +} + +pub fn ts_now() -> String { + chrono::Utc::now().to_rfc3339() +} + +/// 256-bit random session id, hex-encoded: the bearer capability for block +/// PUTs. Anyone holding it may append blocks to the session it names, so it +/// is never logged or returned to anyone but its creator. +pub fn new_session_id() -> String { + hex::encode(rand::random::<[u8; 32]>()) +} + +pub async fn open_session( + db: &Db, + owner_did: &str, + repo_id: &str, + ttl_secs: u64, +) -> Result { + Ok(db.model_open_session(owner_did, repo_id, ttl_secs).await?) +} + +pub async fn load_session(db: &Db, id: &str) -> Result, AppError> { + Ok(db.model_load_session(id).await?) +} + +/// Atomically admit `claimed` bytes against the caller's per-identity +/// open-session cap and the node-wide quota (claimed quota plus every open +/// session's bytes), sliding the session's expiry forward in the same +/// update. Returns the post-update row when admitted, `None` when the +/// session is closed, expired, or the admission would exceed a cap; the +/// caller re-checks the session to pick the honest denial. +pub async fn admit_bytes( + db: &Db, + session_id: &str, + claimed: i64, + ttl_secs: u64, + session_cap: i64, + node_cap: i64, +) -> Result, AppError> { + Ok(db + .model_admit_bytes(session_id, claimed, ttl_secs, session_cap, node_cap) + .await?) +} + +/// Refund a previously admitted charge when the store or the bookkeeping +/// fails. Best-effort under races; an expired session frees the bytes anyway. +pub async fn refund_bytes(db: &Db, session_id: &str, bytes: i64) -> Result<(), AppError> { + db.model_refund_bytes(session_id, bytes).await?; + Ok(()) +} + +/// Book the stored block against the session inside one transaction. Returns +/// `true` when this PUT was a duplicate within the session (the admission +/// credit was refunded). +pub async fn record_block( + db: &Db, + session_id: &str, + block_sha: &str, + size: u64, + admitted: i64, +) -> Result { + Ok(db + .model_record_block(session_id, block_sha, size, admitted) + .await?) +} + +pub async fn release_by_commit( + db: &Db, + repo_id: &str, + commit: &str, +) -> Result, AppError> { + Ok(db.model_release_by_commit(repo_id, commit).await?) +} + +pub async fn release_by_id(db: &Db, id: i64) -> Result, AppError> { + Ok(db.model_release_by_id(id).await?) +} + +/// sha256 of the manifest bytes, as hex. +pub fn manifest_sha256(manifest_bytes: &[u8]) -> String { + use sha2::Digest; + hex::encode(sha2::Sha256::digest(manifest_bytes)) +} + +/// Collect `len` bytes of a stored object starting at `start`. +pub async fn read_range( + store: &Arc, + sha: &str, + start: u64, + len: u64, +) -> Result, crate::blockstore::BlockStoreError> { + use futures::StreamExt; + let id = crate::blockstore::BlockId::parse(sha) + .map_err(|e| crate::blockstore::BlockStoreError::Backend(e.to_string()))?; + let mut stream = store.get_range(&id, start, start + len).await?; + let mut out = Vec::with_capacity(len.min(1 << 22) as usize); + while let Some(chunk) = stream.next().await { + out.extend_from_slice(&chunk?); + } + Ok(out) +} + +/// Collect a stored object's whole body via a range read. +pub async fn read_block( + store: &Arc, + sha: &str, + size: u64, +) -> Result, crate::blockstore::BlockStoreError> { + read_range(store, sha, 0, size).await +} + +/// The set of blocks a manifest references: the reconstruction object itself +/// (stored as its own content block) plus every data block the parsed +/// reconstruction names. The reconstruction object is read from the block +/// store and validated before its block table is trusted. +pub async fn referenced_blocks( + state: &AppState, + manifest: &twigpine_core::model::manifest::Manifest, +) -> Result, AppError> { + use twigpine_core::model::reconstruction::Reconstruction; + let Some(rec_ref) = &manifest.reconstruction else { + return Ok(Vec::new()); + }; + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::NotFound("model hosting is not enabled".into()))?; + let bytes = read_block(&store, &rec_ref.sha256, rec_ref.size) + .await + .map_err(|e| AppError::BadRequest(format!("reconstruction object unreadable: {e}")))?; + let rec = Reconstruction::parse(&bytes) + .map_err(|e| AppError::BadRequest(format!("reconstruction object invalid: {e}")))?; + let mut out = vec![rec_ref.sha256.clone()]; + for b in &rec.blocks { + out.push(b.sha256.clone()); + } + Ok(out) +} diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs new file mode 100644 index 00000000..edf12187 --- /dev/null +++ b/crates/twigpine-node/src/models/sweep.rs @@ -0,0 +1,80 @@ +//! Reclamation: expire upload sessions, drop their block links, mark blocks +//! unreferenced, and delete unreferenced blocks after the unclaimed grace +//! period. Blocks referenced by a live release or an open session survive. +//! The claim path locks block rows (`FOR UPDATE`) before referencing them, +//! and the sweep's delete candidate is re-checked inside its own +//! transaction, so a claim in flight can never lose a block mid-reference. + +use crate::error::AppError; +use crate::state::AppState; + +#[derive(Debug, Default)] +pub struct SweepStats { + pub sessions_expired: u64, + pub blocks_marked: u64, + pub blocks_deleted: u64, +} + +/// One sweep pass. Exposed for tests; the worker calls it on a tick. +pub async fn sweep_once(state: &AppState) -> Result { + let db = &state.db; + let mut stats = SweepStats::default(); + + // Expire sessions past TTL, then drop their block links: an expired + // session no longer confers liveness. + let expired = db.model_expire_sessions().await?; + stats.sessions_expired = expired.len() as u64; + for sid in &expired { + db.model_drop_session_blocks(sid).await?; + } + + // Re-mark liveness both ways: blocks that lost every live reference get + // an unreferenced_since stamp; blocks that regained one clear theirs. + stats.blocks_marked = db.model_remark_liveness().await?; + + // Delete blocks past the grace period. The store object goes first so a + // crash leaves a dangling row (an honest "missing" at next claim) rather + // than an untracked object the sweep can never find again. + let grace = state.config.model_unclaimed_ttl_secs as i64; + let stale = db.model_stale_blocks(grace, 128).await?; + let Some(store) = state.block_store.clone() else { + return Ok(stats); + }; + for sha in stale { + // Re-check liveness under the row lock the claim path also takes, + // held across the store delete so a racing claim blocks rather than + // wins a reference to an object we just removed. + let mut tx = db.model_begin().await?; + if !db.model_tx_block_still_dead(&mut tx, &sha).await? { + tx.commit().await?; + continue; + } + let Ok(id) = crate::blockstore::BlockId::parse(&sha) else { + tx.commit().await?; + continue; + }; + match store.delete(&id).await { + Ok(()) | Err(crate::blockstore::BlockStoreError::NotFound) => {} + Err(e) => { + tracing::warn!("block {sha} store delete failed: {e}"); + tx.commit().await?; + continue; + } + } + db.model_tx_delete_block_row(&mut tx, &sha).await?; + tx.commit().await?; + stats.blocks_deleted += 1; + } + Ok(stats) +} + +/// Periodic sweep; spawned once when model hosting is enabled. +pub async fn run_sweep_worker(state: AppState) { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); + loop { + interval.tick().await; + if let Err(e) = sweep_once(&state).await { + tracing::warn!("model sweep failed: {e}"); + } + } +} diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs new file mode 100644 index 00000000..118ecc5a --- /dev/null +++ b/crates/twigpine-node/src/models/verify.rs @@ -0,0 +1,307 @@ +//! Release verification: rebuild every chunk-stored file, hash it against +//! the manifest, check the declared format against detected bytes, and only +//! then mark the release published (and pin the hidden ref). Rejection frees +//! the quota reservation and drops the block refs. + +use sha2::Digest; +use std::io::Write; +use twigpine_core::model::manifest::{detect_format, StorageKind}; +use twigpine_core::model::reconstruction::{rebuild_file, Reconstruction}; + +use crate::error::AppError; +use crate::state::AppState; + +/// Sink hashing rebuilt bytes and keeping the head for format detection. +struct VerifySink { + hasher: sha2::Sha256, + head: Vec, + digest: Option, +} + +impl Write for VerifySink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.hasher.update(buf); + if self.head.len() < 64 { + let take = (64 - self.head.len()).min(buf.len()); + self.head.extend_from_slice(&buf[..take]); + } + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Verify one release end to end. Idempotent: a release no longer in +/// `verifying` returns immediately. +pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), AppError> { + let Some(release) = super::release_by_id(&state.db, release_id).await? else { + return Ok(()); + }; + if release.state != "verifying" { + return Ok(()); + } + + // The repo must still be fully public: a repo turned private or given + // visibility rules mid-verification never publishes. + let record = state + .db + .get_repo_by_id(&release.repo_id) + .await? + .ok_or_else(|| AppError::NotFound("repo gone".into()))?; + let rules = state.db.list_visibility_rules(&record.id).await?; + if !record.is_public || !rules.is_empty() { + return reject_release(state, release_id, "repository is no longer fully public").await; + } + + let disk_path = std::path::PathBuf::from(&record.disk_path); + let (manifest_bytes, manifest) = match super::claim::read_verified_manifest( + &state.git_bin, + &disk_path, + &release.commit_sha, + &record.owner_did, + ) + .await + { + Ok(v) => v, + Err(e) => { + return reject_release(state, release_id, &format!("manifest re-check failed: {e}")) + .await; + } + }; + if super::manifest_sha256(&manifest_bytes) != release.manifest_sha256 { + return reject_release(state, release_id, "manifest digest changed since claim").await; + } + + let Some(rec_ref) = &manifest.reconstruction else { + return reject_release(state, release_id, "manifest has no reconstruction object").await; + }; + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object unreadable: {e}"), + ) + .await; + } + }; + let rec = match Reconstruction::parse(&rec_bytes) { + Ok(r) => r, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object invalid: {e}"), + ) + .await; + } + }; + + for file in &manifest.files { + match file.storage { + StorageKind::Chunked => { + let Some(entry) = rec.files.iter().find(|f| f.path == file.path).cloned() else { + return reject_release( + state, + release_id, + &format!("reconstruction object has no entry for {}", file.path), + ) + .await; + }; + if entry.sha256 != file.sha256 || entry.size != file.size { + return reject_release( + state, + release_id, + &format!("{}: reconstruction disagrees with the manifest", file.path), + ) + .await; + } + // The rebuild runs on the blocking pool: `rebuild_file` is a + // sync walker over a range-fetch callback, and the store is + // async. block_on inside spawn_blocking is honest — the + // fetch itself is chunk-sized and bounded. + let store2 = store.clone(); + let rec2 = rec.clone(); + let path = file.path.clone(); + let declared = file.format; + let built = tokio::task::spawn_blocking(move || { + let mut sink = VerifySink { + hasher: sha2::Sha256::new(), + head: Vec::new(), + digest: None, + }; + let mut fetch = |block: &str, off: u64, len: u64| -> std::io::Result> { + let store3 = store2.clone(); + let block = block.to_string(); + futures::executor::block_on(async move { + super::read_range(&store3, &block, off, len).await + }) + .map_err(|e| std::io::Error::other(e.to_string())) + }; + rebuild_file(&entry, &rec2, &mut fetch, &mut sink)?; + sink.digest = Some(hex::encode(sink.hasher.clone().finalize())); + Ok::<_, twigpine_core::model::reconstruction::ModelError>(( + sink, path, declared, + )) + }) + .await; + let (sink, path, declared) = match built { + Ok(Ok(v)) => v, + Ok(Err(e)) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + Err(e) => return Err(AppError::Internal(e.into())), + }; + if sink.digest.as_deref() != Some(file.sha256.as_str()) { + return reject_release( + state, + release_id, + &format!( + "{}: rebuilt bytes hash to {}", + path, + sink.digest.unwrap_or_default() + ), + ) + .await; + } + let detected = detect_format(&sink.head, &path); + if detected != declared { + return reject_release( + state, + release_id, + &format!( + "{path}: declared format {declared:?} but bytes detect as {detected:?}" + ), + ) + .await; + } + } + StorageKind::Git => { + match super::claim::git_show( + &state.git_bin, + &disk_path, + &release.commit_sha, + &file.path, + ) + .await + { + Ok(Some(bytes)) => { + let got = hex::encode(sha2::Sha256::digest(&bytes)); + if got != file.sha256 || bytes.len() as u64 != file.size { + return reject_release( + state, + release_id, + &format!("{}: git blob does not match the manifest", file.path), + ) + .await; + } + let detected = detect_format(&bytes[..bytes.len().min(64)], &file.path); + if detected != file.format { + return reject_release( + state, + release_id, + &format!( + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected + ), + ) + .await; + } + } + Ok(None) => { + return reject_release( + state, + release_id, + &format!("{}: not present in the claimed commit", file.path), + ) + .await; + } + Err(e) => return Err(e), + } + } + } + } + + // Publish: hidden ref first, then the state flip, so a crash leaves a + // verifying row the worker retries rather than a dangling ref. + write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; + state.db.model_mark_published(release_id).await?; + Ok(()) +} + +/// `refs/gitlawb/releases/` -> the release commit itself: reachable, +/// so `gc` never prunes it, and hidden under the gitlawb ref namespace. +pub async fn write_release_ref( + git_bin: &str, + disk_path: &std::path::Path, + commit: &str, +) -> Result<(), AppError> { + let out = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &[ + "update-ref", + &format!("refs/gitlawb/releases/{commit}"), + commit, + ], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await + .map_err(AppError::Internal)?; + if !out.status.success() { + return Err(AppError::Internal(anyhow::anyhow!( + "git update-ref failed: {}", + String::from_utf8_lossy(&out.stderr) + .chars() + .take(256) + .collect::() + ))); + } + Ok(()) +} + +/// Reject a release: drop its block refs, release the quota it reserved for +/// blocks no other live release still references, and record the reason. +pub async fn reject_release( + state: &AppState, + release_id: i64, + reason: &str, +) -> Result<(), AppError> { + state.db.model_reject_release(release_id, reason).await?; + tracing::info!(release_id, %reason, "model release rejected"); + Ok(()) +} + +/// Poll for `verifying` releases and verify them in order. Spawned once per +/// node when model hosting is enabled. +pub async fn run_verify_worker(state: AppState) { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); + loop { + interval.tick().await; + let ids = match state.db.model_verifying_ids(4).await { + Ok(v) => v, + Err(e) => { + tracing::warn!("model verify worker query failed: {e}"); + continue; + } + }; + for id in ids { + if let Err(e) = verify_release(&state, id).await { + tracing::warn!("model release {id} verification errored: {e}"); + } + } + } +} diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 64c6f56a..e8f66d33 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -14,8 +14,9 @@ use tower_http::trace::{DefaultOnFailure, DefaultOnResponse, TraceLayer}; use tracing::Level; use crate::api::{ - agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, peers, profiles, - protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, webhooks, + agents, arweave, bounties, certs, changelog, events, ipfs, issues, labels, models, peers, + profiles, protect, pulls, register, replicas, repos, resolve, stars, status, tasks, visibility, + webhooks, }; use crate::auth; use crate::rate_limit; @@ -762,6 +763,72 @@ pub fn build_router(state: AppState) -> Router { auth::optional_signature, )); + // ── Model hosting routes ───────────────────────────────────────────── + // Mounted only when the operator enabled the feature (`block_store` is + // the flag's live form). Three surfaces with three different auth + // shapes: + // - session open + session status: signed, owner-only. + // - claims: signed, persists the request material and owns its replay + // defense exactly like status claims. + // - block PUT: unsigned by design — the session id is the bearer + // credential and a signed 128 MiB body would have to be buffered + // whole to verify. Default body limit off, explicit block cap, same + // per-IP write brake as the other write surfaces. + let model_routes = if state.block_store.is_some() { + let signed = add_auth_layers( + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions", + post(models::open_model_session), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + get(models::get_model_session), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .write_braked(&write_ip_limiter); + let claims = add_auth_layers( + Router::new().route( + "/api/v1/repos/{owner}/{repo}/models/claims", + post(models::claim_model_release), + ), + state.clone(), + SIGNED_BODY_LIMIT, + ) + .layer(RequestBodyLimitLayer::new(status::MAX_REQUEST_BODY_BYTES)) + .layer(axum::Extension(auth::PersistsSignedBody)) + .layer(axum::Extension(auth::OwnsReplayDefense)) + .write_braked(&write_ip_limiter); + let blocks = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/blocks/{sha256}", + axum::routing::put(models::put_model_block), + ) + .layer(DefaultBodyLimit::disable()) + .layer(RequestBodyLimitLayer::new( + crate::models::MAX_BLOCK_BYTES as usize, + )) + .write_braked(&write_ip_limiter); + let reads = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + get(models::get_model_release), + ) + .route( + "/api/v1/repos/{owner}/{repo}/models/releases/{sha}/reconstruction", + get(models::get_model_reconstruction), + ) + .layer(middleware::from_fn_with_state( + auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), + auth::optional_signature, + )); + signed.merge(claims).merge(blocks).merge(reads) + } else { + Router::new() + }; + // ── Meta ────────────────────────────────────────────────────────────── let meta_routes = Router::new() .route("/", get(node_info)) @@ -791,6 +858,7 @@ pub fn build_router(state: AppState) -> Router { .merge(sync_trigger_routes) .merge(ipfs_routes) .merge(arweave_routes) + .merge(model_routes) .merge(meta_routes) .layer( TraceLayer::new_for_http() diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 21ec3d8d..9032eca0 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -176,6 +176,15 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS task_tx.clone(), task_cursor_key.clone(), )); + // Model hosting is ON for the harness node: a filesystem block store in a + // temp dir mounts the model routes so the deny sweep can drive their + // gates for real. Writes land inside the node's per-test repos dir and + // are removed with it. + let block_dir = repos_dir.join("model-blocks"); + std::fs::create_dir_all(&block_dir).expect("create temp block dir"); + let block_store: Option> = Some(Arc::new( + crate::blockstore::fs::FsBlockStore::new(block_dir).expect("fs block store"), + )); AppState { config: Arc::new(Config::parse_from(["twigpine-node"])), db, @@ -228,7 +237,7 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS 16, ), git_bin: "git".to_string(), - block_store: None, + block_store, } } @@ -371,9 +380,50 @@ impl TestNode { record.id } + /// Seed a published model release row directly, bypassing the claim + /// pipeline: deny fixtures need a real row behind the read gate, not the + /// full upload-and-verify path. + pub async fn seed_model_release(&self, repo_id: &str, commit_sha: &str, publisher_did: &str) { + sqlx::query( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ($1,$2,'main',$3,'published',$4,'sig','input','signing',\ + decode('00','hex'),$5)", + ) + .bind(repo_id) + .bind(commit_sha) + .bind(publisher_did) + .bind(format!("{commit_sha:0>64}")) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model release"); + } + + /// Seed an open model upload session row directly (see + /// [`Self::seed_model_release`]): the session-status read row's owner + /// twin needs a real session behind the gate. + pub async fn seed_model_session(&self, repo_id: &str, session_id: &str, owner_did: &str) { + sqlx::query( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1,$2,$3,$4,$5,0,'open')", + ) + .bind(session_id) + .bind(owner_did) + .bind(repo_id) + .bind(chrono::Utc::now().to_rfc3339()) + .bind((chrono::Utc::now() + chrono::Duration::hours(12)).to_rfc3339()) + .execute(self.db.pool()) + .await + .expect("seed model session"); + } + /// Mark `branch` as protected on `repo_id`, so a non-owner push to it is /// rejected by the branch-protection gate (used by the deny-prober's - /// protected-push probe — #195, F3). + /// protected-push probe, #195 F3). pub async fn seed_protected_branch(&self, repo_id: &str, branch: &str, created_by: &str) { self.db .protect_branch(repo_id, branch, created_by) diff --git a/crates/twigpine-node/tests/deny_harness.rs b/crates/twigpine-node/tests/deny_harness.rs index 26b0c0d7..76acf4cb 100644 --- a/crates/twigpine-node/tests/deny_harness.rs +++ b/crates/twigpine-node/tests/deny_harness.rs @@ -1429,6 +1429,24 @@ mod completeness { ("git_upload_pack", NotDrivenReason::GitSmartHttpRead), // Global list-FILTER: 200 with unreadable rows removed, never a 404. ("list_all_bounties", NotDrivenReason::GlobalListFilter), + // Model hosting writes: the session open, claim, and unsigned block + // PUT all read-gate the repo before their own credential checks. None + // is a 404-deny GET; the owner-gate rows drive the signed writes, and + // the bearer-session PUT's denies are covered by the models unit + // tests (a session row cannot be seeded through the public API for + // the stranger leg). + ("open_model_session", NotDrivenReason::ReadGatingMutation), + ("claim_model_release", NotDrivenReason::ReadGatingMutation), + ("put_model_block", NotDrivenReason::ReadGatingMutation), + // get_model_reconstruction's owner-2xx twin needs a completed claim: + // a signed manifest commit in git plus a real reconstruction object + // in the block store, substrate the fixture cannot seed through the + // public API. Its hostile 404 is still what a caller sees; only the + // twin lacks a drivable 2xx. + ( + "get_model_reconstruction", + NotDrivenReason::ExternalDependencyUnavailable, + ), ]; /// Every `.route("", ()…)` mount in `src`, as diff --git a/crates/twigpine-node/tests/support/probe.rs b/crates/twigpine-node/tests/support/probe.rs index 9e27520d..a7fdbbca 100644 --- a/crates/twigpine-node/tests/support/probe.rs +++ b/crates/twigpine-node/tests/support/probe.rs @@ -256,6 +256,21 @@ impl Fixture { let priv_bounty_id = seed_private_bounty(node, &owner, &owner_did, priv_repo, &bounty_marker).await; + // Model hosting is mounted on the harness node (an fs block store in + // the per-test repos dir). The model-release read row fills `{sha}` + // with 40 a's, so seed that commit as a published release on the + // private repo: anon/stranger get the existence-hiding 404, the owner + // twin gets a 200 proving the gate. + node.seed_model_release( + &private_repo_id, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + &owner_did, + ) + .await; + // The session-status read row fills `{id}` with the fixed "1". + node.seed_model_session(&private_repo_id, "1", &owner_did) + .await; + let priv_markers = vec![issue_marker, pr_marker, pr_diff_marker, bounty_marker]; // #195 (F3): seed the caller-self task entities through the real task write diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 61ddf428..07f8c411 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -1030,6 +1030,84 @@ pub fn deny_bearing_routes() -> &'static [Row] { id_source: IdSource::FailableTaskId, anon_read: AnonRead::Deny404, }, + // ── Model hosting (U5/U6). Session open and release claim are signed + // owner-gated writes behind the shared read gate; the session-status + // GET is doubly gated like list_webhooks (OwnerGate + ReadGate rows). + // The unsigned block PUT's bearer session is its credential, and the + // release/reconstruction reads are plain read-gated 404-deny GETs. + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/sessions", + gate: GateClass::OwnerGate, + handler: "models::open_model_session", + // Option> accepts an empty object; the owner + // twin then creates a session (201, Not403). + body: Some(r#"{}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + Row { + method: "POST", + path: "/api/v1/repos/{owner}/{repo}/models/claims", + gate: GateClass::OwnerGate, + handler: "models::claim_model_release", + // A well-formed claim body; the owner twin passes the owner gate and + // fails the commit lookup (400), which is still a Not403 twin. + body: Some(r#"{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","branch":"main"}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Session status: a signed stranger on the PUBLIC repo passes the read + // gate and hits require_repo_owner (403); the owner gets a 404 on the + // absent session (Not403). The read layer is the ReadGate row below. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::OwnerGate, + handler: "models::get_model_session", + body: None, + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, + // Same path, READ layer: anon gets 401 (the route requires a signature), + // a signed non-reader of the private repo gets the existence-hiding 404, + // and the owner reads the session the fixture seeded as id "1". + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/sessions/{id}", + gate: GateClass::ReadGate, + handler: "models::get_model_session", + body: None, + needs: &["model_session"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny401, + }, + // Release status: optional-signature read. The fixture seeds a published + // release on the private repo under commit 40 a's (the {sha} fill), so + // anon/stranger get the existence-hiding 404 and the owner gets a 200. + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/models/releases/{sha}", + gate: GateClass::ReadGate, + handler: "models::get_model_release", + body: None, + needs: &["model_release"], + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, // The read-gate handlers NOT driven here (deferred GET reads, read-gating // mutations, git smart-HTTP reads, the content-addressed read, and the // global list-filters) are no longer tracked by free-text prose: they are From 440a7cffce5d6d3efa08bfa4ac9cb04711df4544 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:33:26 -0600 Subject: [PATCH 13/53] fix(node): cap the first claim's quota reservation too INSERT ... ON CONFLICT DO UPDATE only applies its WHERE to the update branch, so a DID's first claim inserted bytes_used over the cap unchecked. Gate the insert attempt with SELECT ... WHERE. --- crates/twigpine-node/src/db/model_queries.rs | 47 +++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 9a5a1eb6..c49311c2 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -423,7 +423,9 @@ impl Db { } /// Atomic per-identity reservation; `None` when the cap would be - /// exceeded. + /// exceeded. The cap applies on BOTH branches: a `WHERE` inside `DO + /// UPDATE` alone would let a first-time DID insert any `delta`, since + /// that clause never guards the insert attempt. pub async fn model_tx_reserve_quota( &self, tx: &mut Transaction<'_, Postgres>, @@ -432,7 +434,8 @@ impl Db { cap: i64, ) -> Result> { Ok(sqlx::query_scalar::<_, i64>( - "INSERT INTO model_quota_usage (did, bytes_used) VALUES ($1, $2) + "INSERT INTO model_quota_usage (did, bytes_used) + SELECT $1, $2 WHERE $2 <= $3 ON CONFLICT (did) DO UPDATE SET bytes_used = model_quota_usage.bytes_used + $2 WHERE model_quota_usage.bytes_used + $2 <= $3 @@ -848,6 +851,46 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn reserve_quota_caps_first_and_later_claims(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // First claim over cap: refused, and no row may be left behind. + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 2000, 1000) + .await + .unwrap() + .is_none()); + tx.commit().await.unwrap(); + let row: Option = sqlx::query_scalar( + "SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'", + ) + .fetch_optional(&pool) + .await + .unwrap(); + assert!(row.is_none()); + // Within cap inserts, over-cap update refuses, within-cap update adds. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 600, 1000) + .await + .unwrap(), + Some(600) + ); + assert!(db + .model_tx_reserve_quota(&mut tx, "did:owner", 500, 1000) + .await + .unwrap() + .is_none()); + assert_eq!( + db.model_tx_reserve_quota(&mut tx, "did:owner", 400, 1000) + .await + .unwrap(), + Some(1000) + ); + tx.commit().await.unwrap(); + } + #[sqlx::test] async fn release_blocks_keep_a_block_alive(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; From 20fb3c3cb09e797ce6bfbe73264126d84763e8aa Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:34:12 -0600 Subject: [PATCH 14/53] fix(node): hide release refs from clone advertisement Published model releases pin their commits under refs/gitlawb/releases/; advertise them like the requests namespace and every clone fetches internal bookkeeping. --- crates/twigpine-node/src/git/store.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index e330c0c1..52da7912 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -91,10 +91,14 @@ pub fn init_bare(path: &Path) -> Result<()> { // Hide the internal marker namespace from clone/fetch // advertisement. `refs/gitlawb/requests/*` carries request UUIDs // and would otherwise leak per-push metadata to every client and - // grow advertisement cost with push count. + // grow advertisement cost with push count. `refs/gitlawb/releases/*` + // pins published model releases so gc never prunes them; it is + // likewise not for clients. for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { // allow-unbounded-git: same init-time local `git config` as above. let out = Command::new("git") @@ -129,6 +133,8 @@ pub fn ensure_marker_hidden_checked(repo_path: &Path) -> Result<()> { for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { // allow-unbounded-git: reached only through the #[allow(dead_code)] // ensure_marker_hidden wrapper; the push path runs this config through @@ -215,6 +221,8 @@ pub async fn verify_recovery_prereqs_bounded( for (key, value) in [ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), ] { let current = run_git(git_bin, repo_path, &["config", "--get-all", key], timeout).await?; let already = String::from_utf8_lossy(¤t.stdout) From b26307583d9e864472dcb55909bb27c3edda7136 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:34:48 -0600 Subject: [PATCH 15/53] fix(node): stop block ingest when a repo leaves full publicity authorize_repo_read always lets an owner read their own repo, so a session kept accepting bytes after the repo went private. Refuse the PUT alongside the other session-dead cases. --- crates/twigpine-node/src/api/models.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index e916da1b..c2802ab0 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -136,12 +136,16 @@ pub async fn put_model_block( }; // authorize_repo_read 404s a repo the session owner can no longer read; // the session-to-repo binding check below keeps foreign-session PUTs - // indistinguishable from a missing session. - let (record, _rules) = + // indistinguishable from a missing session. The owner always reads their + // own repo, so the fully-public check is what stops bytes landing on a + // repo that turned private or gained visibility rules mid-upload. + let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; if session.repo_id != record.id || session.state != "open" || session.expires_at <= models::ts_now() + || !record.is_public + || !rules.is_empty() { return Err(AppError::NotFound("model upload session not found".into())); } From 4ed781e501aa9a66c5cdbc5a903cd1f3d63e105c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:36:04 -0600 Subject: [PATCH 16/53] style(node): apply rustfmt to the quota test --- crates/twigpine-node/src/db/model_queries.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c49311c2..fe77992e 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -862,12 +862,11 @@ mod tests { .unwrap() .is_none()); tx.commit().await.unwrap(); - let row: Option = sqlx::query_scalar( - "SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'", - ) - .fetch_optional(&pool) - .await - .unwrap(); + let row: Option = + sqlx::query_scalar("SELECT bytes_used FROM model_quota_usage WHERE did = 'did:owner'") + .fetch_optional(&pool) + .await + .unwrap(); assert!(row.is_none()); // Within cap inserts, over-cap update refuses, within-cap update adds. let mut tx = db.model_begin().await.unwrap(); From e2607f9b57765b1a943b7654ac6bafd91a9ae0b8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:41:19 -0600 Subject: [PATCH 17/53] fix(node): rebuild releases with async range reads The verify worker ran rebuild_file inside spawn_blocking with futures::executor::block_on per fetch, which panics on the S3 backend whose client needs a tokio reactor. Walk map_file_range's ordered slices and await each read instead. --- crates/twigpine-node/src/models/verify.rs | 88 +++++++++++------------ 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 118ecc5a..b26272b8 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -6,7 +6,7 @@ use sha2::Digest; use std::io::Write; use twigpine_core::model::manifest::{detect_format, StorageKind}; -use twigpine_core::model::reconstruction::{rebuild_file, Reconstruction}; +use twigpine_core::model::reconstruction::Reconstruction; use crate::error::AppError; use crate::state::AppState; @@ -15,7 +15,6 @@ use crate::state::AppState; struct VerifySink { hasher: sha2::Sha256, head: Vec, - digest: Option, } impl Write for VerifySink { @@ -122,38 +121,15 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App ) .await; } - // The rebuild runs on the blocking pool: `rebuild_file` is a - // sync walker over a range-fetch callback, and the store is - // async. block_on inside spawn_blocking is honest — the - // fetch itself is chunk-sized and bounded. - let store2 = store.clone(); - let rec2 = rec.clone(); - let path = file.path.clone(); - let declared = file.format; - let built = tokio::task::spawn_blocking(move || { - let mut sink = VerifySink { - hasher: sha2::Sha256::new(), - head: Vec::new(), - digest: None, - }; - let mut fetch = |block: &str, off: u64, len: u64| -> std::io::Result> { - let store3 = store2.clone(); - let block = block.to_string(); - futures::executor::block_on(async move { - super::read_range(&store3, &block, off, len).await - }) - .map_err(|e| std::io::Error::other(e.to_string())) - }; - rebuild_file(&entry, &rec2, &mut fetch, &mut sink)?; - sink.digest = Some(hex::encode(sink.hasher.clone().finalize())); - Ok::<_, twigpine_core::model::reconstruction::ModelError>(( - sink, path, declared, - )) - }) - .await; - let (sink, path, declared) = match built { - Ok(Ok(v)) => v, - Ok(Err(e)) => { + // Rebuild by ordered range reads, fully async: a sync walker + // would force block_on, which has no reactor under the S3 + // backend. Blocks were hash-verified at write, so the + // whole-file digest is the check that matters here. + let slices = match twigpine_core::model::reconstruction::map_file_range( + &entry, &rec, 0, file.size, + ) { + Ok(s) => s, + Err(e) => { return reject_release( state, release_id, @@ -161,27 +137,51 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App ) .await; } - Err(e) => return Err(AppError::Internal(e.into())), }; - if sink.digest.as_deref() != Some(file.sha256.as_str()) { + let mut sink = VerifySink { + hasher: sha2::Sha256::new(), + head: Vec::new(), + }; + for slice in &slices { + let bytes = match super::read_range( + &store, + &slice.block, + slice.offset, + slice.len, + ) + .await + { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("{}: rebuild failed: {e}", file.path), + ) + .await; + } + }; + if sink.write_all(&bytes).is_err() { + return Err(AppError::Internal(anyhow::anyhow!("verify sink write"))); + } + } + let digest = hex::encode(sink.hasher.finalize()); + if digest != file.sha256 { return reject_release( state, release_id, - &format!( - "{}: rebuilt bytes hash to {}", - path, - sink.digest.unwrap_or_default() - ), + &format!("{}: rebuilt bytes hash to {digest}", file.path), ) .await; } - let detected = detect_format(&sink.head, &path); - if detected != declared { + let detected = detect_format(&sink.head, &file.path); + if detected != file.format { return reject_release( state, release_id, &format!( - "{path}: declared format {declared:?} but bytes detect as {detected:?}" + "{}: declared format {:?} but bytes detect as {:?}", + file.path, file.format, detected ), ) .await; From bb394dc919aeb4660cd7a01ebde60035eb6ee380 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:44:55 -0600 Subject: [PATCH 18/53] refactor(node): exit model workers on node shutdown Match the other spawned workers: select each tick against the shutdown watch channel instead of looping until the runtime dies. --- crates/twigpine-node/src/models/sweep.rs | 9 +++++++-- crates/twigpine-node/src/models/verify.rs | 8 ++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index edf12187..c11f6ea9 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -68,11 +68,16 @@ pub async fn sweep_once(state: &AppState) -> Result { Ok(stats) } -/// Periodic sweep; spawned once when model hosting is enabled. +/// Periodic sweep; spawned once when model hosting is enabled and exits on +/// node shutdown. pub async fn run_sweep_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); loop { - interval.tick().await; + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } if let Err(e) = sweep_once(&state).await { tracing::warn!("model sweep failed: {e}"); } diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index b26272b8..5a823e36 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -286,11 +286,15 @@ pub async fn reject_release( } /// Poll for `verifying` releases and verify them in order. Spawned once per -/// node when model hosting is enabled. +/// node when model hosting is enabled; exits on node shutdown. pub async fn run_verify_worker(state: AppState) { + let mut shutdown_rx = state.subscribe_shutdown(); let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); loop { - interval.tick().await; + tokio::select! { + _ = interval.tick() => {} + _ = shutdown_rx.changed() => return, + } let ids = match state.db.model_verifying_ids(4).await { Ok(v) => v, Err(e) => { From 2d29e9308ac8c39c690073f9950dbd3b26f7b53c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:45:09 -0600 Subject: [PATCH 19/53] fix(node): refund the admission on post-store failures A size-lookup or record_block error after put_verified leaked the session charge until expiry. --- crates/twigpine-node/src/api/models.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index c2802ab0..d20007e2 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -220,12 +220,25 @@ pub async fn put_model_block( }; let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. - let size = store - .size(&block_id) - .await - .map_err(|e| AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")))? - .unwrap_or(declared); - let duplicate = models::record_block(pool, &session.id, &sha, size, declared as i64).await?; + // Past this point the object exists; a bookkeeping failure must refund + // the admission or the session's charge leaks until it expires. + let size = match store.size(&block_id).await { + Ok(s) => s.unwrap_or(declared), + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(AppError::Internal(anyhow::anyhow!( + "block size lookup failed: {e}" + ))); + } + }; + let duplicate = match models::record_block(pool, &session.id, &sha, size, declared as i64).await + { + Ok(d) => d, + Err(e) => { + let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + return Err(e); + } + }; let fresh = models::load_session(pool, &session.id).await?; Ok(Json(json!({ "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), From 690b0624e1d3a958b4d04aeaeea06c56685d7097 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:57:04 -0600 Subject: [PATCH 20/53] feat(cli): add twigpine model publish Publish open-weight model releases from a local clone: classify and chunk model files, open an upload session, PUT content-addressed blocks through the unsigned session bearer route, sign a manifest with the publisher identity, commit and push the release metadata, claim the release with a signed body, and poll verification until it settles. Supports parent reconstruction dedup and resumable local state. Adds NodeClient::put_unsigned for the raw block PUT. --- crates/twigpine-cli/src/http.rs | 19 + crates/twigpine-cli/src/main.rs | 8 + crates/twigpine-cli/src/model.rs | 1077 ++++++++++++++++++++++++++++++ 3 files changed, 1104 insertions(+) create mode 100644 crates/twigpine-cli/src/model.rs diff --git a/crates/twigpine-cli/src/http.rs b/crates/twigpine-cli/src/http.rs index 309b0d10..a2dda070 100644 --- a/crates/twigpine-cli/src/http.rs +++ b/crates/twigpine-cli/src/http.rs @@ -314,6 +314,25 @@ impl NodeClient { self.send_signed("PUT", path, body).await } + /// PUT raw bytes with no signature and caller-supplied extra headers. + /// Used only for the model block upload, where the session id IS the + /// bearer credential and the body is too large to buffer for signing. + /// Content-Length is set by reqwest from the body, which the route + /// requires. Every other write goes through `put`/`post`/`delete`. + pub async fn put_unsigned( + &self, + path: &str, + body: Vec, + headers: &[(&str, &str)], + ) -> Result { + let url = format!("{}{}", self.node_url, path); + let mut req = self.inner.put(&url).body(body); + for (name, value) in headers { + req = req.header(*name, *value); + } + req.send().await.with_context(|| format!("PUT {url}")) + } + /// DELETE with RFC 9421 signing + transparent iCaptcha solve/retry. pub async fn delete(&self, path: &str, body: &[u8]) -> Result { self.send_signed("DELETE", path, body).await diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index 13696231..9f1dc2e0 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -16,6 +16,7 @@ mod ipfs_cmd; mod issue; mod mcp; mod mirror; +mod model; mod name; mod node; mod node_stake; @@ -140,6 +141,12 @@ enum Commands { /// Print your current identity (DID) and optional node info Whoami(whoami::WhoamiArgs), + + /// Publish open-weight model releases + Model { + #[command(subcommand)] + cmd: model::ModelCmd, + }, } /// The command was `gl` before the rename and still answers to it. Say so @@ -236,6 +243,7 @@ async fn run() -> Result<()> { Commands::Bounty(args) => bounty::run(args).await, Commands::Ucan(args) => ucan_cmd::run(args).await, Commands::Whoami(args) => whoami::run(args).await, + Commands::Model { cmd } => model::run(cmd).await, } } diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs new file mode 100644 index 00000000..ae24c0c1 --- /dev/null +++ b/crates/twigpine-cli/src/model.rs @@ -0,0 +1,1077 @@ +//! `twigpine model` — open-weight model publishing (KTD14). +//! +//! `twigpine model publish` runs inside a local clone of a fully public +//! Twigpine repo: it classifies files by the chunking threshold, packs the +//! large ones into content blocks with cross-release dedup, uploads the new +//! blocks under an upload session (resuming from a `.git` state file after an +//! interruption), commits the signed manifest, pushes, claims the release, +//! and polls until the node's verification publishes it. + +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::STANDARD as B64, Engine}; +use clap::{Args, Subcommand}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Output; +use std::time::{Duration, Instant}; + +use twigpine_core::cid::sha256_hex; +use twigpine_core::model::manifest::{ + self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, + MANIFEST_SCHEMA_V1, +}; +use twigpine_core::model::reconstruction::{pack_file, BlockEntry, DedupIndex, Reconstruction}; + +use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; +use crate::identity::load_keypair_from_dir; + +const DEFAULT_CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024; +const SESSION_HEADER: &str = "x-twigpine-model-session"; +const STATE_FILE_NAME: &str = "twigpine-model-publish.json"; +const GITIGNORE_BEGIN: &str = "# >>> twigpine-model-publish >>>"; +const GITIGNORE_END: &str = "# <<< twigpine-model-publish <<<"; +/// huggingface_hub 2.x refuses plain downloads of a single file past this. +const SINGLE_FILE_WARN_BYTES: u64 = 50 << 30; +/// Bound on a fetched prior reconstruction object: big models name thousands +/// of blocks but the object is small JSON; a runaway body is not one. +const RECONSTRUCTION_FETCH_CAP: usize = 64 * 1024 * 1024; +const POLL_INTERVAL: Duration = Duration::from_secs(3); +const POLL_BUDGET: Duration = Duration::from_secs(300); + +#[derive(Subcommand)] +pub enum ModelCmd { + /// Publish the working tree as a signed model release + Publish(PublishArgs), +} + +#[derive(Args)] +pub struct PublishArgs { + /// Node base URL (or set TWIGPINE_NODE) + #[arg( + long, + default_value = "https://node.twigpine.com", + env = "TWIGPINE_NODE" + )] + pub node: String, + /// Skip the permanence confirmation (for scripts) + #[arg(long)] + pub yes: bool, + /// Declare a parent release: /@ + #[arg(long)] + pub parent: Option, + /// License identifier recorded in the manifest + #[arg(long, default_value = "")] + pub license: String, + /// Branch to push the release commit to (default: current branch) + #[arg(long)] + pub branch: Option, + /// Chunking threshold in bytes; files at or above it are stored as + /// content blocks instead of git blobs + #[arg(long, hide = true, default_value_t = DEFAULT_CHUNK_THRESHOLD)] + pub chunk_threshold_bytes: u64, + /// Identity directory override + #[arg(long)] + pub dir: Option, +} + +pub async fn run(cmd: ModelCmd) -> Result<()> { + match cmd { + ModelCmd::Publish(a) => cmd_publish(a).await, + } +} + +// ── git helpers ───────────────────────────────────────────────────────────── + +fn git(root: &Path, args: &[&str]) -> Result { + let out = std::process::Command::new("git") + .args(args) + .current_dir(root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(out) +} + +fn git_lines(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect()) +} + +fn git_nul(root: &Path, args: &[&str]) -> Result> { + let out = git(root, args)?; + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(text + .split('\0') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect()) +} + +/// `git log` for the release-marker path, newest first; an unborn HEAD just +/// has none. Capped: each commit costs one reconstruction fetch for dedup. +fn release_commits(root: &Path) -> Vec { + git_lines( + root, + &[ + "log", + "--format=%H", + "-n", + "8", + "--", + ".twigpine/model-release.json", + ], + ) + .unwrap_or_default() +} + +fn repo_root() -> Result { + let out = std::process::Command::new("git") + .args(["rev-parse", "--show-toplevel"]) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("not inside a git repository"); + } + let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; + Ok(PathBuf::from(text.trim())) +} + +fn git_dir(root: &Path) -> Result { + let lines = git_lines(root, &["rev-parse", "--git-dir"])?; + let dir = PathBuf::from(lines.first().context("no git dir")?); + Ok(if dir.is_absolute() { + dir + } else { + root.join(dir) + }) +} + +/// Parse a `twigpine:///` (or `gitlawb://`) remote URL. +fn parse_remote_url(url: &str) -> Option<(String, String)> { + let rest = twigpine_core::url_scheme::strip_scheme(url.trim())?; + let slash = rest.rfind('/')?; + let did = rest[..slash].to_string(); + let repo = twigpine_core::ucan::push::canonical_repo_name(&rest[slash + 1..]).to_string(); + if did.is_empty() || repo.is_empty() { + return None; + } + Some((did, repo)) +} + +/// The remote name plus (owner did, repo) of the first remote carrying a +/// twigpine URL: origin first, then twigpine/gitlawb, then any other. +fn detect_remote(root: &Path) -> Result<(String, String, String)> { + let names = git_lines(root, &["remote"])?; + let preferred = ["origin", "twigpine", "gitlawb"]; + let ordered = preferred + .iter() + .filter(|p| names.iter().any(|n| n == *p)) + .map(|p| p.to_string()) + .chain( + names + .iter() + .filter(|n| !preferred.contains(&n.as_str())) + .cloned(), + ); + for name in ordered { + for extra in [&["--all"][..], &["--push", "--all"][..]] { + let mut args = vec!["remote", "get-url"]; + args.extend_from_slice(extra); + args.push(&name); + let Ok(urls) = git_lines(root, &args) else { + continue; + }; + if let Some((did, repo)) = urls.iter().find_map(|u| parse_remote_url(u)) { + return Ok((name, did, repo)); + } + } + } + bail!("no twigpine:// (or gitlawb://) remote found; run inside a clone of the repo") +} + +// ── file classification ───────────────────────────────────────────────────── + +#[derive(Debug, PartialEq, Eq)] +enum Class { + /// Listed in the manifest with `storage: "git"` and committed. + Git, + /// Listed with `storage: "chunked"`, packed into blocks, gitignored. + Chunked, + /// At or over the threshold but git-tracked: refused (weights live + /// outside git). + LargeTracked, + /// Untracked and ignored, so not part of the publishable set. + Ignored, +} + +/// The publishable set is git's own view of the tree: tracked files plus +/// untracked files that are not ignored. An ignored file only comes back in +/// at threshold size and only while it sits inside the managed .gitignore +/// block, which is how previously published chunked paths stay findable on +/// re-publish without sweeping ignored junk (a `target/` dir) into a release. +fn classify(size: u64, tracked: bool, ignored: bool, managed: bool, threshold: u64) -> Class { + if size >= threshold { + if tracked { + Class::LargeTracked + } else if ignored && !managed { + Class::Ignored + } else { + Class::Chunked + } + } else if ignored { + Class::Ignored + } else { + Class::Git + } +} + +struct Scan { + /// Repo-relative paths committed as git blobs. + git_files: Vec, + /// Repo-relative paths packed as content blocks. + chunked_files: Vec, + /// Tracked files at or over the threshold: the refusal list. + refused: Vec, + /// Ignored files at or over the threshold that are not managed: warned + /// and skipped (see [`classify`]). + skipped_ignored: Vec, +} + +/// Tracked paths from `git ls-files -s`, minus submodule gitlinks (mode +/// 160000): a gitlink has no blob to hash and is not a manifest file. +fn tracked_paths(root: &Path) -> Result> { + let entries = git_nul(root, &["ls-files", "-s", "-z"])?; + let mut out = HashSet::new(); + for e in entries { + let Some((meta, name)) = e.split_once('\t') else { + continue; + }; + if meta.starts_with("160000 ") { + continue; + } + out.insert(name.to_string()); + } + Ok(out) +} + +/// Paths listed inside the managed .gitignore block (empty when there is no +/// block): previously published chunked files. +fn managed_block_paths(gitignore: &str) -> Vec { + let mut inside = false; + let mut out = Vec::new(); + for line in gitignore.lines() { + let t = line.trim_end(); + if t == GITIGNORE_BEGIN { + inside = true; + continue; + } + if t == GITIGNORE_END { + break; + } + if inside && !t.is_empty() { + out.push(t.to_string()); + } + } + out +} + +fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { + let tracked = tracked_paths(root)?; + let others = git_nul(root, &["ls-files", "--others", "-z"])?; + let unignored: HashSet = + git_nul(root, &["ls-files", "--others", "--exclude-standard", "-z"])? + .into_iter() + .collect(); + let managed: HashSet = managed_block_paths(gitignore).into_iter().collect(); + + let mut scan = Scan { + git_files: Vec::new(), + chunked_files: Vec::new(), + refused: Vec::new(), + skipped_ignored: Vec::new(), + }; + let mut consider = |path: &str, is_tracked: bool| { + if path.starts_with(".twigpine/") { + return; // release metadata is never a manifest file + } + // A path that vanished between listing and stat (or a tracked file + // deleted in the worktree, whose staged deletion `git add -A` picks + // up) is simply not in the publishable set. + let Ok(meta) = std::fs::symlink_metadata(root.join(path)) else { + return; + }; + if !meta.is_file() && !meta.file_type().is_symlink() { + return; + } + let ignored = !is_tracked && !unignored.contains(path); + match classify( + meta.len(), + is_tracked, + ignored, + managed.contains(path), + threshold, + ) { + Class::Git => scan.git_files.push(path.to_string()), + Class::Chunked => scan.chunked_files.push(path.to_string()), + Class::LargeTracked => scan.refused.push(path.to_string()), + Class::Ignored => { + if meta.len() >= threshold { + scan.skipped_ignored.push(path.to_string()); + } + } + } + }; + + for p in &tracked { + consider(p, true); + } + for p in &others { + if tracked.contains(p) { + continue; + } + consider(p, false); + } + scan.git_files.sort(); + scan.chunked_files.sort(); + scan.refused.sort(); + scan.skipped_ignored.sort(); + Ok(scan) +} + +// ── .gitignore managed block ──────────────────────────────────────────────── + +/// Insert or replace the managed block so it lists exactly `paths`; an empty +/// list removes the block. Idempotent: rewriting the same list yields the +/// same file content. +fn upsert_managed_block(existing: &str, paths: &[String]) -> String { + let mut out: Vec = existing.lines().map(str::to_string).collect(); + if let Some(b) = out.iter().position(|l| l.trim_end() == GITIGNORE_BEGIN) { + let end = out[b + 1..] + .iter() + .position(|l| l.trim_end() == GITIGNORE_END) + .map(|e| b + 1 + e) + .unwrap_or(out.len() - 1); + out.drain(b..=end); + // The blank line we insert before the block goes with it. + if b > 0 && out.get(b - 1).is_some_and(|l| l.is_empty()) { + out.remove(b - 1); + } + } + if !paths.is_empty() { + if !out.is_empty() && !out.last().is_some_and(|l| l.is_empty()) { + out.push(String::new()); + } + out.push(GITIGNORE_BEGIN.to_string()); + out.extend(paths.iter().cloned()); + out.push(GITIGNORE_END.to_string()); + } + let mut s = out.join("\n"); + if !s.is_empty() { + s.push('\n'); + } + s +} + +// ── resume state ──────────────────────────────────────────────────────────── + +#[derive(Debug, Default, Serialize, Deserialize, PartialEq)] +struct PublishState { + session_id: String, + uploaded: Vec, +} + +fn load_state(path: &Path) -> PublishState { + let Ok(text) = std::fs::read_to_string(path) else { + return PublishState::default(); + }; + serde_json::from_str(&text).unwrap_or_default() +} + +/// Rewrite the state file after each uploaded block: the file carries the +/// resume set, so it is written and fsync'd rather than left in page cache. +fn save_state(path: &Path, state: &PublishState) -> Result<()> { + let bytes = serde_json::to_vec(state)?; + let mut f = std::fs::File::create(path).with_context(|| format!("write {}", path.display()))?; + f.write_all(&bytes)?; + f.sync_all()?; + Ok(()) +} + +// ── misc ──────────────────────────────────────────────────────────────────── + +/// `/@<40-hex commit>` -> ((owner, name), commit). +fn parse_parent(spec: &str) -> Result<((String, String), String)> { + let (repo, commit) = spec + .rsplit_once('@') + .context("parent must be /@")?; + let (owner, name) = repo + .split_once('/') + .context("parent must be /@")?; + if owner.is_empty() || name.is_empty() || name.contains('/') { + bail!("parent must be /@"); + } + if commit.len() != 40 || !commit.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("parent commit must be a 40-hex sha"); + } + Ok(((owner.to_string(), name.to_string()), commit.to_string())) +} + +/// The detached signature file contents: base64-std over the domain-tagged +/// manifest bytes, same as `manifest::sign` but through the CLI Keypair +/// (which signs but does not expose its SigningKey). +fn sign_manifest_bytes(kp: &twigpine_core::identity::Keypair, manifest_bytes: &[u8]) -> String { + let sig = kp.sign(&manifest::signing_input(manifest_bytes)); + B64.encode(sig.to_bytes()) +} + +fn read_head(path: &Path, n: u64) -> Result> { + let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; + let mut buf = Vec::new(); + f.take(n).read_to_end(&mut buf)?; + Ok(buf) +} + +/// Bytes of the staged index blob for `path`: exactly what the release +/// commit will store, filters and symlink handling included. +fn staged_blob(root: &Path, path: &str) -> Result> { + Ok(git(root, &["show", &format!(":{path}")])?.stdout) +} + +/// Fetch a prior release's reconstruction object for dedup. A 404 means the +/// commit never became a published release (or its repo stopped serving); +/// any other non-2xx surfaces the node's own body. +async fn fetch_reconstruction( + client: &NodeClient, + owner: &str, + name: &str, + commit: &str, +) -> Result> { + let path = format!("/api/v1/repos/{owner}/{name}/models/releases/{commit}/reconstruction"); + let resp = client + .get_signed(&path) + .await + .context("reconstruction fetch failed")?; + let status = resp.status(); + if status == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !status.is_success() { + let capped = read_body_capped_bytes(resp, 8 * 1024).await; + bail!( + "reconstruction fetch for {commit} failed ({status}): {}", + crate::http::sanitize_node_msg(&String::from_utf8_lossy(&capped.bytes)) + ); + } + let capped = read_body_capped_bytes(resp, RECONSTRUCTION_FETCH_CAP).await; + if capped.truncated || capped.read_failed { + bail!("reconstruction object for {commit} was oversized or truncated"); + } + let rec = Reconstruction::parse(&capped.bytes) + .map_err(|e| anyhow::anyhow!("reconstruction object for {commit} is invalid: {e}"))?; + Ok(Some(rec)) +} + +/// Send one content block to the session. Unsigned by protocol: the session +/// id is the bearer credential. A non-2xx body is surfaced through +/// `read_json`'s denial path. +async fn upload_block( + client: &NodeClient, + base: &str, + session_id: &str, + sha: &str, + data: Vec, +) -> Result<()> { + let resp = client + .put_unsigned( + &format!("{base}/models/blocks/{sha}"), + data, + &[(SESSION_HEADER, session_id)], + ) + .await?; + let _: Value = read_json(resp, "block upload").await?; + Ok(()) +} + +/// Without `--yes`, publishing requires an explicit "yes" on stdin. Any +/// other answer, including EOF on a pipe, declines. +fn confirm_publish() -> Result { + eprint!("type 'yes' to publish: "); + let _ = std::io::stderr().flush(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line)?; + Ok(line.trim().eq_ignore_ascii_case("yes")) +} + +// ── publish ───────────────────────────────────────────────────────────────── + +async fn cmd_publish(args: PublishArgs) -> Result<()> { + let kp = load_keypair_from_dir(args.dir.as_deref())?; + let root = repo_root()?; + let git_dir = git_dir(&root)?; + let (remote_name, owner, name) = detect_remote(&root)?; + let branch = match &args.branch { + Some(b) => b.clone(), + None => { + let out = std::process::Command::new("git") + .args(["symbolic-ref", "--short", "-q", "HEAD"]) + .current_dir(&root) + .output() + .context("failed to run git")?; + if !out.status.success() { + bail!("detached HEAD: pass --branch to name the release branch"); + } + String::from_utf8(out.stdout) + .context("branch name was not utf-8")? + .trim() + .to_string() + } + }; + + // 1. Scan and refuse tracked large files before anything else happens. + let gitignore_path = root.join(".gitignore"); + let existing_gitignore = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); + let scan = scan_files(&root, &existing_gitignore, args.chunk_threshold_bytes)?; + if !scan.refused.is_empty() { + bail!( + "these files are {} bytes or larger but tracked in git; weights must live \ + outside git. Remove them from the index first (git rm --cached):\n {}", + args.chunk_threshold_bytes, + scan.refused.join("\n ") + ); + } + for p in &scan.skipped_ignored { + eprintln!( + "warning: {p} is at or over the chunk threshold but gitignored; \ + unignore it to publish" + ); + } + + // 2. Warn + confirm: publishing is permanent. + println!("Publishing {owner}/{name} as a model release on branch {branch}:"); + println!( + " {} git files, {} chunked files", + scan.git_files.len(), + scan.chunked_files.len() + ); + for p in &scan.chunked_files { + let size = std::fs::symlink_metadata(root.join(p)) + .map(|m| m.len()) + .unwrap_or(0); + if size > SINGLE_FILE_WARN_BYTES { + eprintln!( + "warning: {p} is over 50 GiB; huggingface_hub refuses plain downloads that large" + ); + } + } + eprintln!( + "publishing is permanent: blocks are pinned to IPFS and the manifest anchors \ + to Arweave, so the bytes stay fetchable even if this repo is later removed" + ); + if !args.yes && !confirm_publish()? { + println!("aborted"); + return Ok(()); + } + + let client = NodeClient::new(&args.node, Some(kp.clone())); + let base = format!("/api/v1/repos/{owner}/{name}"); + + // 3. Dedup: reconstructions of prior releases in this clone, plus the + // declared parent's when given. + let mut priors: Vec = Vec::new(); + let mut parent_ref: Option = None; + for commit in release_commits(&root) { + if let Some(rec) = fetch_reconstruction(&client, &owner, &name, &commit).await? { + priors.push(rec); + } + } + if let Some(spec) = &args.parent { + let ((powner, pname), pcommit) = parse_parent(spec)?; + let rec = fetch_reconstruction(&client, &powner, &pname, &pcommit) + .await? + .context("declared parent has no published reconstruction on this node")?; + // There is no manifest-serving route, so the parent manifest sha256 + // is the sha of the manifest bytes in the local clone when the parent + // commit is here, and the sha of the parent's reconstruction object + // (the only parent artifact the node serves) otherwise. The node + // records the field without checking it (R9: a signed claim, not a + // verified link). + let manifest_sha = git( + &root, + &["show", &format!("{pcommit}:.twigpine/model-release.json")], + ) + .map(|out| sha256_hex(&out.stdout)) + .unwrap_or_else(|_| sha256_hex(&rec.to_bytes().unwrap_or_default())); + parent_ref = Some(ParentRef { + repo: format!("{powner}/{pname}"), + commit: pcommit, + manifest_sha256: manifest_sha, + }); + priors.push(rec); + } + let prior_refs: Vec<&Reconstruction> = priors.iter().collect(); + let mut dedup = DedupIndex::from_reconstructions(&prior_refs); + let mut all_entries: HashMap = HashMap::new(); + for rec in &priors { + for b in &rec.blocks { + all_entries.insert(b.sha256.clone(), b.clone()); + } + } + + // 4. Pack every chunked file; shared chunks become terms into prior + // blocks, the rest seal into new blocks to upload. + let mut rec = Reconstruction::new(); + let mut new_blocks = Vec::new(); + let mut new_block_shas: HashSet = HashSet::new(); + let mut files: Vec = Vec::new(); + for path in &scan.chunked_files { + let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; + let packed = pack_file(path, file, &dedup)?; + let head = read_head(&root.join(path), 64)?; + files.push(ManifestFile { + path: path.clone(), + size: packed.file.size, + sha256: packed.file.sha256.clone(), + format: detect_format(&head, path), + storage: StorageKind::Chunked, + }); + rec.files.push(packed.file); + for e in packed.block_entries { + all_entries.insert(e.sha256.clone(), e.clone()); + rec.blocks.push(e); + } + for b in packed.new_blocks { + if new_block_shas.insert(b.sha256.clone()) { + new_blocks.push(b); + } + } + // Make this file's fresh chunks visible to the next file's dedup. + dedup.add(&rec); + } + // Terms into earlier blocks need those entries in this object: a reader + // resolves term.block against rec.blocks only. + let needed: HashSet = rec + .files + .iter() + .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) + .collect(); + for sha in needed { + if rec.blocks.iter().any(|b| b.sha256 == sha) { + continue; + } + let entry = all_entries + .get(&sha) + .with_context(|| format!("term references unknown block {sha}"))?; + rec.blocks.push(entry.clone()); + } + // A release with no chunked files has no chunked bytes to reconstruct: + // no reconstruction object, no reconstruction block. + let rec_bytes = if scan.chunked_files.is_empty() { + Vec::new() + } else { + rec.validate() + .map_err(|e| anyhow::anyhow!("reconstruction object invalid: {e}"))?; + rec.to_bytes() + .map_err(|e| anyhow::anyhow!("reconstruction serialize failed: {e}"))? + }; + let rec_sha = sha256_hex(&rec_bytes); + + // 5. Open (or resume) the upload session and send the new blocks, then + // the reconstruction object as one more block. + let state_path = git_dir.join(STATE_FILE_NAME); + let mut state = load_state(&state_path); + if !state.session_id.is_empty() { + let resp = client + .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) + .await + .context("session status request failed")?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + state = PublishState::default(); + } else { + let v: Value = read_json(resp, "session status").await?; + if v["state"].as_str() != Some("open") { + state = PublishState::default(); + } + } + } + if state.session_id.is_empty() { + let body = serde_json::to_vec(&json!({ + "parent_release": parent_ref.as_ref().map(|p| p.commit.clone()), + }))?; + let resp = client + .post(&format!("{base}/models/sessions"), &body) + .await?; + let v: Value = json_or_denial("open model session", resp).await?; + state.session_id = v["session_id"] + .as_str() + .context("session response had no session_id")? + .to_string(); + state.uploaded.clear(); + save_state(&state_path, &state)?; + } + let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); + let session_id = state.session_id.clone(); + + let total = new_blocks.len() + usize::from(!rec_bytes.is_empty()); + for (i, block) in new_blocks.into_iter().enumerate() { + let sha = block.sha256; + if uploaded.contains(&sha) { + continue; + } + upload_block(&client, &base, &session_id, &sha, block.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha); + save_state(&state_path, &state)?; + println!("uploaded block {}/{total}", i + 1); + } + if !rec_bytes.is_empty() && !uploaded.contains(&rec_sha) { + upload_block(&client, &base, &session_id, &rec_sha, rec_bytes.clone()).await?; + state.uploaded.push(rec_sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded reconstruction object ({total}/{total})"); + } + + // 6. Managed .gitignore block, then stage the publishable set. + let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); + if new_gitignore != existing_gitignore { + std::fs::write(&gitignore_path, &new_gitignore)?; + } + git(&root, &["add", "-A"])?; + + // 7. Hash the git-stored files from the index (the exact bytes the + // commit stores), then write and stage the manifest. + for path in &scan.git_files { + let bytes = staged_blob(&root, path)?; + files.push(ManifestFile { + path: path.clone(), + size: bytes.len() as u64, + sha256: sha256_hex(&bytes), + format: detect_format(&bytes[..bytes.len().min(64)], path), + storage: StorageKind::Git, + }); + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + + let manifest = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner}/{name}"), + publisher_did: kp.did().to_string(), + license: args.license.clone(), + parent: parent_ref, + files, + reconstruction: if rec_bytes.is_empty() { + None + } else { + Some(ReconstructionRef { + sha256: rec_sha, + size: rec_bytes.len() as u64, + }) + }, + }; + let manifest_bytes = manifest + .to_bytes() + .map_err(|e| anyhow::anyhow!("manifest serialize failed: {e}"))?; + let twigpine_dir = root.join(".twigpine"); + std::fs::create_dir_all(&twigpine_dir)?; + std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; + std::fs::write( + twigpine_dir.join("model-release.sig"), + format!("{}\n", sign_manifest_bytes(&kp, &manifest_bytes)), + )?; + git(&root, &["add", "-A"])?; + + // 8. Commit when the index differs, push, and claim HEAD. + let has_changes = git(&root, &["diff", "--cached", "--quiet"]).is_err(); + if has_changes { + let n = release_commits(&root).len() + 1; + git(&root, &["commit", "-m", &format!("model release {n}")])?; + } else { + // Nothing staged: a re-publish of identical content lands here, and + // HEAD must already be a release commit to claim. + if git( + &root, + &["cat-file", "-e", "HEAD:.twigpine/model-release.json"], + ) + .is_err() + { + bail!("nothing to publish and HEAD carries no release manifest"); + } + println!("no changes to commit; claiming the existing release commit"); + } + let commit = git_lines(&root, &["rev-parse", "HEAD"])? + .into_iter() + .next() + .context("no HEAD commit")?; + + let push = std::process::Command::new("git") + .args(["push", &remote_name, &format!("HEAD:{branch}")]) + .current_dir(&root) + .env("TWIGPINE_NODE", &args.node) + // The helper on PATH may be a build from before the rename. + .env("GITLAWB_NODE", &args.node) + .output() + .context("failed to run git push")?; + if !push.status.success() { + bail!( + "git push failed:\n{}", + String::from_utf8_lossy(&push.stderr).trim() + ); + } + println!("pushed {commit} to {remote_name}/{branch}"); + + let claim_body = serde_json::to_vec(&json!({ + "commit": commit, + "branch": branch, + }))?; + let resp = client + .post(&format!("{base}/models/claims"), &claim_body) + .await?; + let claim: Value = json_or_denial("claim release", resp).await?; + let release_id = claim["release_id"].as_i64().unwrap_or_default(); + println!("release {release_id} claimed; verifying"); + + // 9. Poll until the verification worker settles the release. + let release_path = format!("{base}/models/releases/{commit}"); + let deadline = Instant::now() + POLL_BUDGET; + loop { + let resp = client.get_signed(&release_path).await?; + let v: Value = read_json(resp, "release status").await?; + match v["state"].as_str() { + Some("published") => { + println!("published release {release_id}"); + println!(" commit: {}", v["commit"].as_str().unwrap_or(&commit)); + println!( + " manifest: {}", + v["manifest_sha256"].as_str().unwrap_or("?") + ); + let _ = std::fs::remove_file(&state_path); + return Ok(()); + } + Some("rejected") => { + bail!( + "release {release_id} rejected: {}", + v["failure_reason"].as_str().unwrap_or("unknown reason") + ); + } + _ => { + if Instant::now() >= deadline { + println!( + "release {release_id} is still verifying after {}s; its status is at\n \ + GET {release_path}", + POLL_BUDGET.as_secs() + ); + return Ok(()); + } + tokio::time::sleep(POLL_INTERVAL).await; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: u64 = 1024; // test threshold + + #[test] + fn classify_by_threshold_tracking_and_ignore() { + // Below threshold: tracked or unignored-untracked are git files. + assert_eq!(classify(T - 1, true, false, false, T), Class::Git); + assert_eq!(classify(T - 1, false, false, false, T), Class::Git); + assert_eq!(classify(T - 1, false, true, false, T), Class::Ignored); + assert_eq!(classify(T - 1, false, true, true, T), Class::Ignored); + // At/above threshold: tracked refuses; untracked chunks unless + // ignored outside the managed block. + assert_eq!(classify(T, true, false, false, T), Class::LargeTracked); + assert_eq!(classify(T + 1, true, true, false, T), Class::LargeTracked); + assert_eq!(classify(T, false, false, false, T), Class::Chunked); + assert_eq!(classify(T, false, true, true, T), Class::Chunked); + assert_eq!(classify(T, false, true, false, T), Class::Ignored); + } + + #[test] + fn managed_block_upsert_insert_replace_idempotent_remove() { + let base = "*.tmp\n".to_string(); + let paths = vec!["weights/a.bin".to_string(), "b.bin".to_string()]; + let once = upsert_managed_block(&base, &paths); + assert!(once.contains("*.tmp\n")); + assert!(once.contains(GITIGNORE_BEGIN)); + assert!(once.contains("weights/a.bin\nb.bin\n")); + assert!(once.contains(GITIGNORE_END)); + assert_eq!(once, upsert_managed_block(&once, &paths), "idempotent"); + + let replaced = upsert_managed_block(&once, &["c.bin".to_string()]); + assert!(replaced.contains("c.bin")); + assert!(!replaced.contains("a.bin")); + + let removed = upsert_managed_block(&replaced, &[]); + assert!(!removed.contains(GITIGNORE_BEGIN)); + assert_eq!(removed, "*.tmp\n"); + + let empty = upsert_managed_block("", &paths); + assert_eq!(managed_block_paths(&empty), paths); + } + + #[test] + fn managed_block_paths_reads_only_the_block() { + let text = format!("a\n{GITIGNORE_BEGIN}\nx.bin\ny.bin\n{GITIGNORE_END}\nz\n"); + assert_eq!(managed_block_paths(&text), vec!["x.bin", "y.bin"]); + assert!(managed_block_paths("nothing here\n").is_empty()); + } + + #[test] + fn publish_state_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "abc".to_string(), + uploaded: vec!["aa".into(), "bb".into()], + }; + save_state(&path, &state).unwrap(); + assert_eq!(load_state(&path), state); + assert_eq!( + load_state(&dir.path().join("missing.json")), + PublishState::default() + ); + std::fs::write(&path, "not json").unwrap(); + assert_eq!(load_state(&path), PublishState::default()); + } + + #[test] + fn parse_parent_shapes() { + let commit = "a".repeat(40); + let ((owner, name), c) = parse_parent(&format!("alice/weights@{commit}")).unwrap(); + assert_eq!( + (owner.as_str(), name.as_str(), c.as_str()), + ("alice", "weights", commit.as_str()) + ); + // A did:key owner carries colons; the split is on the LAST '@'. + let did_owner = "did:key:z6MkAbc"; + let ((owner, name), _) = parse_parent(&format!("{did_owner}/weights@{commit}")).unwrap(); + assert_eq!((owner.as_str(), name.as_str()), (did_owner, "weights")); + for bad in [ + "noslash", + "a/b@", + "a/b@cafe", + &format!("a/b/c@{commit}"), + &format!("a/b@{commit}x"), + &format!("a/b@{}", "g".repeat(40)), + ] { + assert!(parse_parent(bad).is_err(), "{bad}"); + } + } + + #[test] + fn manifest_assembly_round_trips_storage_kinds() { + // The manifest the command writes: schema v1, repo as owner/name, + // git and chunked entries sorted by path, reconstruction ref present. + let kp = twigpine_core::identity::Keypair::from_seed(&[3u8; 32]).unwrap(); + let mut files = vec![ + ManifestFile { + path: "weights.bin".to_string(), + size: 11, + sha256: "b".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Other, + storage: StorageKind::Chunked, + }, + ManifestFile { + path: "README.md".to_string(), + size: 5, + sha256: "a".repeat(64), + format: twigpine_core::model::manifest::FileFormat::Text, + storage: StorageKind::Git, + }, + ]; + files.sort_by(|a, b| a.path.cmp(&b.path)); + let m = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "did:key:z6MkA/w".to_string(), + publisher_did: kp.did().to_string(), + license: "apache-2.0".to_string(), + parent: None, + files, + reconstruction: Some(ReconstructionRef { + sha256: "c".repeat(64), + size: 42, + }), + }; + let bytes = m.to_bytes().unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["schema"].as_str(), Some(MANIFEST_SCHEMA_V1)); + assert_eq!(v["repo"].as_str(), Some("did:key:z6MkA/w")); + assert_eq!(v["license"].as_str(), Some("apache-2.0")); + let paths: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["path"].as_str()) + .collect(); + assert_eq!(paths, ["README.md", "weights.bin"]); + let storages: Vec<&str> = v["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|f| f["storage"].as_str()) + .collect(); + assert_eq!(storages, ["git", "chunked"]); + let rec_sha = "c".repeat(64); + assert_eq!( + v["reconstruction"]["sha256"].as_str(), + Some(rec_sha.as_str()) + ); + } + + #[test] + fn cli_signature_matches_manifest_sign() { + // The two paths sign the same domain-tagged bytes with the same key: + // manifest::sign takes a raw SigningKey, the CLI signs through Keypair. + let seed = [9u8; 32]; + let signing = ed25519_dalek::SigningKey::from_bytes(&seed); + let kp = twigpine_core::identity::Keypair::from_seed(&seed).unwrap(); + let m = Manifest { + schema: MANIFEST_SCHEMA_V1.to_string(), + repo: "alice/m".to_string(), + publisher_did: kp.did().to_string(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: Some(ReconstructionRef { + sha256: "a".repeat(64), + size: 1, + }), + }; + let bytes = m.to_bytes().unwrap(); + let sig = sign_manifest_bytes(&kp, &bytes); + assert_eq!(sig, manifest::sign(&signing, &bytes)); + let parsed = manifest::verify(&bytes, &sig, &kp.did()).unwrap(); + assert_eq!(parsed.repo, "alice/m"); + } + + #[test] + fn remote_url_parses_both_schemes() { + assert_eq!( + parse_remote_url("twigpine://did:key:z6MkA/repo.git"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!( + parse_remote_url("gitlawb://did:key:z6MkA/repo"), + Some(("did:key:z6MkA".to_string(), "repo".to_string())) + ); + assert_eq!(parse_remote_url("https://x/y"), None); + } +} From ee8f61a6793840feb031250d6661a4d0c20ff1f9 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:57:09 -0600 Subject: [PATCH 21/53] test(node): add HTTP coverage for model routes Exercise the U5/U6/U7 model endpoints over the real HTTP server: session open and status authorization, the unsigned block PUT bearer path (missing, bogus, expired, cross-repo, digest mismatch, duplicate, success), signed claims (valid claim, replay dedup, missing commit, non-owner and anonymous denial), and read-gated release status. Includes a required fix in model_queries.rs: SUM over bigint returns numeric in Postgres, which failed to decode into i64 and made every valid claim 500; cast the aggregates back to bigint. --- crates/twigpine-node/Cargo.toml | 5 + crates/twigpine-node/src/db/model_queries.rs | 13 +- crates/twigpine-node/tests/models_api.rs | 730 +++++++++++++++++++ 3 files changed, 743 insertions(+), 5 deletions(-) create mode 100644 crates/twigpine-node/tests/models_api.rs diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index f1a5f827..acf6097c 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -28,6 +28,11 @@ name = "deny_harness" path = "tests/deny_harness.rs" required-features = ["test-harness"] +[[test]] +name = "models_api" +path = "tests/models_api.rs" +required-features = ["test-harness"] + [dependencies] twigpine-core = { path = "../twigpine-core" } async-trait = "0.1" diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index fe77992e..2244b6ce 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -407,8 +407,9 @@ impl Db { if shas.is_empty() { return Ok(0); } + // SUM over bigint returns numeric; cast back so the i64 decode holds. Ok(sqlx::query_scalar::<_, Option>( - "SELECT SUM(b.size) FROM model_blocks b + "SELECT SUM(b.size)::bigint FROM model_blocks b WHERE b.sha256 = ANY($1) AND NOT EXISTS ( SELECT 1 FROM model_release_blocks rb @@ -450,10 +451,11 @@ impl Db { /// Node-wide used bytes: claimed quota plus every open session's bytes. pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { + // SUM over bigint returns numeric; cast back so the i64 decode holds. Ok(sqlx::query_scalar::<_, Option>( - "SELECT COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + "SELECT (COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions - WHERE state = 'open'), 0)", + WHERE state = 'open'), 0))::bigint", ) .fetch_one(&mut **tx) .await? @@ -579,8 +581,9 @@ impl Db { tx.commit().await?; return Ok(()); }; + // SUM over bigint returns numeric; cast back so the i64 decode holds. let freed: i64 = sqlx::query_scalar::<_, Option>( - "SELECT COALESCE(SUM(b.size), 0) FROM model_blocks b + "SELECT COALESCE(SUM(b.size), 0)::bigint FROM model_blocks b JOIN model_release_blocks rb ON rb.block_sha256 = b.sha256 WHERE rb.release_id = $1 AND NOT EXISTS ( @@ -769,7 +772,7 @@ mod tests { .unwrap() .expect("first admission"); assert_eq!(first.bytes_received, 100); - assert!(first.expires_at > s.expires_at || first.expires_at == s.expires_at); + assert!(first.expires_at >= s.expires_at); // Over the per-identity session cap: refused. assert!(db .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs new file mode 100644 index 00000000..236641f4 --- /dev/null +++ b/crates/twigpine-node/tests/models_api.rs @@ -0,0 +1,730 @@ +//! HTTP-level coverage for the U5/U6/U7 model-hosting routes: the signed +//! session open and session status, the unsigned bearer block PUT, the signed +//! release claim (including its request-digest replay), and the read-gated +//! release status. The deny sweep already proves the hostile statuses; these +//! tests drive the happy paths and the handler-specific 4xxes the sweep rows +//! cannot express. Requires `--features test-harness`. + +#[allow(dead_code)] +mod support; + +use serde_json::{json, Value}; +use sha2::Digest; +use support::signing::signed_request; + +use twigpine_core::http_sig::sign_request; +use twigpine_core::identity::Keypair; +use twigpine_node::test_harness::{spawn_node, TestNode}; + +fn bounded_client() -> reqwest::Client { + reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(30)) + .build() + .expect("client builds") +} + +fn sessions_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/sessions") +} + +fn claims_path(owner: &str, repo: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/claims") +} + +fn release_path(owner: &str, repo: &str, commit: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/releases/{commit}") +} + +fn blocks_path(owner: &str, repo: &str, sha: &str) -> String { + format!("/api/v1/repos/{owner}/{repo}/models/blocks/{sha}") +} + +fn put_block( + client: &reqwest::Client, + base_url: &str, + path: &str, + session: Option<&str>, + body: Vec, +) -> reqwest::RequestBuilder { + let mut req = client.put(format!("{base_url}{path}")).body(body); + if let Some(s) = session { + req = req.header("x-twigpine-model-session", s); + } + req +} + +/// An owner keypair plus the raw SigningKey the manifest format signs with; +/// both derive from one seed so the keypair's DID anchors the manifest. +fn owner_with_signing(seed: u8) -> (Keypair, ed25519_dalek::SigningKey) { + let seed_bytes = [seed; 32]; + ( + Keypair::from_seed(&seed_bytes).expect("keypair"), + ed25519_dalek::SigningKey::from_bytes(&seed_bytes), + ) +} + +/// Build a git repo on disk containing one commit with a valid signed release +/// manifest, returning the commit sha. The claim route's `git cat-file` / +/// `git show` calls run against `repos.disk_path`, so the row must point here. +fn make_release_repo(dir: &std::path::Path, manifest: &[u8], sig: &str) -> String { + let run = |args: &[&str]| { + let out = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + run(&["init", "-q", "-b", "main"]); + std::fs::create_dir_all(dir.join(".twigpine")).expect("mkdir .twigpine"); + std::fs::write(dir.join(".twigpine/model-release.json"), manifest).expect("write manifest"); + std::fs::write(dir.join(".twigpine/model-release.sig"), sig).expect("write sig"); + run(&["add", "-A"]); + run(&[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-q", + "-m", + "model release 1", + ]); + run(&["rev-parse", "HEAD"]) +} + +/// Point the seeded repo row at an on-disk git directory (seed_repo writes a +/// placeholder disk_path the claim route cannot read). +async fn set_disk_path(pool: &sqlx::PgPool, repo_id: &str, dir: &std::path::Path) { + sqlx::query("UPDATE repos SET disk_path = $1 WHERE id = $2") + .bind(dir.to_str().expect("utf-8 temp path")) + .bind(repo_id) + .execute(pool) + .await + .expect("update disk_path"); +} + +async fn seed_open_session(node: &TestNode, repo_id: &str, owner_did: &str) -> String { + let session_id = "s".repeat(64); + node.seed_model_session(repo_id, &session_id, owner_did) + .await; + session_id +} + +// ── POST /models/sessions ──────────────────────────────────────────────────── + +/// The owner opening a session on a fully public repo gets 201 and a +/// 64-hex session id plus an expiry. +#[sqlx::test] +async fn open_session_owner_created(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 201); + let v: Value = resp.json().await.expect("session body"); + assert_eq!( + v["session_id"].as_str().map(str::len), + Some(64), + "session id is a 256-bit hex bearer" + ); + assert!(v["expires_at"].as_str().is_some()); + + node.shutdown().await; +} + +/// A signed caller who is not the repo owner gets the owner gate's 403. +#[sqlx::test] +async fn open_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +/// An unsigned request is stopped by the signature layer before any repo +/// lookup: 401. +#[sqlx::test] +async fn open_session_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + + let resp = client + .post(format!( + "{}{}", + node.base_url, + sessions_path(&owner_did, "model") + )) + .body(b"{}".to_vec()) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A private repo answers the read gate's existence-hiding 404 to a signed +/// non-reader, before the owner gate can fire. +#[sqlx::test] +async fn open_session_private_repo_hidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A public repo carrying a path-scoped visibility rule is not "fully +/// public", so the session open refuses it with a named 400 rather than +/// partially publishing. +#[sqlx::test] +async fn open_session_repo_with_visibility_rule_rejected(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + node.withhold_path(&repo_id, "sub/**", &[], &owner_did) + .await; + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let body = resp.text().await.unwrap_or_default(); + assert!( + body.contains("fully public"), + "denial should name the fully-public requirement, got: {body}" + ); + + node.shutdown().await; +} + +// ── GET /models/sessions/{id} ──────────────────────────────────────────────── + +/// The owner reads back an open session's state and byte counter. +#[sqlx::test] +async fn get_session_owner_reads_open(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("session body"); + assert_eq!(v["session_id"].as_str(), Some(session_id.as_str())); + assert_eq!(v["state"].as_str(), Some("open")); + + node.shutdown().await; +} + +/// A signed stranger reaches the owner gate on the session read: 403. +#[sqlx::test] +async fn get_session_non_owner_forbidden(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &format!("{}/{}", sessions_path(&owner_did, "model"), session_id), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + node.shutdown().await; +} + +// ── PUT /models/blocks/{sha256} ────────────────────────────────────────────── + +/// The unsigned PUT without the session header gets 401: the bearer +/// credential is absent, not invalid. +#[sqlx::test] +async fn put_block_without_session_header_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let sha = hex::encode(sha2::Sha256::digest(b"block")); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + None, + b"block".to_vec(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +/// A session id that was never issued answers the same 404 as an expired or +/// foreign one: a bearer guess learns nothing about which part failed. +#[sqlx::test] +async fn put_block_bogus_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&"f".repeat(64)), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// A session bound to repo A does not upload into repo B: the +/// session-to-repo binding check answers 404. +#[sqlx::test] +async fn put_block_session_for_other_repo_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_a = node.seed_repo(&owner_did, "model-a", true).await; + node.seed_repo(&owner_did, "model-b", true).await; + let session_id = seed_open_session(&node, &repo_a, &owner_did).await; + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model-b", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// An open session whose expiry already passed answers 404; the PUT never +/// reaches the block store. +#[sqlx::test] +async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "e".repeat(64); + sqlx::query( + "INSERT INTO model_upload_sessions + (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) + VALUES ($1,$2,$3,$4,$5,0,'open')", + ) + .bind(&session_id) + .bind(&owner_did) + .bind(&repo_id) + .bind(chrono::Utc::now().to_rfc3339()) + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .execute(&pool) + .await + .expect("seed expired session"); + let body = b"block".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} + +/// Happy path: a block whose body hashes to the id in the path is stored, +/// reported with the session's running byte count and `duplicate:false`; +/// resending it reports `duplicate:true`; a body that does not match the +/// named id is refused with 400. +#[sqlx::test] +async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = b"the quick brown fox".to_vec(); + let sha = hex::encode(sha2::Sha256::digest(&body)); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("block response"); + assert_eq!(v["duplicate"].as_bool(), Some(false)); + assert!( + v["received"].as_i64().unwrap_or(0) >= body.len() as i64, + "bytes_received should include this block: {v}" + ); + + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &sha), + Some(&session_id), + body.clone(), + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("dup response"); + assert_eq!(v["duplicate"].as_bool(), Some(true)); + + let wrong_sha = "0".repeat(64); + let resp = put_block( + &client, + &node.base_url, + &blocks_path(&owner_did, "model", &wrong_sha), + Some(&session_id), + body, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400, "digest mismatch is a 400"); + + node.shutdown().await; +} + +// ── POST /models/claims ────────────────────────────────────────────────────── + +/// A claim against a pushed commit carrying a signed manifest inserts the +/// release row; re-sending the identical signed request resolves to the same +/// release_id through the persisted request digest. +#[sqlx::test] +async fn claim_accepts_signed_manifest_and_replays_idempotently(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(7); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + + let dir = tempfile::tempdir().expect("tempdir"); + let commit = make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let path = claims_path(&owner_did, "model"); + let body = + serde_json::to_vec(&json!({"commit": commit, "branch": "main"})).expect("claim body"); + // Sign once, then send the identical request twice: the digest replay + // resolves the second to the original row. + let signed = sign_request(&owner, "POST", &path, &body); + let send = |client: &reqwest::Client| { + client + .post(format!("{}{}", node.base_url, path)) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body.clone()) + }; + + let resp = send(&client).send().await.expect("request sends"); + let status = resp.status().as_u16(); + let text = resp.text().await.unwrap_or_default(); + assert_eq!(status, 200, "claim body: {text}"); + let v: Value = serde_json::from_str(&text).expect("claim response"); + let release_id = v["release_id"].as_i64().expect("release_id"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("verifying")); + + let resp = send(&client).send().await.expect("replay sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("replay response"); + assert_eq!( + v["release_id"].as_i64(), + Some(release_id), + "a replayed claim must resolve to the original release row" + ); + + node.shutdown().await; +} + +/// A claim naming a commit the repo does not hold is a 400, not a 404: the +/// repo exists and is readable; the commit is the bad input. +#[sqlx::test] +async fn claim_missing_commit_is_bad_request(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let (owner, signing) = owner_with_signing(8); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + + // A real on-disk repo is needed for `git cat-file` to answer "missing" + // rather than the spawn failing on a nonexistent path. + let manifest = twigpine_core::model::manifest::Manifest { + schema: twigpine_core::model::manifest::MANIFEST_SCHEMA_V1.to_string(), + repo: format!("{owner_did}/model"), + publisher_did: owner_did.clone(), + license: "mit".to_string(), + parent: None, + files: vec![], + reconstruction: None, + }; + let manifest_bytes = manifest.to_bytes().expect("manifest bytes"); + let sig = twigpine_core::model::manifest::sign(&signing, &manifest_bytes); + let dir = tempfile::tempdir().expect("tempdir"); + make_release_repo(dir.path(), &manifest_bytes, &sig); + set_disk_path(&pool, &repo_id, dir.path()).await; + + let body = serde_json::to_vec(&json!({ + "commit": "b".repeat(40), + "branch": "main", + })) + .expect("claim body"); + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body, + &owner, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + let text = resp.text().await.unwrap_or_default(); + assert!(text.contains("commit not found"), "got: {text}"); + + node.shutdown().await; +} + +/// The owner gate on claims: a signed stranger is 403, an unsigned request is +/// 401 before the handler runs. +#[sqlx::test] +async fn claim_non_owner_forbidden_and_anon_unauthorized(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", true).await; + let body = serde_json::to_vec(&json!({ + "commit": "a".repeat(40), + "branch": "main", + })) + .expect("claim body"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + body.clone(), + &stranger, + ) + .header("content-type", "application/json") + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 403); + + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 401); + + node.shutdown().await; +} + +// ── GET /models/releases/{sha} ─────────────────────────────────────────────── + +/// A seeded published release reads back its fields; an unknown commit is a +/// plain 404; a private repo's release is existence-hiding to a non-reader. +#[sqlx::test] +async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let commit = "c".repeat(40); + node.seed_model_release(&repo_id, &commit, &owner_did).await; + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &commit) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 200); + let v: Value = resp.json().await.expect("release body"); + assert_eq!(v["commit"].as_str(), Some(commit.as_str())); + assert_eq!(v["state"].as_str(), Some("published")); + assert_eq!(v["branch"].as_str(), Some("main")); + assert!(v["release_id"].as_i64().is_some()); + assert!(v["manifest_sha256"].as_str().is_some()); + + let resp = client + .get(format!( + "{}{}", + node.base_url, + release_path(&owner_did, "model", &"d".repeat(40)) + )) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "unknown commit is a 404"); + + // Private repo: a signed stranger gets the existence-hiding 404. + let priv_repo = node.seed_repo(&owner_did, "model-priv", false).await; + node.seed_model_release(&priv_repo, &commit, &owner_did) + .await; + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &release_path(&owner_did, "model-priv", &commit), + Vec::new(), + &stranger, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404); + + node.shutdown().await; +} From 97c4d9b8a1e895fa9bd414885cca064cb8f42d5d Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:16:54 -0600 Subject: [PATCH 22/53] refactor(node): tighten model publishing after the simplify pass Drop the pass-through models seam so handlers call the Db methods directly, deduplicate the timestamp helpers and the hidden-refs config list, and serve the reconstruction GET from the stored release ref instead of re-verifying the manifest per request. Batch the claim's block-link writes and the sweep's session-link drops so they no longer pay a round trip per block or per expired session, and prefetch rebuild ranges in bounded concurrency during verification. In the CLI, open the upload session before packing so blocks stream out as they seal rather than buffering the whole model in memory, index only each file's fresh block entries for dedup, and sign the manifest through the shared helper via the keypair seed. Tests: make the duplicate-refund and expiry-slide assertions falsifiable, seed the expired-session fixture through the shared helper, and cover the private-repo denial legs for the reconstruction and claims routes. --- crates/twigpine-cli/Cargo.toml | 3 +- crates/twigpine-cli/src/model.rs | 210 ++++++++---------- .../twigpine-core/src/model/reconstruction.rs | 8 +- crates/twigpine-node/src/api/models.rs | 132 ++++++----- crates/twigpine-node/src/db/mod.rs | 4 +- crates/twigpine-node/src/db/model_queries.rs | 75 ++++--- crates/twigpine-node/src/git/store.rs | 41 ++-- crates/twigpine-node/src/models/claim.rs | 41 ++-- crates/twigpine-node/src/models/mod.rs | 100 +-------- crates/twigpine-node/src/models/sweep.rs | 4 +- crates/twigpine-node/src/models/verify.rs | 38 ++-- crates/twigpine-node/tests/models_api.rs | 114 +++++++--- crates/twigpine-node/tests/support/routes.rs | 4 +- 13 files changed, 374 insertions(+), 400 deletions(-) diff --git a/crates/twigpine-cli/Cargo.toml b/crates/twigpine-cli/Cargo.toml index d39d025e..b844b079 100644 --- a/crates/twigpine-cli/Cargo.toml +++ b/crates/twigpine-cli/Cargo.toml @@ -41,8 +41,9 @@ alloy = { version = "1", default-features = false, features = [ "rpc-types-eth", ] } +ed25519-dalek = { workspace = true } + [dev-dependencies] mockito = "1" tempfile = "3" tokio = { workspace = true } -ed25519-dalek = { workspace = true } diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index ae24c0c1..ea2edbd7 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -8,7 +8,6 @@ //! and polls until the node's verification publishes it. use anyhow::{bail, Context, Result}; -use base64::{engine::general_purpose::STANDARD as B64, Engine}; use clap::{Args, Subcommand}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -431,14 +430,6 @@ fn parse_parent(spec: &str) -> Result<((String, String), String)> { Ok(((owner.to_string(), name.to_string()), commit.to_string())) } -/// The detached signature file contents: base64-std over the domain-tagged -/// manifest bytes, same as `manifest::sign` but through the CLI Keypair -/// (which signs but does not expose its SigningKey). -fn sign_manifest_bytes(kp: &twigpine_core::identity::Keypair, manifest_bytes: &[u8]) -> String { - let sig = kp.sign(&manifest::signing_input(manifest_bytes)); - B64.encode(sig.to_bytes()) -} - fn read_head(path: &Path, n: u64) -> Result> { let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; let mut buf = Vec::new(); @@ -594,8 +585,9 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { // declared parent's when given. let mut priors: Vec = Vec::new(); let mut parent_ref: Option = None; - for commit in release_commits(&root) { - if let Some(rec) = fetch_reconstruction(&client, &owner, &name, &commit).await? { + let prior_commits = release_commits(&root); + for commit in &prior_commits { + if let Some(rec) = fetch_reconstruction(&client, &owner, &name, commit).await? { priors.push(rec); } } @@ -632,15 +624,50 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } - // 4. Pack every chunked file; shared chunks become terms into prior - // blocks, the rest seal into new blocks to upload. + // 4. Open (or resume) the upload session before packing, so each new + // block streams out as it seals instead of buffering the whole + // model in memory. + let state_path = git_dir.join(STATE_FILE_NAME); + let mut state = load_state(&state_path); + if !state.session_id.is_empty() { + let resp = client + .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) + .await + .context("session status request failed")?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + state = PublishState::default(); + } else { + let v: Value = read_json(resp, "session status").await?; + if v["state"].as_str() != Some("open") { + state = PublishState::default(); + } + } + } + if state.session_id.is_empty() { + let body = serde_json::to_vec(&json!({}))?; + let resp = client + .post(&format!("{base}/models/sessions"), &body) + .await?; + let v: Value = json_or_denial("open model session", resp).await?; + state.session_id = v["session_id"] + .as_str() + .context("session response had no session_id")? + .to_string(); + state.uploaded.clear(); + save_state(&state_path, &state)?; + } + let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); + let session_id = state.session_id.clone(); + + // 5. Pack every chunked file; shared chunks become terms into prior + // blocks, the rest seal into new blocks uploaded as they seal. let mut rec = Reconstruction::new(); - let mut new_blocks = Vec::new(); - let mut new_block_shas: HashSet = HashSet::new(); let mut files: Vec = Vec::new(); for path in &scan.chunked_files { let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; let packed = pack_file(path, file, &dedup)?; + // Make this file's fresh chunks visible to the next file's dedup. + dedup.add_block_entries(&packed.block_entries); let head = read_head(&root.join(path), 64)?; files.push(ManifestFile { path: path.clone(), @@ -655,12 +682,16 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { rec.blocks.push(e); } for b in packed.new_blocks { - if new_block_shas.insert(b.sha256.clone()) { - new_blocks.push(b); + let sha = b.sha256; + if uploaded.contains(&sha) { + continue; } + upload_block(&client, &base, &session_id, &sha, b.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded block {}", &sha[..16]); } - // Make this file's fresh chunks visible to the next file's dedup. - dedup.add(&rec); } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. @@ -669,13 +700,15 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { .iter() .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) .collect(); + let mut present: HashSet = rec.blocks.iter().map(|b| b.sha256.clone()).collect(); for sha in needed { - if rec.blocks.iter().any(|b| b.sha256 == sha) { + if present.contains(&sha) { continue; } let entry = all_entries .get(&sha) .with_context(|| format!("term references unknown block {sha}"))?; + present.insert(entry.sha256.clone()); rec.blocks.push(entry.clone()); } // A release with no chunked files has no chunked bytes to reconstruct: @@ -690,69 +723,24 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { }; let rec_sha = sha256_hex(&rec_bytes); - // 5. Open (or resume) the upload session and send the new blocks, then - // the reconstruction object as one more block. - let state_path = git_dir.join(STATE_FILE_NAME); - let mut state = load_state(&state_path); - if !state.session_id.is_empty() { - let resp = client - .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) - .await - .context("session status request failed")?; - if resp.status() == reqwest::StatusCode::NOT_FOUND { - state = PublishState::default(); - } else { - let v: Value = read_json(resp, "session status").await?; - if v["state"].as_str() != Some("open") { - state = PublishState::default(); - } - } - } - if state.session_id.is_empty() { - let body = serde_json::to_vec(&json!({ - "parent_release": parent_ref.as_ref().map(|p| p.commit.clone()), - }))?; - let resp = client - .post(&format!("{base}/models/sessions"), &body) - .await?; - let v: Value = json_or_denial("open model session", resp).await?; - state.session_id = v["session_id"] - .as_str() - .context("session response had no session_id")? - .to_string(); - state.uploaded.clear(); - save_state(&state_path, &state)?; - } - let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); - let session_id = state.session_id.clone(); - - let total = new_blocks.len() + usize::from(!rec_bytes.is_empty()); - for (i, block) in new_blocks.into_iter().enumerate() { - let sha = block.sha256; - if uploaded.contains(&sha) { - continue; - } - upload_block(&client, &base, &session_id, &sha, block.data).await?; - state.uploaded.push(sha.clone()); - uploaded.insert(sha); - save_state(&state_path, &state)?; - println!("uploaded block {}/{total}", i + 1); - } - if !rec_bytes.is_empty() && !uploaded.contains(&rec_sha) { - upload_block(&client, &base, &session_id, &rec_sha, rec_bytes.clone()).await?; + // 6. The reconstruction object goes up as one more content block. + let has_rec = !rec_bytes.is_empty(); + let rec_size = rec_bytes.len() as u64; + if has_rec && !uploaded.contains(&rec_sha) { + upload_block(&client, &base, &session_id, &rec_sha, rec_bytes).await?; state.uploaded.push(rec_sha.clone()); save_state(&state_path, &state)?; - println!("uploaded reconstruction object ({total}/{total})"); + println!("uploaded reconstruction object"); } - // 6. Managed .gitignore block, then stage the publishable set. + // 7. Managed .gitignore block, then stage the publishable set. let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); if new_gitignore != existing_gitignore { std::fs::write(&gitignore_path, &new_gitignore)?; } git(&root, &["add", "-A"])?; - // 7. Hash the git-stored files from the index (the exact bytes the + // 8. Hash the git-stored files from the index (the exact bytes the // commit stores), then write and stage the manifest. for path in &scan.git_files { let bytes = staged_blob(&root, path)?; @@ -773,12 +761,12 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { license: args.license.clone(), parent: parent_ref, files, - reconstruction: if rec_bytes.is_empty() { + reconstruction: if !has_rec { None } else { Some(ReconstructionRef { sha256: rec_sha, - size: rec_bytes.len() as u64, + size: rec_size, }) }, }; @@ -790,14 +778,27 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; std::fs::write( twigpine_dir.join("model-release.sig"), - format!("{}\n", sign_manifest_bytes(&kp, &manifest_bytes)), + format!( + "{}\n", + manifest::sign( + &ed25519_dalek::SigningKey::from_bytes(&kp.to_seed()), + &manifest_bytes, + ) + ), + )?; + git( + &root, + &[ + "add", + ".twigpine/model-release.json", + ".twigpine/model-release.sig", + ], )?; - git(&root, &["add", "-A"])?; - // 8. Commit when the index differs, push, and claim HEAD. + // 9. Commit when the index differs, push, and claim HEAD. let has_changes = git(&root, &["diff", "--cached", "--quiet"]).is_err(); if has_changes { - let n = release_commits(&root).len() + 1; + let n = prior_commits.len() + 1; git(&root, &["commit", "-m", &format!("model release {n}")])?; } else { // Nothing staged: a re-publish of identical content lands here, and @@ -844,7 +845,7 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let release_id = claim["release_id"].as_i64().unwrap_or_default(); println!("release {release_id} claimed; verifying"); - // 9. Poll until the verification worker settles the release. + // 10. Poll until the verification worker settles the release. let release_path = format!("{base}/models/releases/{commit}"); let deadline = Instant::now() + POLL_BUDGET; loop { @@ -886,22 +887,25 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { mod tests { use super::*; - const T: u64 = 1024; // test threshold + const THR: u64 = 1024; #[test] fn classify_by_threshold_tracking_and_ignore() { // Below threshold: tracked or unignored-untracked are git files. - assert_eq!(classify(T - 1, true, false, false, T), Class::Git); - assert_eq!(classify(T - 1, false, false, false, T), Class::Git); - assert_eq!(classify(T - 1, false, true, false, T), Class::Ignored); - assert_eq!(classify(T - 1, false, true, true, T), Class::Ignored); + assert_eq!(classify(THR - 1, true, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, false, false, THR), Class::Git); + assert_eq!(classify(THR - 1, false, true, false, THR), Class::Ignored); + assert_eq!(classify(THR - 1, false, true, true, THR), Class::Ignored); // At/above threshold: tracked refuses; untracked chunks unless // ignored outside the managed block. - assert_eq!(classify(T, true, false, false, T), Class::LargeTracked); - assert_eq!(classify(T + 1, true, true, false, T), Class::LargeTracked); - assert_eq!(classify(T, false, false, false, T), Class::Chunked); - assert_eq!(classify(T, false, true, true, T), Class::Chunked); - assert_eq!(classify(T, false, true, false, T), Class::Ignored); + assert_eq!(classify(THR, true, false, false, THR), Class::LargeTracked); + assert_eq!( + classify(THR + 1, true, true, false, THR), + Class::LargeTracked + ); + assert_eq!(classify(THR, false, false, false, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, true, THR), Class::Chunked); + assert_eq!(classify(THR, false, true, false, THR), Class::Ignored); } #[test] @@ -1036,32 +1040,6 @@ mod tests { ); } - #[test] - fn cli_signature_matches_manifest_sign() { - // The two paths sign the same domain-tagged bytes with the same key: - // manifest::sign takes a raw SigningKey, the CLI signs through Keypair. - let seed = [9u8; 32]; - let signing = ed25519_dalek::SigningKey::from_bytes(&seed); - let kp = twigpine_core::identity::Keypair::from_seed(&seed).unwrap(); - let m = Manifest { - schema: MANIFEST_SCHEMA_V1.to_string(), - repo: "alice/m".to_string(), - publisher_did: kp.did().to_string(), - license: "mit".to_string(), - parent: None, - files: vec![], - reconstruction: Some(ReconstructionRef { - sha256: "a".repeat(64), - size: 1, - }), - }; - let bytes = m.to_bytes().unwrap(); - let sig = sign_manifest_bytes(&kp, &bytes); - assert_eq!(sig, manifest::sign(&signing, &bytes)); - let parsed = manifest::verify(&bytes, &sig, &kp.did()).unwrap(); - assert_eq!(parsed.repo, "alice/m"); - } - #[test] fn remote_url_parses_both_schemes() { assert_eq!( diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 70d2a33e..97f391bb 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -182,7 +182,13 @@ impl DedupIndex { } pub fn add(&mut self, rec: &Reconstruction) { - for block in &rec.blocks { + self.add_block_entries(&rec.blocks); + } + + /// Index only `entries`: callers packing several files can add each + /// file's fresh block table instead of re-scanning every prior entry. + pub fn add_block_entries(&mut self, entries: &[BlockEntry]) { + for block in entries { for (i, chunk) in block.chunks.iter().enumerate() { // First writer wins: two priors carrying the same chunk are // interchangeable, so keep the earliest. diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index d20007e2..9c2e7c35 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -48,14 +48,6 @@ fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result Ok(()) } -#[derive(Debug, Deserialize, Default)] -pub struct OpenSessionBody { - /// Optional commit sha of the declared parent release. Informational at - /// open time; the claim re-anchors the parent through the manifest. - #[serde(default)] - pub parent_release: Option, -} - /// POST `/api/v1/repos/{owner}/{repo}/models/sessions` — open an upload /// session. Owner-only (a session writes bytes the owner is billed for) on a /// fully public repo. @@ -63,20 +55,17 @@ pub async fn open_model_session( State(state): State, Path((owner, name)): Path<(String, String)>, Extension(auth): Extension, - _body: Option>, + _body: Option>, ) -> Result { hosting_enabled(&state)?; let caller = &auth.0; let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; require_repo_owner(&record, caller)?; require_fully_public(&record, &rules)?; - let session = models::open_session( - &state.db, - caller, - &record.id, - state.config.model_session_ttl_secs, - ) - .await?; + let session = state + .db + .model_open_session(caller, &record.id, state.config.model_session_ttl_secs) + .await?; Ok(( axum::http::StatusCode::CREATED, Json(json!({ @@ -97,7 +86,9 @@ pub async fn get_model_session( let caller = &auth.0; let (record, _rules) = authorize_repo_read(&state, &owner, &name, Some(caller), "/").await?; require_repo_owner(&record, caller)?; - let session = models::load_session(&state.db, &id) + let session = state + .db + .model_load_session(&id) .await? .filter(|s| s.repo_id == record.id) .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; @@ -130,8 +121,8 @@ pub async fn put_model_block( "a model block PUT requires the session header".into(), )); }; - let pool = &state.db; - let Some(session) = models::load_session(pool, &session_id).await? else { + let db = &state.db; + let Some(session) = db.model_load_session(&session_id).await? else { return Err(AppError::NotFound("model upload session not found".into())); }; // authorize_repo_read 404s a repo the session owner can no longer read; @@ -168,19 +159,20 @@ pub async fn put_model_block( // node-wide quota, and it slides the session expiry in the same write. let session_cap = state.config.effective_model_max_session_bytes() as i64; let node_cap = state.config.model_node_quota_bytes as i64; - let Some(_) = models::admit_bytes( - pool, - &session.id, - declared as i64, - state.config.model_session_ttl_secs, - session_cap, - node_cap, - ) - .await? + let Some(_) = db + .model_admit_bytes( + &session.id, + declared as i64, + state.config.model_session_ttl_secs, + session_cap, + node_cap, + ) + .await? else { // Not admitted: re-check whether the session died (404 hides the // session) or a cap refused (named quota). - let session = models::load_session(pool, &session_id) + let session = db + .model_load_session(&session_id) .await? .filter(|s| s.state == "open" && s.expires_at > models::ts_now()); return match session { @@ -197,49 +189,48 @@ pub async fn put_model_block( .into_body() .into_data_stream() .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); - let outcome = store + if let Err(e) = store .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) - .await; - let outcome = match outcome { - Ok(o) => o, - Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; - return Err(match e { - BlockStoreError::DigestMismatch => { - AppError::BadRequest(format!("block body does not hash to the named id {sha}")) - } - BlockStoreError::TooLarge(cap) => { - AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) - } - BlockStoreError::Unknown => AppError::Conflict( - "the write's outcome is unknown; check the object before retrying".into(), - ), - other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), - }); - } - }; - let _ = outcome; // Stored and AlreadyPresent both leave the bytes stored. + .await + { + let _ = db.model_refund_bytes(&session.id, declared as i64).await; + return Err(match e { + BlockStoreError::DigestMismatch => { + AppError::BadRequest(format!("block body does not hash to the named id {sha}")) + } + BlockStoreError::TooLarge(cap) => { + AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + } + BlockStoreError::Unknown => AppError::Conflict( + "the write's outcome is unknown; check the object before retrying".into(), + ), + other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), + }); + } + // Stored and AlreadyPresent both leave the bytes stored. // Past this point the object exists; a bookkeeping failure must refund // the admission or the session's charge leaks until it expires. let size = match store.size(&block_id).await { Ok(s) => s.unwrap_or(declared), Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; + let _ = db.model_refund_bytes(&session.id, declared as i64).await; return Err(AppError::Internal(anyhow::anyhow!( "block size lookup failed: {e}" ))); } }; - let duplicate = match models::record_block(pool, &session.id, &sha, size, declared as i64).await + let duplicate = match db + .model_record_block(&session.id, &sha, size, declared as i64) + .await { Ok(d) => d, Err(e) => { - let _ = models::refund_bytes(pool, &session.id, declared as i64).await; - return Err(e); + let _ = db.model_refund_bytes(&session.id, declared as i64).await; + return Err(e.into()); } }; - let fresh = models::load_session(pool, &session.id).await?; + let fresh = db.model_load_session(&session.id).await?; Ok(Json(json!({ "received": fresh.as_ref().map(|s| s.bytes_received).unwrap_or(0), "duplicate": duplicate, @@ -327,7 +318,9 @@ pub async fn get_model_release( let caller = auth.map(|Extension(AuthenticatedDid(d))| d); let (record, _rules) = authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; - let release = models::release_by_commit(&state.db, &record.id, &commit) + let release = state + .db + .model_release_by_commit(&record.id, &commit) .await? .ok_or_else(|| AppError::NotFound("model release not found".into()))?; Ok(Json(release_view(&release))) @@ -350,25 +343,30 @@ pub async fn get_model_reconstruction( if !record.is_public || !rules.is_empty() { return Err(AppError::NotFound("model release not found".into())); } - let release = models::release_by_commit(&state.db, &record.id, &commit) + let release = state + .db + .model_release_by_commit(&record.id, &commit) .await? .filter(|r| r.state == "published") .ok_or_else(|| AppError::NotFound("model release not found".into()))?; - let (manifest_bytes, manifest) = models::claim::read_verified_manifest( - &state.git_bin, - &std::path::PathBuf::from(&record.disk_path), - &release.commit_sha, - &record.owner_did, - ) - .await?; - let _ = manifest_bytes; - let Some(rec_ref) = &manifest.reconstruction else { + // The stored reconstruction ref was bound when the release verified; + // re-reading and re-verifying the manifest per GET is wasted work. + let Some(sha) = state.db.model_reconstruction_sha(release.id).await? else { return Err(AppError::NotFound( "release has no reconstruction object".into(), )); }; let store = state.block_store.clone().expect("checked above"); - let bytes = models::read_block(&store, &rec_ref.sha256, rec_ref.size) + let size = store + .size( + &BlockId::parse(&sha) + .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?, + ) + .await + .ok() + .flatten() + .ok_or_else(|| AppError::NotFound("reconstruction object not stored".into()))?; + let bytes = models::read_block(&store, &sha, size) .await .map_err(|_| AppError::NotFound("reconstruction object not stored".into()))?; Ok(( diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 0fe0d0d9..3fb66e3c 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -524,13 +524,13 @@ pub struct MarkerCleanup { pub dead_letter: bool, } +pub mod model_queries; + /// The lifecycle states of a row in `pending_ref_transitions`. Persisted as a /// TEXT column with one of these string values; the constants are the canonical /// spellings, and tests + the recovery drain all use them so a typo on one /// side or the other cannot silently mismatch the other. #[allow(dead_code)] // constants are used by tests + the next-slice handler -pub mod model_queries; - pub mod pending_state { #[allow(dead_code)] pub const PREPARED: &str = "prepared"; diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 2244b6ce..272c96ec 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -1,13 +1,11 @@ //! Model-hosting queries. Timestamps follow the repo convention: rfc3339 //! text in TEXT columns, written and compared through the helpers here. -#[cfg(any(test, feature = "test-harness"))] -use sqlx::PgPool; use sqlx::{Postgres, Transaction}; use super::{Db, Result}; -fn ts_now() -> String { +pub(crate) fn ts_now() -> String { chrono::Utc::now().to_rfc3339() } @@ -258,6 +256,19 @@ impl Db { Ok(row.map(Into::into)) } + /// The reconstruction object sha a release was claimed with, if any. + /// The reconstruction GET serves by this stored ref: the manifest it + /// names is immutable under the pinned commit and was verified at claim. + pub async fn model_reconstruction_sha(&self, id: i64) -> Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT reconstruction_sha256 FROM model_releases WHERE id = $1", + ) + .bind(id) + .fetch_optional(&self.pool) + .await? + .flatten()) + } + pub async fn model_release_by_id(&self, id: i64) -> Result> { let row = sqlx::query_as::<_, ReleaseTuple>(&format!( "SELECT {RELEASE_COLS} FROM model_releases WHERE id = $1" @@ -499,31 +510,36 @@ impl Db { Ok(row.into()) } - /// Link `sha` to the release and drop it from the publisher's open - /// sessions, so the same bytes stop counting twice node-wide. - pub async fn model_tx_link_release_block( + /// Link `shas` to the release and drop them from the publisher's open + /// sessions, so the same bytes stop counting twice node-wide. Batched: + /// this runs inside the claim's advisory lock, so a manifest naming + /// thousands of blocks must not pay two round trips per block. + pub async fn model_tx_link_release_blocks( &self, tx: &mut Transaction<'_, Postgres>, release_id: i64, publisher_did: &str, - sha: &str, + shas: &[String], ) -> Result<()> { + if shas.is_empty() { + return Ok(()); + } sqlx::query( "INSERT INTO model_release_blocks (release_id, block_sha256) - VALUES ($1, $2) ON CONFLICT DO NOTHING", + SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING", ) .bind(release_id) - .bind(sha) + .bind(shas) .execute(&mut **tx) .await?; sqlx::query( "DELETE FROM model_session_blocks sb USING model_upload_sessions s WHERE s.id = sb.session_id AND s.owner_did = $1 - AND s.state = 'open' AND sb.block_sha256 = $2", + AND s.state = 'open' AND sb.block_sha256 = ANY($2)", ) .bind(publisher_did) - .bind(sha) + .bind(shas) .execute(&mut **tx) .await?; Ok(()) @@ -637,9 +653,9 @@ impl Db { .await?) } - pub async fn model_drop_session_blocks(&self, session_id: &str) -> Result<()> { - sqlx::query("DELETE FROM model_session_blocks WHERE session_id = $1") - .bind(session_id) + pub async fn model_drop_sessions_blocks(&self, session_ids: &[String]) -> Result<()> { + sqlx::query("DELETE FROM model_session_blocks WHERE session_id = ANY($1)") + .bind(session_ids) .execute(&self.pool) .await?; Ok(()) @@ -735,12 +751,6 @@ impl Db { } } -/// The PgPool behind a `Db`, for test fixtures that seed rows directly. -#[cfg(any(test, feature = "test-harness"))] -pub fn test_pool(db: &Db) -> &PgPool { - db.pool() -} - #[cfg(test)] mod tests { use super::*; @@ -762,17 +772,14 @@ mod tests { #[sqlx::test] async fn admit_bytes_enforces_session_cap_and_slides_expiry(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; - let s = db - .model_open_session("did:owner", "r1", 3600) - .await - .unwrap(); + let s = db.model_open_session("did:owner", "r1", 60).await.unwrap(); let first = db .model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) .await .unwrap() .expect("first admission"); assert_eq!(first.bytes_received, 100); - assert!(first.expires_at >= s.expires_at); + assert!(first.expires_at > s.expires_at); // Over the per-identity session cap: refused. assert!(db .model_admit_bytes(&s.id, 950, 3600, 1000, 10_000) @@ -795,11 +802,21 @@ mod tests { .await .unwrap(); let sha = "a".repeat(64); + // First PUT: admit the block's bytes, then record the link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("first admission"); assert!(!db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); - // Same block again: duplicate, admission refunded. + // Same block again: the second admission is charged then refunded + // when the record sees the existing link. + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .expect("second admission"); assert!(db.model_record_block(&s.id, &sha, 100, 100).await.unwrap()); let s2 = db.model_load_session(&s.id).await.unwrap().unwrap(); - assert_eq!(s2.bytes_received, 0); + assert_eq!(s2.bytes_received, 100); } #[sqlx::test] @@ -834,7 +851,9 @@ mod tests { db.model_expire_sessions().await.unwrap(), vec![s.id.clone()] ); - db.model_drop_session_blocks(&s.id).await.unwrap(); + db.model_drop_sessions_blocks(std::slice::from_ref(&s.id)) + .await + .unwrap(); // The block is now unreferenced: marked, then deletable past grace. assert_eq!(db.model_remark_liveness().await.unwrap(), 1); diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 52da7912..d2628d33 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -1,6 +1,16 @@ use anyhow::{bail, Context, Result}; use std::path::Path; use std::process::Command; +/// Ref namespaces clients must never see: `refs/gitlawb/requests/*` is +/// internal bookkeeping, and `refs/gitlawb/releases/*` pins published model +/// releases so gc never prunes them. One shared list keeps the +/// repo-config writers in lockstep. +const HIDDEN_REFS: &[(&str, &str)] = &[ + ("uploadpack.hideRefs", "refs/gitlawb/requests/"), + ("transfer.hideRefs", "refs/gitlawb/requests/"), + ("uploadpack.hideRefs", "refs/gitlawb/releases/"), + ("transfer.hideRefs", "refs/gitlawb/releases/"), +]; /// Initialize a new bare git repository with SHA-1 object format (default). /// @@ -88,18 +98,11 @@ pub fn init_bare(path: &Path) -> Result<()> { Ok(_) => {} } - // Hide the internal marker namespace from clone/fetch - // advertisement. `refs/gitlawb/requests/*` carries request UUIDs - // and would otherwise leak per-push metadata to every client and - // grow advertisement cost with push count. `refs/gitlawb/releases/*` - // pins published model releases so gc never prunes them; it is - // likewise not for clients. - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + // Hide the internal marker namespaces from clone/fetch + // advertisement: `refs/gitlawb/requests/*` would leak per-push + // metadata to every client and grow advertisement cost with push + // count. + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: same init-time local `git config` as above. let out = Command::new("git") .args(["config", "--add", key, value]) @@ -130,12 +133,7 @@ pub fn ensure_marker_hidden(repo_path: &Path) { } pub fn ensure_marker_hidden_checked(repo_path: &Path) -> Result<()> { - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + for &(key, value) in HIDDEN_REFS { // allow-unbounded-git: reached only through the #[allow(dead_code)] // ensure_marker_hidden wrapper; the push path runs this config through // verify_recovery_prereqs_bounded's timeout runner. @@ -218,12 +216,7 @@ pub async fn verify_recovery_prereqs_bounded( ); } } - for (key, value) in [ - ("uploadpack.hideRefs", "refs/gitlawb/requests/"), - ("transfer.hideRefs", "refs/gitlawb/requests/"), - ("uploadpack.hideRefs", "refs/gitlawb/releases/"), - ("transfer.hideRefs", "refs/gitlawb/releases/"), - ] { + for &(key, value) in HIDDEN_REFS { let current = run_git(git_bin, repo_path, &["config", "--get-all", key], timeout).await?; let already = String::from_utf8_lossy(¤t.stdout) .lines() diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 5d92cca8..84db6791 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -26,7 +26,6 @@ fn bad_request(msg: impl Into) -> AppError { AppError::BadRequest(msg.into()) } -/// Read `commit:path` bytes from the repo on disk, bounded. pub(crate) async fn git_show( git_bin: &str, disk_path: &std::path::Path, @@ -60,7 +59,6 @@ pub(crate) async fn git_show( } } -/// Whether commit `sha` resolves in the repo. pub async fn commit_exists( git_bin: &str, disk_path: &std::path::Path, @@ -117,13 +115,12 @@ pub async fn claim_release( let db = &state.db; let disk_path = std::path::PathBuf::from(&record.disk_path); - // The pushed commit must exist and carry the signed manifest. if !commit_exists(&state.git_bin, &disk_path, commit).await? { return Err(bad_request("commit not found in this repository")); } let (manifest_bytes, manifest) = read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; - let m_sha = super::manifest_sha256(&manifest_bytes); + let m_sha = twigpine_core::cid::sha256_hex(&manifest_bytes); let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); let blocks = super::referenced_blocks(state, &manifest).await?; @@ -150,8 +147,12 @@ pub async fn claim_release( // Lock the referenced block rows so a racing sweep cannot delete one // mid-claim, and require each to exist. if !blocks.is_empty() { - let present = db.model_tx_lock_present_blocks(&mut tx, &blocks).await?; - if let Some(missing) = blocks.iter().find(|b| !present.contains(b)) { + let present: std::collections::HashSet = db + .model_tx_lock_present_blocks(&mut tx, &blocks) + .await? + .into_iter() + .collect(); + if let Some(missing) = blocks.iter().find(|b| !present.contains(b.as_str())) { return Err(bad_request(format!( "manifest references block {} which is not stored on this node", &missing[..16] @@ -161,12 +162,18 @@ pub async fn claim_release( // Authorization: every referenced block must arrive through the caller's // open session, a live release of the caller's, or the declared parent. - let caller_session_blocks = db.model_tx_session_blocks(&mut tx, caller).await?; - let caller_release_blocks = db + let caller_session_blocks: std::collections::HashSet = db + .model_tx_session_blocks(&mut tx, caller) + .await? + .into_iter() + .collect(); + let caller_release_blocks: std::collections::HashSet = db .model_tx_publisher_release_blocks(&mut tx, caller) - .await?; - let parent_blocks: Vec = match &manifest.parent { - None => Vec::new(), + .await? + .into_iter() + .collect(); + let parent_blocks: std::collections::HashSet = match &manifest.parent { + None => std::collections::HashSet::new(), Some(parent) => { let (powner, pname) = parent .repo @@ -189,7 +196,7 @@ pub async fn claim_release( "declared parent is not a published release on this node", )); } - rows + rows.into_iter().collect() } }; for b in &blocks { @@ -258,12 +265,10 @@ pub async fn claim_release( .await?; let release_id = row.id; - for b in &blocks { - // Claimed blocks leave the caller's open sessions' charge: the - // release now carries them, so session bytes stop double-counting. - db.model_tx_link_release_block(&mut tx, release_id, caller, b) - .await?; - } + // Claimed blocks leave the caller's open sessions' charge: the + // release now carries them, so session bytes stop double-counting. + db.model_tx_link_release_blocks(&mut tx, release_id, caller, &blocks) + .await?; db.model_tx_recount_open_session_bytes(&mut tx, caller) .await?; diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index ee45d2b5..dfee0f64 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -4,8 +4,8 @@ //! re-checks it. //! //! All SQL lives in `crate::db::model_queries` as typed `Db` methods; the -//! free functions here are the thin `&Db`-taking seams the handlers and -//! workers share. +//! free functions here are the store read helpers the handlers and workers +//! share. pub mod claim; pub mod sweep; @@ -13,11 +13,12 @@ pub mod verify; use std::sync::Arc; -use crate::db::model_queries::{ModelRelease, ModelSession}; -use crate::db::Db; +use crate::db::model_queries::ModelRelease; use crate::error::AppError; use crate::state::AppState; +pub(crate) use crate::db::model_queries::ts_now; + /// Transport + store hard cap on one block (KTD1: 64 MiB target, 128 MiB cap). pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; @@ -26,98 +27,8 @@ pub const MAX_BLOCK_BYTES: u64 = 128 * 1024 * 1024; /// lock is what makes them safe under racing claims. pub(crate) const CLAIM_LOCK_KEY: i64 = 0x6D6F64656C636C61; // "modelcla" -pub type SessionRow = ModelSession; pub type ReleaseRow = ModelRelease; -/// rfc3339 UTC `secs` from now: the repo's TEXT timestamp convention. -pub fn ts_from_now(secs: i64) -> String { - (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339() -} - -pub fn ts_now() -> String { - chrono::Utc::now().to_rfc3339() -} - -/// 256-bit random session id, hex-encoded: the bearer capability for block -/// PUTs. Anyone holding it may append blocks to the session it names, so it -/// is never logged or returned to anyone but its creator. -pub fn new_session_id() -> String { - hex::encode(rand::random::<[u8; 32]>()) -} - -pub async fn open_session( - db: &Db, - owner_did: &str, - repo_id: &str, - ttl_secs: u64, -) -> Result { - Ok(db.model_open_session(owner_did, repo_id, ttl_secs).await?) -} - -pub async fn load_session(db: &Db, id: &str) -> Result, AppError> { - Ok(db.model_load_session(id).await?) -} - -/// Atomically admit `claimed` bytes against the caller's per-identity -/// open-session cap and the node-wide quota (claimed quota plus every open -/// session's bytes), sliding the session's expiry forward in the same -/// update. Returns the post-update row when admitted, `None` when the -/// session is closed, expired, or the admission would exceed a cap; the -/// caller re-checks the session to pick the honest denial. -pub async fn admit_bytes( - db: &Db, - session_id: &str, - claimed: i64, - ttl_secs: u64, - session_cap: i64, - node_cap: i64, -) -> Result, AppError> { - Ok(db - .model_admit_bytes(session_id, claimed, ttl_secs, session_cap, node_cap) - .await?) -} - -/// Refund a previously admitted charge when the store or the bookkeeping -/// fails. Best-effort under races; an expired session frees the bytes anyway. -pub async fn refund_bytes(db: &Db, session_id: &str, bytes: i64) -> Result<(), AppError> { - db.model_refund_bytes(session_id, bytes).await?; - Ok(()) -} - -/// Book the stored block against the session inside one transaction. Returns -/// `true` when this PUT was a duplicate within the session (the admission -/// credit was refunded). -pub async fn record_block( - db: &Db, - session_id: &str, - block_sha: &str, - size: u64, - admitted: i64, -) -> Result { - Ok(db - .model_record_block(session_id, block_sha, size, admitted) - .await?) -} - -pub async fn release_by_commit( - db: &Db, - repo_id: &str, - commit: &str, -) -> Result, AppError> { - Ok(db.model_release_by_commit(repo_id, commit).await?) -} - -pub async fn release_by_id(db: &Db, id: i64) -> Result, AppError> { - Ok(db.model_release_by_id(id).await?) -} - -/// sha256 of the manifest bytes, as hex. -pub fn manifest_sha256(manifest_bytes: &[u8]) -> String { - use sha2::Digest; - hex::encode(sha2::Sha256::digest(manifest_bytes)) -} - -/// Collect `len` bytes of a stored object starting at `start`. pub async fn read_range( store: &Arc, sha: &str, @@ -135,7 +46,6 @@ pub async fn read_range( Ok(out) } -/// Collect a stored object's whole body via a range read. pub async fn read_block( store: &Arc, sha: &str, diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index c11f6ea9..00202bfa 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -24,9 +24,7 @@ pub async fn sweep_once(state: &AppState) -> Result { // session no longer confers liveness. let expired = db.model_expire_sessions().await?; stats.sessions_expired = expired.len() as u64; - for sid in &expired { - db.model_drop_session_blocks(sid).await?; - } + db.model_drop_sessions_blocks(&expired).await?; // Re-mark liveness both ways: blocks that lost every live reference get // an unreferenced_since stamp; blocks that regained one clear theirs. diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 5a823e36..ae35c3bb 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -3,6 +3,7 @@ //! then mark the release published (and pin the hidden ref). Rejection frees //! the quota reservation and drops the block refs. +use futures::StreamExt; use sha2::Digest; use std::io::Write; use twigpine_core::model::manifest::{detect_format, StorageKind}; @@ -34,7 +35,7 @@ impl Write for VerifySink { /// Verify one release end to end. Idempotent: a release no longer in /// `verifying` returns immediately. pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), AppError> { - let Some(release) = super::release_by_id(&state.db, release_id).await? else { + let Some(release) = state.db.model_release_by_id(release_id).await? else { return Ok(()); }; if release.state != "verifying" { @@ -68,7 +69,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await; } }; - if super::manifest_sha256(&manifest_bytes) != release.manifest_sha256 { + if twigpine_core::cid::sha256_hex(&manifest_bytes) != release.manifest_sha256 { return reject_release(state, release_id, "manifest digest changed since claim").await; } @@ -102,10 +103,12 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App } }; + let rec_by_path: std::collections::HashMap<&str, _> = + rec.files.iter().map(|f| (f.path.as_str(), f)).collect(); for file in &manifest.files { match file.storage { StorageKind::Chunked => { - let Some(entry) = rec.files.iter().find(|f| f.path == file.path).cloned() else { + let Some(&entry) = rec_by_path.get(file.path.as_str()) else { return reject_release( state, release_id, @@ -126,7 +129,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // backend. Blocks were hash-verified at write, so the // whole-file digest is the check that matters here. let slices = match twigpine_core::model::reconstruction::map_file_range( - &entry, &rec, 0, file.size, + entry, &rec, 0, file.size, ) { Ok(s) => s, Err(e) => { @@ -142,15 +145,22 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App hasher: sha2::Sha256::new(), head: Vec::new(), }; - for slice in &slices { - let bytes = match super::read_range( - &store, - &slice.block, - slice.offset, - slice.len, - ) - .await - { + // Ordered prefetch: `buffered` preserves order while + // overlapping the store's per-slice round trips. + let jobs = slices + .iter() + .map(|s| (s.block.clone(), s.offset, s.len)) + .collect::>(); + let fetched = + futures::stream::iter(jobs.into_iter().map(|(block, offset, len)| { + let store = store.clone(); + async move { super::read_range(&store, &block, offset, len).await } + })) + .buffered(4) + .collect::>() + .await; + for bytes in fetched { + let bytes = match bytes { Ok(b) => b, Err(e) => { return reject_release( @@ -197,7 +207,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await { Ok(Some(bytes)) => { - let got = hex::encode(sha2::Sha256::digest(&bytes)); + let got = twigpine_core::cid::sha256_hex(&bytes); if got != file.sha256 || bytes.len() as u64 != file.size { return reject_release( state, diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index 236641f4..0d3116a4 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -9,20 +9,14 @@ mod support; use serde_json::{json, Value}; -use sha2::Digest; +use support::bounded_client; use support::signing::signed_request; +use twigpine_core::cid::sha256_hex; use twigpine_core::http_sig::sign_request; use twigpine_core::identity::Keypair; use twigpine_node::test_harness::{spawn_node, TestNode}; -fn bounded_client() -> reqwest::Client { - reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(30)) - .build() - .expect("client builds") -} - fn sessions_path(owner: &str, repo: &str) -> String { format!("/api/v1/repos/{owner}/{repo}/models/sessions") } @@ -330,7 +324,7 @@ async fn put_block_without_session_header_unauthorized(pool: sqlx::PgPool) { let client = bounded_client(); let owner_did = Keypair::generate().did().to_string(); node.seed_repo(&owner_did, "model", true).await; - let sha = hex::encode(sha2::Sha256::digest(b"block")); + let sha = sha256_hex(b"block"); let resp = put_block( &client, @@ -356,7 +350,7 @@ async fn put_block_bogus_session_not_found(pool: sqlx::PgPool) { let owner_did = Keypair::generate().did().to_string(); node.seed_repo(&owner_did, "model", true).await; let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -384,7 +378,7 @@ async fn put_block_session_for_other_repo_not_found(pool: sqlx::PgPool) { node.seed_repo(&owner_did, "model-b", true).await; let session_id = seed_open_session(&node, &repo_a, &owner_did).await; let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -410,21 +404,16 @@ async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { let owner_did = Keypair::generate().did().to_string(); let repo_id = node.seed_repo(&owner_did, "model", true).await; let session_id = "e".repeat(64); - sqlx::query( - "INSERT INTO model_upload_sessions - (id, owner_did, repo_id, created_at, expires_at, bytes_received, state) - VALUES ($1,$2,$3,$4,$5,0,'open')", - ) - .bind(&session_id) - .bind(&owner_did) - .bind(&repo_id) - .bind(chrono::Utc::now().to_rfc3339()) - .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) - .execute(&pool) - .await - .expect("seed expired session"); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); let body = b"block".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, @@ -441,10 +430,6 @@ async fn put_block_expired_session_not_found(pool: sqlx::PgPool) { node.shutdown().await; } -/// Happy path: a block whose body hashes to the id in the path is stored, -/// reported with the session's running byte count and `duplicate:false`; -/// resending it reports `duplicate:true`; a body that does not match the -/// named id is refused with 400. #[sqlx::test] async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) { let node = spawn_node(pool).await; @@ -454,7 +439,7 @@ async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) let session_id = seed_open_session(&node, &repo_id, &owner_did).await; let body = b"the quick brown fox".to_vec(); - let sha = hex::encode(sha2::Sha256::digest(&body)); + let sha = sha256_hex(&body); let resp = put_block( &client, &node.base_url, @@ -728,3 +713,72 @@ async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { node.shutdown().await; } + +/// The reconstruction GET and the claims POST hide a repo that is not fully +/// public: every caller class gets the same 404, none reach the store or the +/// commit lookup. The deny sweep cannot drive the hostile-only legs for the +/// reconstruction route, so they live here. +#[sqlx::test] +async fn reconstruction_and_claims_deny_on_private_repo(pool: sqlx::PgPool) { + let node = spawn_node(pool).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let stranger = Keypair::generate(); + let owner_did = owner.did().to_string(); + node.seed_repo(&owner_did, "model", false).await; + let commit = "c".repeat(40); + let rec_path = format!( + "{}/reconstruction", + release_path(&owner_did, "model", &commit) + ); + + for (label, req) in [ + ( + "anon GET reconstruction", + client.get(format!("{}{}", node.base_url, rec_path)), + ), + ( + "stranger GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &stranger, + ), + ), + ( + "owner GET reconstruction", + signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &rec_path, + Vec::new(), + &owner, + ), + ), + ( + "stranger POST claims", + signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &claims_path(&owner_did, "model"), + serde_json::to_vec(&serde_json::json!({ + "commit": commit, + "branch": "main", + })) + .expect("claim body"), + &stranger, + ) + .header("content-type", "application/json"), + ), + ] { + let resp = req.send().await.expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "{label}"); + } + + node.shutdown().await; +} diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 07f8c411..4cf536ba 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -1055,7 +1055,9 @@ pub fn deny_bearing_routes() -> &'static [Row] { gate: GateClass::OwnerGate, handler: "models::claim_model_release", // A well-formed claim body; the owner twin passes the owner gate and - // fails the commit lookup (400), which is still a Not403 twin. + // fails the commit lookup (the seeded placeholder disk_path makes + // it a 500 today, a real on-disk repo would make it 400), which is + // still a Not403 twin. body: Some(r#"{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","branch":"main"}"#), needs: NO_ENTITY, reach: Reach::None, From 0e7fb3c43e74cfc92976d8eb06f391d88747c7e1 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:28:21 -0600 Subject: [PATCH 23/53] fix(node): harden model publishing after the review pass Address the correctness and security review findings on the publish path: - claim-side block reachability now honors wall-clock session expiry, so a session swept lazily cannot launder references between expiry and the periodic sweep. - the node-wide quota check runs after claimed blocks leave the session charge; before, they counted twice and could falsely exhaust the cap. - claim and release-reject take the same advisory lock, closing the freed-vs-referenced race that could refund quota for live blocks. - block admission serializes through a global advisory lock so racing PUTs on different sessions cannot overshoot per-owner or node caps. - the sweep's liveness re-check locks the row first, then tests in a second statement; the folded form read a pre-lock snapshot and could delete a block a racing claim just referenced. - charge moves off sessions subtract exactly the claimed set, preserving bytes admitted but not yet recorded by a PUT still in flight. - verification consumes the ordered prefetch stream instead of collecting it, so a rebuilt file costs block-sized memory; the CLI packs on a blocking thread and uploads each block as it seals. - all-git releases (no reconstruction object) verify instead of being admitted then deterministically rejected; manifests naming chunked files without one are refused at claim. - the verifier refuses commits carrying files the manifest never named, and claims require manifest.repo to name the claimed repository. - publish is conditional on the row still verifying; a mid-verify rejection now unwinds the just-written release ref instead of leaving it advertised. - the claim path pins the commit under the hidden release ref immediately, closing the force-push-plus-gc window before publish, and write_release_ref ensures the hideRefs config itself rather than relying on the warn-and-proceed push path. - block PUT error paths refund admission AND delete the orphaned store object; a vanished object after write is an error, not a fabricated size, and body-stream failures return 400 instead of 500. - stale verifying rows past six hours are rejected by the sweep so a wedged release frees the publisher's one-verifying slot. - the CLI stages exactly the scanned publishable set via a NUL pathspec rather than `git add -A`, resolves staged blobs through the index instead of revspec syntax, escapes gitignore metacharacters in the managed block, and retries transient status-read failures while polling. - misc: owner DIDs are canonicalized before manifest verification, reconstruction block sums are validated, range arithmetic is checked, and attacker-controlled ids are truncated safely in error messages. --- crates/twigpine-cli/src/model.rs | 164 +++++++++++++--- .../twigpine-core/src/model/reconstruction.rs | 83 ++++++--- crates/twigpine-node/src/api/models.rs | 23 ++- crates/twigpine-node/src/blockstore/fs.rs | 2 +- crates/twigpine-node/src/blockstore/mod.rs | 4 + crates/twigpine-node/src/blockstore/s3.rs | 2 +- crates/twigpine-node/src/db/model_queries.rs | 154 +++++++++++---- crates/twigpine-node/src/git/store.rs | 2 +- crates/twigpine-node/src/models/claim.rs | 101 ++++++---- crates/twigpine-node/src/models/mod.rs | 5 +- crates/twigpine-node/src/models/sweep.rs | 11 ++ crates/twigpine-node/src/models/verify.rs | 176 +++++++++++++++--- 12 files changed, 566 insertions(+), 161 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index ea2edbd7..9805a892 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -22,7 +22,9 @@ use twigpine_core::model::manifest::{ self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, }; -use twigpine_core::model::reconstruction::{pack_file, BlockEntry, DedupIndex, Reconstruction}; +use twigpine_core::model::reconstruction::{ + pack_file_with, BlockEntry, DedupIndex, Reconstruction, +}; use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; use crate::identity::load_keypair_from_dir; @@ -270,6 +272,39 @@ fn tracked_paths(root: &Path) -> Result> { /// Paths listed inside the managed .gitignore block (empty when there is no /// block): previously published chunked files. +/// One repo-relative path as a gitignore pattern line: pattern +/// metacharacters and a trailing space are backslash-escaped. +fn escape_gitignore_path(p: &str) -> String { + let mut out = String::new(); + let mut chars = p.chars().peekable(); + while let Some(c) = chars.next() { + if matches!(c, '\\' | '!' | '#' | '[' | ']') { + out.push('\\'); + } + if c == ' ' && chars.peek().is_none() { + out.push('\\'); + } + out.push(c); + } + out +} + +fn unescape_gitignore_path(line: &str) -> String { + let mut out = String::new(); + let mut escaped = false; + for c in line.chars() { + if escaped { + out.push(c); + escaped = false; + } else if c == '\\' { + escaped = true; + } else { + out.push(c); + } + } + out +} + fn managed_block_paths(gitignore: &str) -> Vec { let mut inside = false; let mut out = Vec::new(); @@ -283,7 +318,7 @@ fn managed_block_paths(gitignore: &str) -> Vec { break; } if inside && !t.is_empty() { - out.push(t.to_string()); + out.push(unescape_gitignore_path(t)); } } out @@ -376,7 +411,7 @@ fn upsert_managed_block(existing: &str, paths: &[String]) -> String { out.push(String::new()); } out.push(GITIGNORE_BEGIN.to_string()); - out.extend(paths.iter().cloned()); + out.extend(paths.iter().map(|p| escape_gitignore_path(p))); out.push(GITIGNORE_END.to_string()); } let mut s = out.join("\n"); @@ -440,7 +475,18 @@ fn read_head(path: &Path, n: u64) -> Result> { /// Bytes of the staged index blob for `path`: exactly what the release /// commit will store, filters and symlink handling included. fn staged_blob(root: &Path, path: &str) -> Result> { - Ok(git(root, &["show", &format!(":{path}")])?.stdout) + // Resolve the blob sha through the index rather than `:{path}` revspec + // syntax: a path that opens with magic characters is parsed as revspec + // there, not as a filename. + let out = git(root, &["ls-files", "-s", "-z", "--", path])?; + let stdout = String::from_utf8(out.stdout).context("ls-files output was not utf-8")?; + // ` \t`: the sha is the second blank field. + let sha = stdout + .split(' ') + .nth(1) + .filter(|s| !s.is_empty()) + .with_context(|| format!("{path} is not staged in the index"))?; + Ok(git(root, &["cat-file", "blob", sha])?.stdout) } /// Fetch a prior release's reconstruction object for dedup. A 404 means the @@ -664,34 +710,56 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let mut rec = Reconstruction::new(); let mut files: Vec = Vec::new(); for path in &scan.chunked_files { - let file = std::fs::File::open(root.join(path)).with_context(|| format!("open {path}"))?; - let packed = pack_file(path, file, &dedup)?; + // Pack on a blocking thread and upload each block as it seals: a + // bounded channel keeps resident memory to a couple of blocks + // rather than the whole file. The dedup index moves to the thread + // through an Arc and comes back when it finishes. + let shared_dedup = std::sync::Arc::new(std::mem::take(&mut dedup)); + let task_dedup = shared_dedup.clone(); + let (block_tx, mut block_rx) = + tokio::sync::mpsc::channel::(2); + let pack_path = path.clone(); + let pack_root = root.clone(); + let pack_task = tokio::task::spawn_blocking(move || { + let file = std::fs::File::open(pack_root.join(&pack_path)) + .map_err(|e| std::io::Error::new(e.kind(), format!("open {pack_path}: {e}")))?; + pack_file_with(&pack_path, file, &task_dedup, move |block| { + block_tx + .blocking_send(block) + .map_err(|_| std::io::Error::other("block upload channel closed")) + }) + }); + while let Some(block) = block_rx.recv().await { + let sha = block.sha256; + if uploaded.contains(&sha) { + continue; + } + upload_block(&client, &base, &session_id, &sha, block.data).await?; + state.uploaded.push(sha.clone()); + uploaded.insert(sha.clone()); + save_state(&state_path, &state)?; + println!("uploaded block {}", &sha[..16]); + } + let (file_entry, block_entries) = pack_task + .await + .context("pack task failed")? + .with_context(|| format!("pack {path}"))?; + dedup = std::sync::Arc::try_unwrap(shared_dedup).unwrap_or_else(|a| (*a).clone()); // Make this file's fresh chunks visible to the next file's dedup. - dedup.add_block_entries(&packed.block_entries); + dedup.add_block_entries(&block_entries); let head = read_head(&root.join(path), 64)?; files.push(ManifestFile { path: path.clone(), - size: packed.file.size, - sha256: packed.file.sha256.clone(), + size: file_entry.size, + sha256: file_entry.sha256.clone(), format: detect_format(&head, path), storage: StorageKind::Chunked, }); - rec.files.push(packed.file); - for e in packed.block_entries { + rec.files.push(file_entry); + for e in block_entries { all_entries.insert(e.sha256.clone(), e.clone()); rec.blocks.push(e); } - for b in packed.new_blocks { - let sha = b.sha256; - if uploaded.contains(&sha) { - continue; - } - upload_block(&client, &base, &session_id, &sha, b.data).await?; - state.uploaded.push(sha.clone()); - uploaded.insert(sha.clone()); - save_state(&state_path, &state)?; - println!("uploaded block {}", &sha[..16]); - } } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. @@ -733,12 +801,42 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { println!("uploaded reconstruction object"); } - // 7. Managed .gitignore block, then stage the publishable set. + // 7. Managed .gitignore block, then stage exactly the publishable set + // through a NUL pathspec: a bare `git add -A` would sweep in work the + // scan never saw (files created or un-ignored during the upload, or + // index changes staged for something else). let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); if new_gitignore != existing_gitignore { std::fs::write(&gitignore_path, &new_gitignore)?; } - git(&root, &["add", "-A"])?; + let pathspec_path = git_dir.join("twigpine-model-pathspec"); + { + let mut spec = Vec::new(); + for p in &scan.git_files { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + for p in [ + ".gitignore", + ".twigpine/model-release.json", + ".twigpine/model-release.sig", + ] { + spec.extend_from_slice(p.as_bytes()); + spec.push(0); + } + std::fs::write(&pathspec_path, spec)?; + } + let staged = git( + &root, + &[ + "add", + "-A", + "--pathspec-file-nul", + &format!("--pathspec-from-file={}", pathspec_path.display()), + ], + ); + let _ = std::fs::remove_file(&pathspec_path); + staged?; // 8. Hash the git-stored files from the index (the exact bytes the // commit stores), then write and stage the manifest. @@ -849,7 +947,23 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let release_path = format!("{base}/models/releases/{commit}"); let deadline = Instant::now() + POLL_BUDGET; loop { - let resp = client.get_signed(&release_path).await?; + // One transport hiccup should not abort the publish; the signed + // status read is idempotent, so retry it a few times. + let resp = 'poll: { + let mut last = None; + for _ in 0..3 { + match client.get_signed(&release_path).await { + Ok(r) => break 'poll r, + Err(e) => { + last = Some(e); + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + } + return Err(last + .expect("three attempts ran") + .context("release status request failed")); + }; let v: Value = read_json(resp, "release status").await?; match v["state"].as_str() { Some("published") => { diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 97f391bb..0b7401fd 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -99,6 +99,21 @@ impl Reconstruction { /// Structural sanity: terms index real blocks, chunk ranges are ordered, /// and each file's terms sum to its declared size. pub fn validate(&self) -> Result<(), ModelError> { + for block in &self.blocks { + let sum: u64 = block + .chunks + .iter() + .try_fold(0u64, |acc, c| acc.checked_add(c.len)) + .ok_or_else(|| { + ModelError::Invalid(format!("block {} chunk lengths overflow", block.sha256)) + })?; + if sum != block.size { + return Err(ModelError::Invalid(format!( + "block {} chunks sum to {sum} but the entry declares {}", + block.sha256, block.size + ))); + } + } let blocks: HashMap<&str, &BlockEntry> = self.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect(); for file in &self.files { @@ -128,15 +143,19 @@ impl Reconstruction { } let span: u64 = block.chunks[term.chunk_start as usize..term.chunk_end as usize] .iter() - .map(|c| c.len) - .sum(); + .try_fold(0u64, |acc, c| acc.checked_add(c.len)) + .ok_or_else(|| { + ModelError::Invalid(format!("{}: term lengths overflow", file.path)) + })?; if span != term.length { return Err(ModelError::Invalid(format!( "{}: term length {span} != declared {}", file.path, term.length ))); } - total += term.length; + total = total.checked_add(term.length).ok_or_else(|| { + ModelError::Invalid(format!("{}: file size overflow", file.path)) + })?; } if total != file.size { return Err(ModelError::Invalid(format!( @@ -162,7 +181,7 @@ impl Default for Reconstruction { /// Chunk-sha lookup over prior reconstruction objects, the dedup surface: /// a chunk whose hash a prior release already stored can be referenced by /// term instead of re-uploaded. -#[derive(Default)] +#[derive(Default, Clone)] pub struct DedupIndex { /// chunk sha256 -> (block sha256, chunk index inside that block) by_chunk: HashMap, @@ -203,14 +222,14 @@ impl DedupIndex { /// Seal the accumulating block of new chunks: patch its id into the terms /// written while it was still open, then append the block-table entry and /// queue the bytes for upload. -fn seal_pending( +fn seal_pending std::io::Result<()>>( pending: &mut Vec, terms: &mut [Term], block_entries: &mut Vec, - new_blocks: &mut Vec, -) { + on_block: &mut F, +) -> std::io::Result<()> { if pending.is_empty() { - return; + return Ok(()); } let chunks = std::mem::take(pending); let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum::()); @@ -241,7 +260,7 @@ fn seal_pending( }) .collect(), }); - new_blocks.push(block); + on_block(block) } /// What `pack_file` produced: the file's entry, the new blocks to store and @@ -254,16 +273,38 @@ pub struct PackedFile { /// Chunk and pack one file, reusing terms for chunks a prior reconstruction /// already holds (`dedup`). `path` is the repo-relative path recorded in the -/// entry. +/// entry. Every sealed block is held in the result; publishers of large +/// files should prefer `pack_file_with`, which keeps memory bounded by a +/// block instead of the file. pub fn pack_file( path: &str, reader: R, dedup: &DedupIndex, ) -> std::io::Result { + let mut new_blocks: Vec = Vec::new(); + let (file, block_entries) = pack_file_with(path, reader, dedup, |b| { + new_blocks.push(b); + Ok(()) + })?; + Ok(PackedFile { + file, + new_blocks, + block_entries, + }) +} + +/// `pack_file` with each sealed block handed to `on_block` as it finishes: +/// the caller can upload and drop it while the file is still packing, so a +/// file of any size packs in block-sized memory. +pub fn pack_file_with std::io::Result<()>>( + path: &str, + reader: R, + dedup: &DedupIndex, + mut on_block: F, +) -> std::io::Result<(FileEntry, Vec)> { let mut file_hasher = sha2::Sha256::new(); let mut terms: Vec = Vec::new(); - let mut new_blocks: Vec = Vec::new(); let mut block_entries: Vec = Vec::new(); // Chunks not found in `dedup` accumulate into one pending block that // seals only at the target size or EOF. Sealing on every reused-chunk @@ -312,22 +353,12 @@ pub fn pack_file( }), } if pending_bytes >= BLOCK_TARGET { - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; pending_bytes = 0; } } } - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; let file = FileEntry { path: path.to_string(), @@ -335,11 +366,7 @@ pub fn pack_file( sha256: hex::encode(file_hasher.finalize()), terms, }; - Ok(PackedFile { - file, - new_blocks, - block_entries, - }) + Ok((file, block_entries)) } /// Byte-range mapping: which slices of which blocks serve file bytes diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 9c2e7c35..d62770a6 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -204,20 +204,30 @@ pub async fn put_model_block( BlockStoreError::Unknown => AppError::Conflict( "the write's outcome is unknown; check the object before retrying".into(), ), + BlockStoreError::Body(e) => { + AppError::BadRequest(format!("block body could not be read: {e}")) + } other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), }); } // Stored and AlreadyPresent both leave the bytes stored. // Past this point the object exists; a bookkeeping failure must refund - // the admission or the session's charge leaks until it expires. + // the admission or the session's charge leaks until it expires, and + // must delete the store object or the sweep can never find it (its + // candidate list is model_blocks rows). let size = match store.size(&block_id).await { - Ok(s) => s.unwrap_or(declared), - Err(e) => { + Ok(Some(s)) => s, + r => { let _ = db.model_refund_bytes(&session.id, declared as i64).await; - return Err(AppError::Internal(anyhow::anyhow!( - "block size lookup failed: {e}" - ))); + let _ = store.delete(&block_id).await; + return Err(match r { + Ok(None) => AppError::Internal(anyhow::anyhow!( + "block {sha} absent immediately after write" + )), + Err(e) => AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")), + Ok(Some(_)) => unreachable!(), + }); } }; let duplicate = match db @@ -227,6 +237,7 @@ pub async fn put_model_block( Ok(d) => d, Err(e) => { let _ = db.model_refund_bytes(&session.id, declared as i64).await; + let _ = store.delete(&block_id).await; return Err(e.into()); } }; diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 61da56b1..94439bf7 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -81,7 +81,7 @@ impl BlockStore for FsBlockStore { let mut len: u64 = 0; let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs index 4a89325d..d0fd902e 100644 --- a/crates/twigpine-node/src/blockstore/mod.rs +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -95,6 +95,10 @@ pub enum BlockStoreError { /// unknown. #[error("the write's outcome is unknown; check size() before retrying")] Unknown, + /// The body stream itself failed (client abort, truncated upload): a + /// caller fault, distinct from a store-side `Io`. + #[error("body stream error: {0}")] + Body(io::Error), #[error("i/o error: {0}")] Io(#[from] io::Error), #[error("backend error: {0}")] diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index afafdbc2..29b29def 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -196,7 +196,7 @@ impl BlockStore for S3BlockStore { // ever resident, never the whole body. let result: Result<(), BlockStoreError> = async { while let Some(chunk) = body.next().await { - let chunk = chunk?; + let chunk = chunk.map_err(BlockStoreError::Body)?; len = len.saturating_add(chunk.len() as u64); if len > max_len { return Err(BlockStoreError::TooLarge(max_len)); diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 272c96ec..3db76275 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -25,6 +25,11 @@ pub struct ModelSession { type SessionTuple = (String, String, String, String, i64, String); +/// Global advisory key serializing block-byte admission across sessions +/// (see `model_admit_bytes`). Distinct from `CLAIM_LOCK_KEY` in +/// `crate::models`, which serializes claim admission. +const MODEL_ADMIT_LOCK: i64 = 0x6D6F64656C61646D; // "modeladm" + const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; impl From for ModelSession { @@ -149,6 +154,16 @@ impl Db { session_cap: i64, node_cap: i64, ) -> Result> { + // Serialize admissions process-wide: the per-owner and node-wide cap + // terms read other sessions' bytes_received, and two concurrent PUTs + // on different sessions would otherwise admit against the same stale + // sums. The critical section is one UPDATE, so the global key costs + // nothing next to the upload itself. + let mut tx = self.pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(MODEL_ADMIT_LOCK) + .execute(&mut *tx) + .await?; let row = sqlx::query_as::<_, SessionTuple>(&format!( "UPDATE model_upload_sessions s SET bytes_received = s.bytes_received + $1, @@ -174,8 +189,9 @@ impl Db { .bind(ts_now()) .bind(session_cap) .bind(node_cap) - .fetch_optional(&self.pool) + .fetch_optional(&mut *tx) .await?; + tx.commit().await?; Ok(row.map(Into::into)) } @@ -256,6 +272,19 @@ impl Db { Ok(row.map(Into::into)) } + /// Ids of `verifying` releases stuck past `stale_secs`: the worker + /// retries them forever today, so the sweep rejects them to un-wedge + /// the publisher's one-verifying slot. + pub async fn model_stale_verifying(&self, stale_secs: i64) -> Result> { + Ok(sqlx::query_scalar( + "SELECT id FROM model_releases + WHERE state = 'verifying' AND created_at < $1", + ) + .bind(ts_from_now(-stale_secs)) + .fetch_all(&self.pool) + .await?) + } + /// The reconstruction object sha a release was claimed with, if any. /// The reconstruction GET serves by this stored ref: the manifest it /// names is immutable under the pinned commit and was verified at claim. @@ -354,9 +383,10 @@ impl Db { Ok(sqlx::query_scalar( "SELECT sb.block_sha256 FROM model_session_blocks sb JOIN model_upload_sessions s ON s.id = sb.session_id - WHERE s.owner_did = $1 AND s.state = 'open'", + WHERE s.owner_did = $1 AND s.state = 'open' AND s.expires_at > $2", ) .bind(owner_did) + .bind(ts_now()) .fetch_all(&mut **tx) .await?) } @@ -532,11 +562,27 @@ impl Db { .bind(shas) .execute(&mut **tx) .await?; + // The release now carries these blocks, so the sessions stop being + // charged for exactly the bytes that moved. Subtracting the moved + // set (rather than recounting links) preserves bytes admitted but + // not yet recorded by a PUT still in flight. sqlx::query( - "DELETE FROM model_session_blocks sb - USING model_upload_sessions s - WHERE s.id = sb.session_id AND s.owner_did = $1 - AND s.state = 'open' AND sb.block_sha256 = ANY($2)", + "WITH moved AS ( + DELETE FROM model_session_blocks sb + USING model_upload_sessions s + WHERE s.id = sb.session_id AND s.owner_did = $1 + AND s.state = 'open' AND sb.block_sha256 = ANY($2) + RETURNING sb.session_id, sb.block_sha256 + ), per_session AS ( + SELECT m.session_id, COALESCE(SUM(b.size), 0)::bigint AS bytes + FROM moved m + JOIN model_blocks b ON b.sha256 = m.block_sha256 + GROUP BY m.session_id + ) + UPDATE model_upload_sessions s + SET bytes_received = GREATEST(s.bytes_received - ps.bytes, 0) + FROM per_session ps + WHERE ps.session_id = s.id", ) .bind(publisher_did) .bind(shas) @@ -545,29 +591,12 @@ impl Db { Ok(()) } - pub async fn model_tx_recount_open_session_bytes( - &self, - tx: &mut Transaction<'_, Postgres>, - owner_did: &str, - ) -> Result<()> { - sqlx::query( - "UPDATE model_upload_sessions s - SET bytes_received = COALESCE(( - SELECT SUM(b.size) FROM model_session_blocks sb - JOIN model_blocks b ON b.sha256 = sb.block_sha256 - WHERE sb.session_id = s.id), 0) - WHERE s.owner_did = $1 AND s.state = 'open'", - ) - .bind(owner_did) - .execute(&mut **tx) - .await?; - Ok(()) - } - // ── verification ─────────────────────────────────────────────────────── - pub async fn model_mark_published(&self, release_id: i64) -> Result<()> { - sqlx::query( + /// `false` when the release left `verifying` first (the stale-verify + /// sweep rejected it mid-run); the caller then unwinds what it wrote. + pub async fn model_mark_published(&self, release_id: i64) -> Result { + let done = sqlx::query( "UPDATE model_releases SET state = 'published', published_at = $2 WHERE id = $1 AND state = 'verifying'", @@ -575,14 +604,23 @@ impl Db { .bind(release_id) .bind(ts_now()) .execute(&self.pool) - .await?; - Ok(()) + .await? + .rows_affected(); + Ok(done > 0) } /// Reject: mark the release, drop its refs, and refund the publisher the /// bytes no other live release still references. pub async fn model_reject_release(&self, release_id: i64, reason: &str) -> Result<()> { let mut tx = self.pool.begin().await?; + // The refund's "no other live release references this block" test + // and a concurrent claim's "not already claimed" test must agree; + // the claim lock makes them serialize. Same order as claim_release + // (advisory first, then rows), so no deadlock is introduced. + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(crate::models::CLAIM_LOCK_KEY) + .execute(&mut *tx) + .await?; let released: Option<(String,)> = sqlx::query_as( "UPDATE model_releases SET state = 'rejected', failure_reason = $2 @@ -719,6 +757,19 @@ impl Db { tx: &mut Transaction<'_, Postgres>, sha: &str, ) -> Result { + // Lock the block row first. READ COMMITTED snapshots are taken per + // statement, so folding the liveness subqueries into the locking + // SELECT would evaluate them against the pre-lock snapshot and miss + // a link committed while this statement waited. + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM model_blocks WHERE sha256 = $1 FOR UPDATE)", + ) + .bind(sha) + .fetch_one(&mut **tx) + .await?; + if !exists { + return Ok(true); + } Ok(sqlx::query_scalar::<_, bool>( "SELECT NOT EXISTS ( SELECT 1 FROM model_release_blocks rb @@ -728,14 +779,11 @@ impl Db { AND NOT EXISTS ( SELECT 1 FROM model_session_blocks sb JOIN model_upload_sessions s ON s.id = sb.session_id - WHERE sb.block_sha256 = $1 AND s.state = 'open') - FROM model_blocks b - WHERE b.sha256 = $1 FOR UPDATE", + WHERE sb.block_sha256 = $1 AND s.state = 'open')", ) .bind(sha) - .fetch_optional(&mut **tx) - .await? - .unwrap_or(false)) + .fetch_one(&mut **tx) + .await?) } pub async fn model_tx_delete_block_row( @@ -873,6 +921,42 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn session_blocks_ignore_expired_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let sha = "c".repeat(64); + db.model_record_block(&s.id, &sha, 100, 100).await.unwrap(); + + let mut tx = db.model_begin().await.unwrap(); + assert_eq!( + db.model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap(), + vec![sha.clone()] + ); + tx.rollback().await.unwrap(); + + // Past the wall-clock TTL the row still says 'open' until the sweep + // runs, yet the claim-side reachability set must already be empty. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind("2000-01-01T00:00:00+00:00") + .bind(&s.id) + .execute(&pool) + .await + .unwrap(); + let mut tx = db.model_begin().await.unwrap(); + assert!(db + .model_tx_session_blocks(&mut tx, "did:owner") + .await + .unwrap() + .is_empty()); + tx.rollback().await.unwrap(); + } + #[sqlx::test] async fn reserve_quota_caps_first_and_later_claims(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index d2628d33..f3e65607 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -5,7 +5,7 @@ use std::process::Command; /// internal bookkeeping, and `refs/gitlawb/releases/*` pins published model /// releases so gc never prunes them. One shared list keeps the /// repo-config writers in lockstep. -const HIDDEN_REFS: &[(&str, &str)] = &[ +pub(crate) const HIDDEN_REFS: &[(&str, &str)] = &[ ("uploadpack.hideRefs", "refs/gitlawb/requests/"), ("transfer.hideRefs", "refs/gitlawb/requests/"), ("uploadpack.hideRefs", "refs/gitlawb/releases/"), diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 84db6791..bfc3f4b9 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -2,7 +2,7 @@ //! the check-then-act tail (other-verifying probe, quota reservation, release //! insert) runs inside one transaction under the claim advisory lock. -use twigpine_core::model::manifest::Manifest; +use twigpine_core::model::manifest::{Manifest, StorageKind}; use crate::db::model_queries::ClaimPersist; use crate::db::RepoRecord; @@ -93,7 +93,7 @@ pub(crate) async fn read_verified_manifest( .ok_or_else(|| bad_request("commit carries no .twigpine/model-release.sig"))?; let sig_text = String::from_utf8(sig_text).map_err(|_| bad_request("model-release.sig is not utf-8"))?; - let did: twigpine_core::did::Did = owner_did + let did: twigpine_core::did::Did = crate::db::canonical_did(owner_did) .parse() .map_err(|_| bad_request("repo owner DID does not resolve"))?; let manifest = twigpine_core::model::manifest::verify(&manifest_bytes, &sig_text, &did) @@ -120,10 +120,51 @@ pub async fn claim_release( } let (manifest_bytes, manifest) = read_verified_manifest(&state.git_bin, &disk_path, commit, &record.owner_did).await?; + let expected_repo = format!( + "{}/{}", + crate::db::canonical_did(&record.owner_did), + record.name + ); + if manifest.repo != expected_repo { + return Err(bad_request("manifest names a different repository")); + } + if manifest.reconstruction.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return Err(bad_request( + "chunked files declared but the manifest has no reconstruction object", + )); + } let m_sha = twigpine_core::cid::sha256_hex(&manifest_bytes); let rec_sha = manifest.reconstruction.as_ref().map(|r| r.sha256.clone()); let blocks = super::referenced_blocks(state, &manifest).await?; + // Resolve the declared parent before the transaction: the repo lookup + // uses its own pool connection and must not sit behind the global + // advisory lock, where pool pressure would stall every claim. + let parent = match &manifest.parent { + None => None, + Some(parent) => { + let (powner, pname) = parent + .repo + .split_once('/') + .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; + // A parent only confers blocks while its repo is fully public: + // a withdrawn parent cannot launder references. + let (precord, prules) = + crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; + if !precord.is_public || !prules.is_empty() { + return Err(bad_request( + "declared parent's repo is no longer fully public", + )); + } + Some((precord.id, parent.commit.clone())) + } + }; + let mut tx = db.model_begin().await?; db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; @@ -155,7 +196,7 @@ pub async fn claim_release( if let Some(missing) = blocks.iter().find(|b| !present.contains(b.as_str())) { return Err(bad_request(format!( "manifest references block {} which is not stored on this node", - &missing[..16] + missing.get(..16).unwrap_or(missing) ))); } } @@ -172,24 +213,11 @@ pub async fn claim_release( .await? .into_iter() .collect(); - let parent_blocks: std::collections::HashSet = match &manifest.parent { + let parent_blocks: std::collections::HashSet = match &parent { None => std::collections::HashSet::new(), - Some(parent) => { - let (powner, pname) = parent - .repo - .split_once('/') - .ok_or_else(|| bad_request("declared parent repo is not owner/name"))?; - // A parent only confers blocks while its repo is fully public: - // a withdrawn parent cannot launder references. - let (precord, prules) = - crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; - if !precord.is_public || !prules.is_empty() { - return Err(bad_request( - "declared parent's repo is no longer fully public", - )); - } + Some((prepo_id, pcommit)) => { let rows = db - .model_tx_release_blocks_at_commit(&mut tx, &precord.id, &parent.commit) + .model_tx_release_blocks_at_commit(&mut tx, prepo_id, pcommit) .await?; if rows.is_empty() { return Err(bad_request( @@ -207,7 +235,7 @@ pub async fn claim_release( return Err(bad_request(format!( "block {} is not reachable through an open session, a prior \ release, or the declared parent", - &b[..16] + b.get(..16).unwrap_or(b) ))); } } @@ -234,16 +262,6 @@ pub async fn claim_release( ))); } - // Node-wide quota in the same transaction: claimed bytes plus open - // session bytes. - let node_cap = state.config.model_node_quota_bytes as i64; - let node_total = db.model_tx_node_used(&mut tx).await?; - if node_total > node_cap { - return Err(AppError::TooManyRequests(format!( - "node model storage cap ({node_cap} bytes) would be exceeded" - ))); - } - let persist = ClaimPersist { signature: material.signature.clone(), signature_input: material.signature_input.clone(), @@ -266,12 +284,29 @@ pub async fn claim_release( let release_id = row.id; // Claimed blocks leave the caller's open sessions' charge: the - // release now carries them, so session bytes stop double-counting. + // release now carries them. This must precede the node-cap check or + // the just-claimed bytes count twice (once under quota, once under + // the sessions they still appear linked to). db.model_tx_link_release_blocks(&mut tx, release_id, caller, &blocks) .await?; - db.model_tx_recount_open_session_bytes(&mut tx, caller) - .await?; + + // Node-wide quota in the same transaction: claimed bytes plus open + // session bytes. + let node_cap = state.config.model_node_quota_bytes as i64; + let node_total = db.model_tx_node_used(&mut tx).await?; + if node_total > node_cap { + return Err(AppError::TooManyRequests(format!( + "node model storage cap ({node_cap} bytes) would be exceeded" + ))); + } tx.commit().await?; + + // Pin the commit under the hidden release ref now: between claim and + // publish a force-push plus gc could drop the commit the verifier + // needs. Best-effort; the publish path writes it again. + if let Err(e) = super::verify::write_release_ref(&state.git_bin, &disk_path, commit).await { + tracing::warn!(%commit, "release ref write at claim failed: {e}"); + } Ok(row) } diff --git a/crates/twigpine-node/src/models/mod.rs b/crates/twigpine-node/src/models/mod.rs index dfee0f64..f4e3e036 100644 --- a/crates/twigpine-node/src/models/mod.rs +++ b/crates/twigpine-node/src/models/mod.rs @@ -38,7 +38,10 @@ pub async fn read_range( use futures::StreamExt; let id = crate::blockstore::BlockId::parse(sha) .map_err(|e| crate::blockstore::BlockStoreError::Backend(e.to_string()))?; - let mut stream = store.get_range(&id, start, start + len).await?; + let end = start + .checked_add(len) + .ok_or(crate::blockstore::BlockStoreError::OutOfRange)?; + let mut stream = store.get_range(&id, start, end).await?; let mut out = Vec::with_capacity(len.min(1 << 22) as usize); while let Some(chunk) = stream.next().await { out.extend_from_slice(&chunk?); diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index 00202bfa..ca16a9a4 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -8,6 +8,10 @@ use crate::error::AppError; use crate::state::AppState; +/// A release still `verifying` this many seconds after claim is treated as +/// wedged: the worker died mid-verify or hit a persistent internal error. +const STALE_VERIFY_SECS: i64 = 6 * 3600; + #[derive(Debug, Default)] pub struct SweepStats { pub sessions_expired: u64, @@ -26,6 +30,13 @@ pub async fn sweep_once(state: &AppState) -> Result { stats.sessions_expired = expired.len() as u64; db.model_drop_sessions_blocks(&expired).await?; + // A `verifying` row that outlived its window wedges the publisher's + // one-verifying slot; reject it (which also frees the reservation). + for id in db.model_stale_verifying(STALE_VERIFY_SECS).await? { + db.model_reject_release(id, "verification timed out") + .await?; + } + // Re-mark liveness both ways: blocks that lost every live reference get // an unreferenced_since stamp; blocks that regained one clear theirs. stats.blocks_marked = db.model_remark_liveness().await?; diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index ae35c3bb..096896f9 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -73,38 +73,90 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App return reject_release(state, release_id, "manifest digest changed since claim").await; } - let Some(rec_ref) = &manifest.reconstruction else { - return reject_release(state, release_id, "manifest has no reconstruction object").await; - }; - let store = state - .block_store - .clone() - .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; - let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { - Ok(b) => b, - Err(e) => { - return reject_release( - state, - release_id, - &format!("reconstruction object unreadable: {e}"), - ) - .await; + let rec = match &manifest.reconstruction { + Some(rec_ref) => { + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; + let rec_bytes = match super::read_block(&store, &rec_ref.sha256, rec_ref.size).await { + Ok(b) => b, + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object unreadable: {e}"), + ) + .await; + } + }; + match Reconstruction::parse(&rec_bytes) { + Ok(r) => Some(r), + Err(e) => { + return reject_release( + state, + release_id, + &format!("reconstruction object invalid: {e}"), + ) + .await; + } + } } + None => None, }; - let rec = match Reconstruction::parse(&rec_bytes) { - Ok(r) => r, - Err(e) => { + // An all-Git release legitimately carries no reconstruction object; a + // manifest naming chunked files without one is self-contradictory. + if rec.is_none() + && manifest + .files + .iter() + .any(|f| matches!(f.storage, StorageKind::Chunked)) + { + return reject_release( + state, + release_id, + "chunked files declared but the manifest has no reconstruction object", + ) + .await; + } + + // Commit ⊆ manifest: a committed file the manifest does not name as + // git-stored slipped past the publish scan; refuse it rather than + // release bytes the manifest never described. + let tree = crate::git::store::run_git_bounded( + &state.git_bin, + &disk_path, + &["ls-tree", "-r", "--name-only", &release.commit_sha], + b"", + std::time::Duration::from_secs(30), + "git ls-tree", + ) + .await + .map_err(AppError::Internal)?; + let manifest_git_paths: std::collections::HashSet<&str> = manifest + .files + .iter() + .filter(|f| f.storage == StorageKind::Git) + .map(|f| f.path.as_str()) + .collect(); + for path in String::from_utf8_lossy(&tree.stdout) + .lines() + .filter(|p| !p.starts_with(".twigpine/")) + { + if !manifest_git_paths.contains(path) { return reject_release( state, release_id, - &format!("reconstruction object invalid: {e}"), + &format!("{path} is committed but not in the manifest"), ) .await; } - }; + } - let rec_by_path: std::collections::HashMap<&str, _> = - rec.files.iter().map(|f| (f.path.as_str(), f)).collect(); + let rec_by_path: std::collections::HashMap<&str, _> = rec + .as_ref() + .map(|r| r.files.iter().map(|f| (f.path.as_str(), f)).collect()) + .unwrap_or_default(); for file in &manifest.files { match file.storage { StorageKind::Chunked => { @@ -128,8 +180,9 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // would force block_on, which has no reactor under the S3 // backend. Blocks were hash-verified at write, so the // whole-file digest is the check that matters here. + let rec = rec.as_ref().expect("entry implies rec"); let slices = match twigpine_core::model::reconstruction::map_file_range( - entry, &rec, 0, file.size, + entry, rec, 0, file.size, ) { Ok(s) => s, Err(e) => { @@ -147,19 +200,25 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App }; // Ordered prefetch: `buffered` preserves order while // overlapping the store's per-slice round trips. + let store = state + .block_store + .clone() + .ok_or_else(|| AppError::Internal(anyhow::anyhow!("block store gone")))?; let jobs = slices .iter() .map(|s| (s.block.clone(), s.offset, s.len)) .collect::>(); - let fetched = + // Ordered prefetch: `buffered` preserves order while + // overlapping the store's per-slice round trips. Consume + // as slices land: collecting first would hold the whole + // rebuilt file in memory. + let mut fetched = futures::stream::iter(jobs.into_iter().map(|(block, offset, len)| { let store = store.clone(); async move { super::read_range(&store, &block, offset, len).await } })) - .buffered(4) - .collect::>() - .await; - for bytes in fetched { + .buffered(4); + while let Some(bytes) = fetched.next().await { let bytes = match bytes { Ok(b) => b, Err(e) => { @@ -246,17 +305,74 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // Publish: hidden ref first, then the state flip, so a crash leaves a // verifying row the worker retries rather than a dangling ref. write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; - state.db.model_mark_published(release_id).await?; + if !state.db.model_mark_published(release_id).await? { + // The stale-verify sweep rejected the row while this pass ran: + // drop the ref just written so it does not advertise a rejected + // commit. + let ref_name = format!("refs/gitlawb/releases/{}", release.commit_sha); + let _ = crate::git::store::run_git_bounded( + &state.git_bin, + &disk_path, + &["update-ref", "-d", &ref_name], + b"", + std::time::Duration::from_secs(30), + "git update-ref", + ) + .await; + } Ok(()) } /// `refs/gitlawb/releases/` -> the release commit itself: reachable, /// so `gc` never prunes it, and hidden under the gitlawb ref namespace. +/// Idempotently add the release-ref hideRefs config: repos created before +/// the namespace existed only get it via the push-path prereq, which is +/// warn-and-proceed, so a failed write there would leave release commits +/// advertised to every clone. +async fn ensure_release_refs_hidden( + git_bin: &str, + disk_path: &std::path::Path, +) -> Result<(), AppError> { + for &(key, value) in crate::git::store::HIDDEN_REFS + .iter() + .filter(|(_, v)| v.contains("releases/")) + { + let have = crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--get-all", key], + b"", + std::time::Duration::from_secs(30), + "git config --get-all", + ) + .await + .map_err(AppError::Internal)?; + if String::from_utf8_lossy(&have.stdout) + .lines() + .any(|l| l.trim() == value) + { + continue; + } + crate::git::store::run_git_bounded( + git_bin, + disk_path, + &["config", "--add", key, value], + b"", + std::time::Duration::from_secs(30), + "git config --add", + ) + .await + .map_err(AppError::Internal)?; + } + Ok(()) +} + pub async fn write_release_ref( git_bin: &str, disk_path: &std::path::Path, commit: &str, ) -> Result<(), AppError> { + ensure_release_refs_hidden(git_bin, disk_path).await?; let out = crate::git::store::run_git_bounded( git_bin, disk_path, From 9207ee2838cda6bc954b10c25caa53eb10b9049c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:29:40 -0600 Subject: [PATCH 24/53] chore(cli): annotate model publish's local git spawns The CLI is a short-lived process driving git synchronously; the unbounded-child guidance targets request handlers holding a concurrency permit, which does not apply here. --- crates/twigpine-cli/src/model.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 9805a892..dd2c2ff1 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -87,6 +87,8 @@ pub async fn run(cmd: ModelCmd) -> Result<()> { // ── git helpers ───────────────────────────────────────────────────────────── fn git(root: &Path, args: &[&str]) -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(args) .current_dir(root) @@ -141,6 +143,8 @@ fn release_commits(root: &Path) -> Vec { } fn repo_root() -> Result { + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["rev-parse", "--show-toplevel"]) .output() @@ -564,6 +568,8 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { let branch = match &args.branch { Some(b) => b.clone(), None => { + // allow-unbounded-git: short-lived CLI process; there is no + // request permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["symbolic-ref", "--short", "-q", "HEAD"]) .current_dir(&root) @@ -916,6 +922,8 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { .next() .context("no HEAD commit")?; + // allow-unbounded-git: short-lived CLI process; there is no request + // permit to hold or client disconnect to outlive. let push = std::process::Command::new("git") .args(["push", &remote_name, &format!("HEAD:{branch}")]) .current_dir(&root) From 236728ec1554b366628342f24e5d504c9680579e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:36:32 -0600 Subject: [PATCH 25/53] fix(node): refuse mirror rows for model publishing A mirror row's publicity pair is vacuous (is_public is hardcoded true, rules never sync), so a mirror without a canonical twin would pass the fully-public gate end to end. Fail closed on slash-form ids at session open, claim, parent resolution, and the verify recheck, with a mirror-without-twin test. --- crates/twigpine-node/src/api/models.rs | 6 ++- crates/twigpine-node/src/models/claim.rs | 4 +- crates/twigpine-node/src/models/verify.rs | 4 +- crates/twigpine-node/tests/models_api.rs | 57 +++++++++++++++++++++++ 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index d62770a6..ce7cdcbd 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -40,7 +40,11 @@ fn hosting_enabled(state: &AppState) -> Result<()> { /// a public one carrying any path-scoped visibility rule, refuses with a /// clear 4xx rather than partially publishing. fn require_fully_public(record: &RepoRecord, rules: &[VisibilityRule]) -> Result<()> { - if !record.is_public || !rules.is_empty() { + // A mirror row (slash-form id) carries a vacuous publicity pair: its + // is_public is hardcoded true and rules never sync, so passing this + // check on one means nothing. Mirrors are replication-managed, not + // publishable; refuse them the same way as a gated canonical repo. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return Err(AppError::BadRequest( "model hosting requires a fully public repository".into(), )); diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index bfc3f4b9..1d06e483 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -156,7 +156,9 @@ pub async fn claim_release( // a withdrawn parent cannot launder references. let (precord, prules) = crate::api::authorize_repo_read(state, powner, pname, Some(caller), "/").await?; - if !precord.is_public || !prules.is_empty() { + // A mirror parent row fails closed the same way: its publicity + // pair is vacuous. + if !precord.is_public || !prules.is_empty() || precord.id.contains('/') { return Err(bad_request( "declared parent's repo is no longer fully public", )); diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 096896f9..6296732f 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -50,7 +50,9 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .await? .ok_or_else(|| AppError::NotFound("repo gone".into()))?; let rules = state.db.list_visibility_rules(&record.id).await?; - if !record.is_public || !rules.is_empty() { + // A mirror row (slash-form id) has a vacuous publicity pair, so it can + // never prove full publicity here either. + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return reject_release(state, release_id, "repository is no longer fully public").await; } diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index 0d3116a4..ea89c43e 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -145,6 +145,63 @@ async fn open_session_owner_created(pool: sqlx::PgPool) { node.shutdown().await; } +/// A mirror row with no canonical twin carries a vacuous publicity pair: +/// `is_public` is hardcoded true and rules never sync, so neither check may +/// admit it for publishing. Slash-form ids mark mirror rows (issue #244). +#[sqlx::test] +async fn mirror_repo_without_twin_cannot_publish(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let owner = Keypair::generate(); + let owner_did = owner.did().to_string(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos + (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1,'model',$2,'mirrored from peer',true,'main',$3,$3,'/tmp/mirror-model')", + ) + .bind(format!("{owner_did}/model")) + .bind(&owner_did) + .bind(&now) + .execute(&pool) + .await + .expect("mirror row seeds"); + + let resp = signed_request( + &client, + reqwest::Method::POST, + &node.base_url, + &sessions_path(&owner_did, "model"), + b"{}".to_vec(), + &owner, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + let body = serde_json::to_vec(&json!({"commit": "0".repeat(40), "branch": "main"})).unwrap(); + let signed = sign_request(&owner, "POST", &claims_path(&owner_did, "model"), &body); + let resp = client + .post(format!( + "{}{}", + node.base_url, + claims_path(&owner_did, "model") + )) + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature) + .header("content-type", "application/json") + .body(body) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 400); + + node.shutdown().await; +} + /// A signed caller who is not the repo owner gets the owner gate's 403. #[sqlx::test] async fn open_session_non_owner_forbidden(pool: sqlx::PgPool) { From 27e971ca8372a78bf496c22e8505121b51a8b4c4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:46:53 -0600 Subject: [PATCH 26/53] fix(node): fail closed on mirror rows at every model publicity check Extend the mirror guard to block PUTs and reconstruction reads, and mark the verify recheck for the push gate's mirror-pair scan. --- crates/twigpine-node/src/api/models.rs | 10 +++++++++- crates/twigpine-node/src/models/verify.rs | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index ce7cdcbd..480d81a2 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -134,6 +134,10 @@ pub async fn put_model_block( // indistinguishable from a missing session. The owner always reads their // own repo, so the fully-public check is what stops bytes landing on a // repo that turned private or gained visibility rules mid-upload. + // mirror-rows-handled: sessions can only bind canonical repos (open + // refuses slash ids); the id check below already makes a mirror row a + // mismatch, and the explicit slash guard keeps the publicity pair from + // being trusted on one. let (record, rules) = authorize_repo_read(&state, &owner, &name, Some(&session.owner_did), "/").await?; if session.repo_id != record.id @@ -141,6 +145,7 @@ pub async fn put_model_block( || session.expires_at <= models::ts_now() || !record.is_public || !rules.is_empty() + || record.id.contains('/') { return Err(AppError::NotFound("model upload session not found".into())); } @@ -353,9 +358,12 @@ pub async fn get_model_reconstruction( ) -> Result { hosting_enabled(&state)?; let caller = auth.map(|Extension(AuthenticatedDid(d))| d); + // mirror-rows-handled: a mirror row (slash-form id) can never carry a + // claimed release, and its publicity pair is vacuous, so it takes the + // same 404 as a private repo. let (record, rules) = authorize_repo_read(&state, &owner, &name, caller.as_deref(), "/").await?; - if !record.is_public || !rules.is_empty() { + if !record.is_public || !rules.is_empty() || record.id.contains('/') { return Err(AppError::NotFound("model release not found".into())); } let release = state diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 6296732f..df4300c5 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -49,6 +49,8 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .get_repo_by_id(&release.repo_id) .await? .ok_or_else(|| AppError::NotFound("repo gone".into()))?; + // mirror-rows-handled: a slash-form id fails closed in the condition + // below; the vacuous pair never admits a mirror for publishing. let rules = state.db.list_visibility_rules(&record.id).await?; // A mirror row (slash-form id) has a vacuous publicity pair, so it can // never prove full publicity here either. From 7a792f03610a1315098958b991c1935201c4b610 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:49:50 -0600 Subject: [PATCH 27/53] fix(node): stream model packing, make the block store durable, tighten S3 ambiguity Allowlist fastcdc for the twigpine-core purity gate. Add pack_file_with so each sealed block goes to a sink and drop per-chunk buffers after sealing. Detect safetensors before the pickle prefix test. Require the unclaimed TTL to exceed the session TTL. Refuse empty blocks in both backends to match model_blocks.size > 0. Persist the fs ancestor chain on every store and on AlreadyPresent. Report a retried complete's NoSuchUpload and 409 as Unknown, and split oversized stream items across bounded S3 parts. --- ci/twigpine-core-allowed-deps.txt | 1 + crates/twigpine-core/src/model/chunking.rs | 22 +- crates/twigpine-core/src/model/manifest.rs | 32 ++- .../twigpine-core/src/model/reconstruction.rs | 137 +++++++++--- crates/twigpine-node/src/blockstore/fs.rs | 200 ++++++++++++++++-- crates/twigpine-node/src/blockstore/mod.rs | 23 +- crates/twigpine-node/src/blockstore/s3.rs | 147 ++++++++++--- crates/twigpine-node/src/config.rs | 34 +++ docs/RUN-A-NODE.md | 2 +- 9 files changed, 516 insertions(+), 82 deletions(-) diff --git a/ci/twigpine-core-allowed-deps.txt b/ci/twigpine-core-allowed-deps.txt index 2875f6dc..dc0c199f 100644 --- a/ci/twigpine-core-allowed-deps.txt +++ b/ci/twigpine-core-allowed-deps.txt @@ -56,6 +56,7 @@ digest ed25519 ed25519-dalek equivalent +fastcdc generic-array getrandom hashbrown diff --git a/crates/twigpine-core/src/model/chunking.rs b/crates/twigpine-core/src/model/chunking.rs index 190c1e58..95aa5395 100644 --- a/crates/twigpine-core/src/model/chunking.rs +++ b/crates/twigpine-core/src/model/chunking.rs @@ -117,23 +117,33 @@ mod tests { #[test] fn chunk_data_never_buffers_the_file() { // The contract this format depends on: a reader is consumed a chunk - // at a time. Guard it by chunking a reader that would panic if read - // past its claimed end before the iterator asks for more. - struct Stingy { + // at a time. Count what the first chunk cost out of a large input. + use std::cell::Cell; + use std::rc::Rc; + struct Counting { left: usize, + read: Rc>, } - impl Read for Stingy { + impl Read for Counting { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let n = buf.len().min(self.left); self.left -= n; buf[..n].fill(1); + self.read.set(self.read.get() + n); Ok(n) } } - let mut it = chunk_reader(Stingy { - left: 3 * CHUNK_MAX, + let read = Rc::new(Cell::new(0)); + let mut it = chunk_reader(Counting { + left: 64 * 1024 * 1024, + read: read.clone(), }); let first = it.next().unwrap().unwrap(); assert!(first.len <= CHUNK_MAX); + assert!( + read.get() <= 2 * CHUNK_MAX, + "read {} bytes for one chunk", + read.get() + ); } } diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index 90cac811..de40e391 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -183,6 +183,15 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { if first_bytes.starts_with(b"GGUF") { return FileFormat::Gguf; } + // safetensors: an 8-byte little-endian header length followed by '{'. + // Checked before raw pickle: a header length such as 0x0380 starts with + // the bytes 0x80 0x03, which the pickle test below would claim. + if first_bytes.len() >= 9 + && u64::from_le_bytes(first_bytes[..8].try_into().unwrap()) > 0 + && first_bytes[8] == b'{' + { + return FileFormat::Safetensors; + } // Raw pickle: the protocol opcode 0x80 followed by the version byte. if first_bytes.len() >= 2 && first_bytes[0] == 0x80 && (2..=5).contains(&first_bytes[1]) { return FileFormat::Pickle; @@ -193,13 +202,6 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { if first_bytes.starts_with(b"PK\x03\x04") && matches!(ext, "bin" | "pt" | "pth" | "ckpt") { return FileFormat::Pickle; } - // safetensors: an 8-byte little-endian header length followed by '{'. - if first_bytes.len() >= 9 - && u64::from_le_bytes(first_bytes[..8].try_into().unwrap()) > 0 - && first_bytes[8] == b'{' - { - return FileFormat::Safetensors; - } if matches!( ext, // `tokenizer.model` is deliberately absent: it is a sentencepiece @@ -327,6 +329,22 @@ mod tests { let mut st = 5u64.to_le_bytes().to_vec(); st.extend_from_slice(b"{\"a\":0}"); assert_eq!(detect_format(&st, "m.safetensors"), FileFormat::Safetensors); + // A header length whose low bytes read as a pickle prefix (0x0480 + // and 0x0380 start 0x80 0x04 / 0x80 0x03) is still safetensors. + for len in [0x0480u64, 0x0380, 0x0280, 0x0580] { + let mut overlap = len.to_le_bytes().to_vec(); + overlap.extend_from_slice(b"{\"a\":0}"); + assert_eq!( + detect_format(&overlap, "m.safetensors"), + FileFormat::Safetensors, + "header length {len:#x}" + ); + } + // A real pickle whose byte 8 is not '{' stays pickle. + assert_eq!( + detect_format(b"\x80\x04\x95\x00\x00\x00\x00\x00\x00", "x.bin"), + FileFormat::Pickle + ); assert_eq!(detect_format(b"GGUF\x01rest", "m.gguf"), FileFormat::Gguf); assert_eq!(detect_format(b"\x80\x04x", "torch.bin"), FileFormat::Pickle); assert_eq!( diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 70d2a33e..35386162 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -197,19 +197,22 @@ impl DedupIndex { /// Seal the accumulating block of new chunks: patch its id into the terms /// written while it was still open, then append the block-table entry and /// queue the bytes for upload. -fn seal_pending( +fn seal_pending std::io::Result<()>>( pending: &mut Vec, terms: &mut [Term], block_entries: &mut Vec, - new_blocks: &mut Vec, -) { + on_block: &mut F, +) -> std::io::Result<()> { if pending.is_empty() { - return; + return Ok(()); } - let chunks = std::mem::take(pending); + let mut chunks = std::mem::take(pending); let mut data = Vec::with_capacity(chunks.iter().map(|c| c.len).sum::()); - for c in &chunks { + for c in &mut chunks { data.extend_from_slice(&c.data); + // The bytes now live in `data`; keeping the chunk's copy would hold + // every sealed block twice. Chunk metadata (sha256, len) stays. + c.data = Vec::new(); } let block = Block { sha256: sha256_hex(&data), @@ -235,7 +238,7 @@ fn seal_pending( }) .collect(), }); - new_blocks.push(block); + on_block(block) } /// What `pack_file` produced: the file's entry, the new blocks to store and @@ -248,16 +251,38 @@ pub struct PackedFile { /// Chunk and pack one file, reusing terms for chunks a prior reconstruction /// already holds (`dedup`). `path` is the repo-relative path recorded in the -/// entry. +/// entry. Every sealed block is held in the result; publishers of large +/// files should prefer `pack_file_with`, which keeps memory bounded by a +/// block instead of the file. pub fn pack_file( path: &str, reader: R, dedup: &DedupIndex, ) -> std::io::Result { + let mut new_blocks: Vec = Vec::new(); + let (file, block_entries) = pack_file_with(path, reader, dedup, |b| { + new_blocks.push(b); + Ok(()) + })?; + Ok(PackedFile { + file, + new_blocks, + block_entries, + }) +} + +/// `pack_file` with each sealed block handed to `on_block` as it finishes: +/// the caller can upload and drop it while the file is still packing, so a +/// file of any size packs in block-sized memory. +pub fn pack_file_with std::io::Result<()>>( + path: &str, + reader: R, + dedup: &DedupIndex, + mut on_block: F, +) -> std::io::Result<(FileEntry, Vec)> { let mut file_hasher = sha2::Sha256::new(); let mut terms: Vec = Vec::new(); - let mut new_blocks: Vec = Vec::new(); let mut block_entries: Vec = Vec::new(); // Chunks not found in `dedup` accumulate into one pending block that // seals only at the target size or EOF. Sealing on every reused-chunk @@ -306,22 +331,12 @@ pub fn pack_file( }), } if pending_bytes >= BLOCK_TARGET { - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; pending_bytes = 0; } } } - seal_pending( - &mut pending, - &mut terms, - &mut block_entries, - &mut new_blocks, - ); + seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; let file = FileEntry { path: path.to_string(), @@ -329,11 +344,7 @@ pub fn pack_file( sha256: hex::encode(file_hasher.finalize()), terms, }; - Ok(PackedFile { - file, - new_blocks, - block_entries, - }) + Ok((file, block_entries)) } /// Byte-range mapping: which slices of which blocks serve file bytes @@ -511,6 +522,80 @@ mod tests { (rec, packed) } + /// Deterministic non-repeating bytes that count what was consumed, so a + /// test can see how much of the input had been read when a block sealed. + struct CountingGen { + left: usize, + state: u64, + read: std::rc::Rc>, + } + + impl Read for CountingGen { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = buf.len().min(self.left); + for b in &mut buf[..n] { + self.state = self + .state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + *b = (self.state >> 56) as u8; + } + self.left -= n; + self.read.set(self.read.get() + n); + Ok(n) + } + } + + #[test] + fn pack_file_with_hands_over_each_block_while_reading() { + let total = BLOCK_TARGET + 8 * 1024 * 1024; + let read = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let reader = CountingGen { + left: total, + state: 1, + read: read.clone(), + }; + let mut read_at_block: Vec = Vec::new(); + let mut cleared = true; + let (file, entries) = pack_file_with("w.bin", reader, &DedupIndex::new(), |b| { + read_at_block.push(read.get()); + cleared &= b.chunks.iter().all(|c| c.data.is_empty() && c.len > 0); + assert_eq!(b.data.len(), b.chunks.iter().map(|c| c.len).sum::()); + Ok(()) + }) + .unwrap(); + assert_eq!(file.size, total as u64); + assert!(read_at_block.len() >= 2, "expected two sealed blocks"); + // The first block reached the sink long before the input ended: the + // packer held about one block, not the file. + assert!( + read_at_block[0] <= BLOCK_TARGET + 4 * crate::model::chunking::CHUNK_MAX, + "first block sealed after {} bytes read", + read_at_block[0] + ); + assert!(read_at_block[0] < total); + assert!(cleared, "a sealed block still carries per-chunk buffers"); + assert_eq!(entries.len(), read_at_block.len()); + } + + #[test] + fn pack_file_with_propagates_a_sink_error() { + let read = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let reader = CountingGen { + left: BLOCK_TARGET + 1024 * 1024, + state: 2, + read: read.clone(), + }; + let err = pack_file_with("w.bin", reader, &DedupIndex::new(), |_| { + Err(std::io::Error::other("sink full")) + }) + .map(|_| ()) + .unwrap_err(); + assert_eq!(err.to_string(), "sink full"); + // The error stopped the read; the rest of the input was not consumed. + assert!(read.get() < BLOCK_TARGET + 1024 * 1024); + } + #[test] fn pack_then_rebuild_is_byte_identical() { let bytes = gen_bytes(3 * 1024 * 1024 + 13, 7); diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 61da56b1..96ab0389 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -25,10 +25,44 @@ pub struct FsBlockStore { impl FsBlockStore { pub fn new(root: PathBuf) -> io::Result { - std::fs::create_dir_all(root.join("tmp"))?; + 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)?; + } + } Ok(Self { root }) } + /// Fsync `dir` and every directory above it up to the store root, so the + /// whole `//` name chain is durable. Used wherever success + /// is reported for a name this call did not itself just publish: a + /// concurrent writer may have linked it and not yet synced. + async fn sync_chain(&self, dir: &Path) -> io::Result<()> { + fsync_dir(dir).await?; + self.sync_ancestors(dir).await + } + + /// The directories above a leaf directory, up to and including the root. + async fn sync_ancestors(&self, dir: &Path) -> io::Result<()> { + fsync_dir(dir.parent().unwrap_or(&self.root)).await?; + fsync_dir(&self.root).await + } + fn content_path(&self, id: &BlockId) -> PathBuf { let s = id.as_str(); self.root.join(&s[..2]).join(&s[2..4]).join(s) @@ -49,9 +83,28 @@ impl FsBlockStore { /// `Stored`, a link that only exists in the page cache is a lost write. #[cfg(unix)] async fn fsync_dir(dir: &Path) -> io::Result<()> { + #[cfg(test)] + SYNCED.lock().unwrap().push(dir.to_path_buf()); tokio::fs::File::open(dir).await?.sync_all().await } +#[cfg(unix)] +fn fsync_dir_blocking(dir: &Path) -> io::Result<()> { + #[cfg(test)] + SYNCED.lock().unwrap().push(dir.to_path_buf()); + std::fs::File::open(dir)?.sync_all() +} + +#[cfg(not(unix))] +fn fsync_dir_blocking(_: &Path) -> io::Result<()> { + Ok(()) +} + +/// Every directory fsynced in this test process, so a test can assert which +/// names a code path made durable. +#[cfg(test)] +static SYNCED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + /// Directory fsync is a unix durability primitive; elsewhere the link is /// the best guarantee available. #[cfg(not(unix))] @@ -68,7 +121,11 @@ impl BlockStore for FsBlockStore { max_len: u64, ) -> Result { let dest = self.content_path(id); + let dir = dest.parent().expect("content path has two levels"); if dest.exists() { + // The name may belong to a writer that linked it and has not + // fsynced yet: persist the chain before reporting it present. + self.sync_chain(dir).await?; return Ok(PutOutcome::AlreadyPresent); } @@ -103,6 +160,11 @@ impl BlockStore for FsBlockStore { Self::cleanup(&tmp).await; return Err(BlockStoreError::DigestMismatch); } + if len == 0 { + drop(file); + 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. if let Err(e) = file.sync_all().await { @@ -112,21 +174,17 @@ impl BlockStore for FsBlockStore { } drop(file); - let dir = dest.parent().expect("content path has two levels"); - let fresh_dirs = !dir.exists(); if let Err(e) = tokio::fs::create_dir_all(dir).await { Self::cleanup(&tmp).await; return Err(e.into()); } - if fresh_dirs { - // The new / levels are themselves names in a parent - // directory; persist each level's entry. - for ancestor in [dir.parent().unwrap_or(&self.root), self.root.as_path()] { - if let Err(e) = fsync_dir(ancestor).await { - Self::cleanup(&tmp).await; - return Err(e.into()); - } - } + // The / levels are names in their parents. Persist them on + // every store, not only when this call created them: a concurrent + // writer may have created them and not yet synced, and the + // directory merely existing says nothing about being durable. + if let Err(e) = self.sync_ancestors(dir).await { + Self::cleanup(&tmp).await; + return Err(e.into()); } // A hard link refuses to replace an existing object, which is what // makes a same-content race benign rather than a torn write. @@ -141,6 +199,8 @@ impl BlockStore for FsBlockStore { } Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { Self::cleanup(&tmp).await; + // The winner's link may precede its own directory sync. + self.sync_chain(dir).await?; Ok(PutOutcome::AlreadyPresent) } Err(e) => { @@ -310,6 +370,122 @@ mod tests { crate::blockstore::parity::get_range_edge_contract(&s).await; } + #[tokio::test] + async fn empty_body_is_refused_and_leaves_nothing() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + crate::blockstore::parity::empty_body_contract(&s).await; + assert_eq!( + std::fs::read_dir(dir.path().join("blocks/tmp")) + .unwrap() + .count(), + 0 + ); + } + + /// Directories whose entry was fsynced under `root`, in call order. + fn synced_under(root: &Path) -> Vec { + SYNCED + .lock() + .unwrap() + .iter() + .filter(|p| p.starts_with(root)) + .cloned() + .collect() + } + + fn forget_synced(root: &Path) { + SYNCED.lock().unwrap().retain(|p| !p.starts_with(root)); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_new_root_persists_every_created_ancestor() { + let dir = tempfile::tempdir().unwrap(); + let top = dir.path().join("a"); + let root = top.join("b").join("blocks"); + FsBlockStore::new(root.clone()).unwrap(); + let synced = synced_under(dir.path()); + // Each directory created on the way down, and the pre-existing + // directory that now holds the first of them, has been fsynced. + for expected in [ + dir.path(), + top.as_path(), + top.join("b").as_path(), + root.as_path(), + ] { + assert!( + synced.iter().any(|p| p == expected), + "{expected:?} not fsynced; got {synced:?}" + ); + } + } + + /// A destination that already exists may have been linked by a writer + /// that has not fsynced yet, so reporting it present must persist the + /// whole publication chain itself. + #[cfg(unix)] + #[tokio::test] + async fn already_present_persists_the_publication_chain() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let body = b"duplicate".to_vec(); + let id = id_of(&body); + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(); + let leaf = s.content_path(&id).parent().unwrap().to_path_buf(); + forget_synced(dir.path()); + assert_eq!( + s.put_verified(&id, stream(body), u64::MAX).await.unwrap(), + PutOutcome::AlreadyPresent + ); + let synced = synced_under(dir.path()); + for expected in [leaf.as_path(), leaf.parent().unwrap(), s.root.as_path()] { + assert!( + synced.iter().any(|p| p == expected), + "{expected:?} not fsynced on AlreadyPresent; got {synced:?}" + ); + } + } + + /// A second block landing in a directory that already exists still + /// persists that directory's ancestors: existence is not durability. + #[cfg(unix)] + #[tokio::test] + async fn every_store_persists_the_ancestor_chain() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let first = b"first".to_vec(); + s.put_verified(&id_of(&first), stream(first.clone()), u64::MAX) + .await + .unwrap(); + // Same aa/bb directory, different object: find a body whose id + // shares the first four hex characters. + let target = id_of(&first); + let prefix = &target.as_str()[..4]; + let mut n = 0u64; + let sibling = loop { + let candidate = n.to_le_bytes().to_vec(); + if id_of(&candidate).as_str().starts_with(prefix) && candidate != first { + break candidate; + } + n += 1; + }; + forget_synced(dir.path()); + s.put_verified(&id_of(&sibling), stream(sibling.clone()), u64::MAX) + .await + .unwrap(); + let leaf = s.content_path(&target).parent().unwrap().to_path_buf(); + let synced = synced_under(dir.path()); + for expected in [leaf.as_path(), leaf.parent().unwrap(), s.root.as_path()] { + assert!( + synced.iter().any(|p| p == expected), + "{expected:?} not fsynced for a store into an existing dir; got {synced:?}" + ); + } + } + #[tokio::test] async fn concurrent_puts_leave_one_object() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/blockstore/mod.rs b/crates/twigpine-node/src/blockstore/mod.rs index 4a89325d..d44210d9 100644 --- a/crates/twigpine-node/src/blockstore/mod.rs +++ b/crates/twigpine-node/src/blockstore/mod.rs @@ -82,6 +82,12 @@ pub enum BlockStoreError { /// stored. #[error("body exceeds the {0}-byte limit")] TooLarge(u64), + /// The body was empty. Model blocks are never empty (`model_blocks.size` + /// is checked `> 0` and the packer never seals an empty block), so both + /// backends refuse the empty id instead of storing a zero-byte object the + /// database could not record. Nothing was stored. + #[error("an empty body is not a valid block")] + EmptyBlock, /// The requested byte range is outside the stored object. #[error("requested range is outside the object")] OutOfRange, @@ -106,7 +112,12 @@ pub trait BlockStore: Send + Sync { /// Stream `body` into the store under `id`, hashing as it goes. The body /// is never fully buffered. Fails with `TooLarge` the moment the body /// exceeds `max_len`, with `DigestMismatch` when the bytes do not hash to - /// `id`, and leaves no object or temporary state behind on any failure. + /// `id`, and with `EmptyBlock` for a zero-length body. After any of those + /// definite failures no object is stored and staged data is cleaned up on + /// a best-effort basis: a remote backend whose abort call fails leaves + /// orphaned staging state behind. `Unknown` is the exception to the + /// no-object guarantee: the write may have committed, so callers + /// reconcile with `size()` before retrying. async fn put_verified( &self, id: &BlockId, @@ -162,6 +173,16 @@ pub(crate) mod parity { use futures::StreamExt; use sha2::{Digest, Sha256}; + /// A zero-length body is refused identically by every backend and leaves + /// no object under the empty-body id. + pub(crate) async fn empty_body_contract(store: &dyn BlockStore) { + let id = BlockId::parse(&hex::encode(Sha256::digest(b""))).unwrap(); + let body = futures::stream::iter(Vec::>::new()).boxed(); + let err = store.put_verified(&id, body, u64::MAX).await.unwrap_err(); + assert!(matches!(err, BlockStoreError::EmptyBlock), "got {err:?}"); + assert_eq!(store.size(&id).await.unwrap(), None); + } + pub(crate) async fn get_range_edge_contract(store: &dyn BlockStore) { let body: Vec = (0..10_000u32).map(|i| (i % 251) as u8).collect(); let id = BlockId::parse(&hex::encode(Sha256::digest(&body))).unwrap(); diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index afafdbc2..1eb11788 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -16,7 +16,7 @@ use std::io; use async_trait::async_trait; -use aws_sdk_s3::error::SdkError; +use aws_sdk_s3::error::{ProvideErrorMetadata, SdkError}; use aws_sdk_s3::primitives::ByteStream; use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart}; use aws_sdk_s3::Client as S3Client; @@ -35,6 +35,22 @@ const PART_SIZE: usize = 16 * 1024 * 1024; const KEY_PREFIX: &str = "model-blocks/v1"; +/// Does a non-success `CompleteMultipartUpload` answer prove the object was +/// not committed? A 4xx refusal does, except two answers a retried complete +/// produces after an earlier attempt committed with its response lost: 404 +/// `NoSuchUpload` (the upload id is consumed by the commit) and 409 +/// (`OperationAborted`, a conflicting operation in flight). Those are +/// ambiguous, so the caller reconciles with `size()`. Every non-4xx status +/// is ambiguous too. +fn complete_refusal_is_definite(status: u16, code: Option<&str>) -> bool { + match status { + 404 if code == Some("NoSuchUpload") => false, + 409 => false, + 400..=499 => true, + _ => false, + } +} + pub struct S3BlockStore { s3: S3Client, bucket: String, @@ -147,9 +163,9 @@ impl S3BlockStore { /// honest answer is `Unknown`. Same rule as `git::tigris`'s dispatch /// classifier, including the cautious fallback for the `#[non_exhaustive]` /// error enum. - fn classify_complete_failure(err: &SdkError) -> BlockStoreError { + fn classify_complete_failure(err: &SdkError) -> BlockStoreError { if let Some(status) = err.raw_response().map(|r| r.status().as_u16()) { - return if (400..500).contains(&status) { + return if complete_refusal_is_definite(status, ProvideErrorMetadata::code(err)) { Self::backend(format!("complete refused with status {status}")) } else { BlockStoreError::Unknown @@ -175,8 +191,6 @@ impl BlockStore for S3BlockStore { return Ok(PutOutcome::AlreadyPresent); } - // A zero-length body cannot be a multipart upload, but it can be a - // valid (if useless) object under the empty-sha id. let upload = self .s3 .create_multipart_upload() @@ -202,10 +216,17 @@ impl BlockStore for S3BlockStore { return Err(BlockStoreError::TooLarge(max_len)); } hasher.update(&chunk); - part_buf.extend_from_slice(&chunk); - if part_buf.len() >= PART_SIZE { - self.flush_part(&key, &upload_id, &mut part_buf, &mut parts) - .await?; + // A stream item can be as large as a whole block: fill each + // part to PART_SIZE and flush, never copy the item in whole. + let mut rest: &[u8] = &chunk; + while !rest.is_empty() { + let take = (PART_SIZE - part_buf.len()).min(rest.len()); + part_buf.extend_from_slice(&rest[..take]); + rest = &rest[take..]; + if part_buf.len() >= PART_SIZE { + self.flush_part(&key, &upload_id, &mut part_buf, &mut parts) + .await?; + } } } Ok(()) @@ -216,6 +237,10 @@ impl BlockStore for S3BlockStore { self.abort(&key, &upload_id).await; return Err(e); } + if len == 0 { + self.abort(&key, &upload_id).await; + return Err(BlockStoreError::EmptyBlock); + } if hex::encode(hasher.finalize()) != id.as_str() { self.abort(&key, &upload_id).await; return Err(BlockStoreError::DigestMismatch); @@ -229,26 +254,6 @@ impl BlockStore for S3BlockStore { return Err(e); } } - if parts.is_empty() { - // len == 0 and the hash matched, meaning id is the empty-sha. - self.abort(&key, &upload_id).await; - self.s3 - .put_object() - .bucket(&self.bucket) - .key(&key) - .body(ByteStream::from_static(b"")) - .send() - .await - .map_err(|e| { - if e.raw_response().is_none() { - BlockStoreError::Unknown - } else { - Self::backend(e) - } - })?; - return Ok(PutOutcome::Stored); - } - let completed = CompletedMultipartUpload::builder() .set_parts(Some(parts)) .build(); @@ -377,6 +382,8 @@ mod tests { /// past the client's operation timeout, simulating a commit whose /// answer was lost. hang_on_complete: Mutex, + /// Largest single part body the mock has received. + max_part_len: Mutex, } async fn head_handler( @@ -445,6 +452,10 @@ mod tests { q.get("partNumber").and_then(|p| p.parse::().ok()), q.get("uploadId"), ) { + { + let mut max = st.max_part_len.lock().unwrap(); + *max = (*max).max(body.len()); + } st.parts.lock().unwrap().insert((key, part), body.to_vec()); return Response::builder() .status(StatusCode::OK) @@ -543,6 +554,8 @@ mod tests { .route("/{bucket}/{*key}", post(post_handler)) .route("/{bucket}/{*key}", head(head_handler)) .route("/{bucket}/{*key}", delete(delete_handler)) + // Parts are PART_SIZE bytes; axum's 2 MiB default would refuse them. + .layer(axum::extract::DefaultBodyLimit::disable()) .with_state(st.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -615,6 +628,82 @@ mod tests { crate::blockstore::parity::get_range_edge_contract(&s).await; } + #[tokio::test] + async fn empty_body_is_refused_and_leaves_nothing() { + let (url, st) = spawn_mock(false).await; + let s = store(&url); + crate::blockstore::parity::empty_body_contract(&s).await; + assert!(st.parts.lock().unwrap().is_empty()); + assert!(st.map.lock().unwrap().is_empty()); + } + + #[test] + fn complete_failure_classifier_table() { + // Definite refusals stay backend errors. + for (status, code) in [ + (400, Some("InvalidPart")), + (400, Some("EntityTooSmall")), + (403, Some("AccessDenied")), + (404, Some("NoSuchBucket")), + (404, None), + (412, Some("PreconditionFailed")), + ] { + assert!( + complete_refusal_is_definite(status, code), + "{status} {code:?} should be definite" + ); + } + // A retry after a lost-answer commit, a conflicting operation, and + // anything outside 4xx are ambiguous. + for (status, code) in [ + (404, Some("NoSuchUpload")), + (409, Some("OperationAborted")), + (409, None), + (200, Some("InternalError")), + (500, None), + (502, None), + (503, Some("SlowDown")), + ] { + assert!( + !complete_refusal_is_definite(status, code), + "{status} {code:?} should be ambiguous" + ); + } + } + + #[tokio::test] + async fn one_oversized_stream_item_is_split_into_bounded_parts() { + let (url, st) = spawn_mock(false).await; + let s = store(&url); + let body: Vec = (0..(PART_SIZE * 2 + 1234) as u32) + .map(|i| (i % 253) as u8) + .collect(); + let id = id_of(&body); + // One item holding the whole body, then many small items. + assert_eq!( + s.put_verified(&id, stream(body.clone()), u64::MAX) + .await + .unwrap(), + PutOutcome::Stored + ); + assert_eq!(s.size(&id).await.unwrap(), Some(body.len() as u64)); + let got = collect(s.get_range(&id, 0, body.len() as u64).await.unwrap()).await; + assert_eq!(got, body, "split parts must reassemble in order"); + s.delete(&id).await.unwrap(); + let small: Vec> = body.chunks(100_000).map(|c| c.to_vec()).collect(); + let stream_small = + futures::stream::iter(small.into_iter().map(|p| Ok(Bytes::from(p)))).boxed(); + assert_eq!( + s.put_verified(&id, stream_small, u64::MAX).await.unwrap(), + PutOutcome::Stored + ); + let got = collect(s.get_range(&id, 0, body.len() as u64).await.unwrap()).await; + assert_eq!(got, body); + // Parts are consumed by the commit; the mock recorded each upload. + let max_part = st.max_part_len.lock().unwrap(); + assert!(*max_part <= PART_SIZE, "a part held {} bytes", *max_part); + } + #[tokio::test] async fn digest_mismatch_aborts_and_stores_nothing() { let (url, st) = spawn_mock(false).await; diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index bb56a020..b1c68f92 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1175,6 +1175,14 @@ impl Config { /// validated. pub fn validate(&mut self) -> Result<(), String> { self.settle_default_key_paths()?; + if self.model_unclaimed_ttl_secs <= self.model_session_ttl_secs { + return Err(format!( + "TWIGPINE_MODEL_UNCLAIMED_TTL_SECS ({}) must exceed \ + TWIGPINE_MODEL_SESSION_TTL_SECS ({}) so an in-progress upload \ + is never swept under its publisher", + self.model_unclaimed_ttl_secs, self.model_session_ttl_secs + )); + } // Concurrent git writes pin the dedicated lock pool for their whole // duration (connection-affine advisory lock in acquire_write). The main // pool no longer carries that occupancy. @@ -1444,6 +1452,32 @@ mod tests { assert_eq!(config.blockstore_s3_bucket, "model-blocks"); } + #[test] + fn model_unclaimed_ttl_must_exceed_session_ttl() { + let parse = |unclaimed: &str, session: &str| { + let mut config = Config::parse_from([ + "twigpine-node", + "--model-unclaimed-ttl-secs", + unclaimed, + "--model-session-ttl-secs", + session, + ]); + config.validate() + }; + // Reversed and equal both let the sweep delete blocks under an open + // upload session. + let reversed = parse("30", "60").unwrap_err(); + assert!( + reversed.contains("TWIGPINE_MODEL_UNCLAIMED_TTL_SECS"), + "{reversed}" + ); + assert!(parse("60", "60").is_err()); + assert!(parse("61", "60").is_ok()); + // The shipped defaults satisfy the rule. + let mut defaults = Config::parse_from(["twigpine-node"]); + defaults.validate().unwrap(); + } + #[test] fn upstream_mirror_worker_is_default_off_and_bounded() { let mut config = Config::parse_from(["twigpine-node"]); diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 60792c8e..733693e3 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -292,7 +292,7 @@ content-addressed blocks outside git. - `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). -- `TWIGPINE_MODEL_UNCLAIMED_TTL_SECS` - grace period before unclaimed blocks are swept (default 86400). +- `TWIGPINE_MODEL_UNCLAIMED_TTL_SECS` - grace period before unclaimed blocks are swept (default 86400). Must exceed the session TTL; the node refuses to start otherwise. - `TWIGPINE_MODEL_SESSION_TTL_SECS` - base upload-session lifetime, renewed by each accepted block (default 43200). - `TWIGPINE_MODEL_MAX_SESSION_BYTES` - optional cap on one identity's open sessions (defaults to the quota). - `TWIGPINE_BLOCKSTORE_DIR` - where blocks live on disk (default `./data/model-blocks`). From 85e412454c0fc6855e6745562b3f7777c0bc33e0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:25:57 -0600 Subject: [PATCH 28/53] fix(node): pin model.rs on the read_json gate, expire open sessions on status read Enroll model.rs in CONVERTED_IN_186 so no_parse_before_status passes. GET session status now answers 404 once expires_at has passed, matching the block PUT, so the CLI resume path abandons a lapsed session. Add a guard test that a block larger than its declared Content-Length is rejected. --- .../tests/no_parse_before_status.rs | 1 + crates/twigpine-node/src/api/models.rs | 2 +- crates/twigpine-node/tests/models_api.rs | 90 +++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-cli/tests/no_parse_before_status.rs b/crates/twigpine-cli/tests/no_parse_before_status.rs index 708498c1..f9b2bfbd 100644 --- a/crates/twigpine-cli/tests/no_parse_before_status.rs +++ b/crates/twigpine-cli/tests/no_parse_before_status.rs @@ -66,6 +66,7 @@ const CONVERTED_IN_186: &[&str] = &[ "changelog.rs", "issue.rs", "mcp.rs", + "model.rs", "peer.rs", "pr.rs", "protect.rs", diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 480d81a2..d7db08a1 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -94,7 +94,7 @@ pub async fn get_model_session( .db .model_load_session(&id) .await? - .filter(|s| s.repo_id == record.id) + .filter(|s| s.repo_id == record.id && s.expires_at > models::ts_now()) .ok_or_else(|| AppError::NotFound("model upload session not found".into()))?; Ok(Json(json!({ "session_id": session.id, diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index ea89c43e..b0402401 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -545,6 +545,96 @@ async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) node.shutdown().await; } +/// A session bearer that declares a small Content-Length but streams a larger +/// valid block must not get the larger block stored under the small charge. +/// Both framing headers are sent so the body is read to EOF by chunked +/// framing while the handler still sees the understated length. +#[sqlx::test] +async fn put_block_understated_content_length_is_not_stored_under_small_charge(pool: sqlx::PgPool) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let node = spawn_node(pool).await; + let owner_did = Keypair::generate().did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = seed_open_session(&node, &repo_id, &owner_did).await; + + let body = vec![b'x'; 4096]; + let sha = sha256_hex(&body); + let addr = node.base_url.trim_start_matches("http://").to_string(); + let mut sock = tokio::net::TcpStream::connect(&addr) + .await + .expect("connect"); + let head = format!( + "PUT {} HTTP/1.1\r\nHost: {addr}\r\nx-twigpine-model-session: {session_id}\r\n\ + Content-Length: 4\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n", + blocks_path(&owner_did, "model", &sha) + ); + sock.write_all(head.as_bytes()).await.expect("write head"); + sock.write_all(format!("{:x}\r\n", body.len()).as_bytes()) + .await + .expect("write chunk size"); + sock.write_all(&body).await.expect("write body"); + sock.write_all(b"\r\n0\r\n\r\n").await.expect("write end"); + let mut raw = Vec::new(); + let _ = sock.read_to_end(&mut raw).await; + let raw = String::from_utf8_lossy(&raw).to_string(); + let status_line = raw.lines().next().unwrap_or("").to_string(); + eprintln!("raw response: {raw}"); + assert!( + !status_line.contains(" 200 "), + "a block larger than its declared Content-Length must not be admitted: {status_line}" + ); + + node.shutdown().await; +} + +/// An open session past its `expires_at` is dead on the status read too, so +/// the CLI resume path (which abandons a 404) does not keep a lapsed session. +#[sqlx::test] +async fn get_session_expired_open_session_not_found(pool: sqlx::PgPool) { + let node = spawn_node(pool.clone()).await; + let client = bounded_client(); + let kp = Keypair::generate(); + let owner_did = kp.did().to_string(); + let repo_id = node.seed_repo(&owner_did, "model", true).await; + let session_id = "f".repeat(64); + node.seed_model_session(&repo_id, &session_id, &owner_did) + .await; + let path = format!("{}/{session_id}", sessions_path(&owner_did, "model")); + let live = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(live.status().as_u16(), 200, "a live session reads as open"); + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1 WHERE id = $2") + .bind((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()) + .bind(&session_id) + .execute(&pool) + .await + .expect("backdate session expiry"); + let resp = signed_request( + &client, + reqwest::Method::GET, + &node.base_url, + &path, + Vec::new(), + &kp, + ) + .send() + .await + .expect("request sends"); + assert_eq!(resp.status().as_u16(), 404, "a lapsed session is not found"); + + node.shutdown().await; +} + // ── POST /models/claims ────────────────────────────────────────────────────── /// A claim against a pushed commit carrying a signed manifest inserts the From 2973f3e7efcbd8254a7a49b4b7aa4717c51c7c3f Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:24:17 -0600 Subject: [PATCH 29/53] fix(node): fail closed on hostile reconstruction metadata, clean up cancelled block writes Reconstruction validation now uses checked arithmetic, rejects duplicate block rows and block sizes that disagree with their chunks, and map_file_range shares rebuild_file's bounds guard. Safetensors detection caps the header length at 100 MB so a pickle with '{' at byte 8 stays pickle. A dropped put_verified removes its staged file (fs) or aborts its multipart upload (s3) unless the complete request may have committed. --- crates/twigpine-core/src/model/manifest.rs | 14 +- .../twigpine-core/src/model/reconstruction.rs | 181 +++++++++++++++--- crates/twigpine-node/src/blockstore/fs.rs | 37 ++++ crates/twigpine-node/src/blockstore/s3.rs | 98 +++++++++- 4 files changed, 305 insertions(+), 25 deletions(-) diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index de40e391..2085ecc0 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -186,8 +186,14 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { // safetensors: an 8-byte little-endian header length followed by '{'. // Checked before raw pickle: a header length such as 0x0380 starts with // the bytes 0x80 0x03, which the pickle test below would claim. + // The header length is capped at the 100 MB the safetensors reader + // itself enforces, so a pickle whose byte 8 is '{' is not claimed. + const MAX_SAFETENSORS_HEADER: u64 = 100_000_000; + let header_len = first_bytes + .get(..8) + .map(|b| u64::from_le_bytes(b.try_into().unwrap())); if first_bytes.len() >= 9 - && u64::from_le_bytes(first_bytes[..8].try_into().unwrap()) > 0 + && header_len.is_some_and(|n| n > 0 && n <= MAX_SAFETENSORS_HEADER) && first_bytes[8] == b'{' { return FileFormat::Safetensors; @@ -340,6 +346,12 @@ mod tests { "header length {len:#x}" ); } + // A protocol-2 pickle whose byte 8 happens to be '{' ("a{" string) + // has an impossible header length, so it stays pickle. + assert_eq!( + detect_format(b"\x80\x02X\x02\x00\x00\x00a{q\x00.", "x.bin"), + FileFormat::Pickle + ); // A real pickle whose byte 8 is not '{' stays pickle. assert_eq!( detect_format(b"\x80\x04\x95\x00\x00\x00\x00\x00\x00", "x.bin"), diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 35386162..8297d91c 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -99,8 +99,22 @@ impl Reconstruction { /// Structural sanity: terms index real blocks, chunk ranges are ordered, /// and each file's terms sum to its declared size. pub fn validate(&self) -> Result<(), ModelError> { - let blocks: HashMap<&str, &BlockEntry> = - self.blocks.iter().map(|b| (b.sha256.as_str(), b)).collect(); + let mut blocks: HashMap<&str, &BlockEntry> = HashMap::new(); + for b in &self.blocks { + if blocks.insert(b.sha256.as_str(), b).is_some() { + return Err(ModelError::Invalid(format!( + "duplicate block row {}", + b.sha256 + ))); + } + let sum = checked_len_sum(b.chunks.iter().map(|c| c.len), &b.sha256)?; + if sum != b.size { + return Err(ModelError::Invalid(format!( + "block {} declares {} bytes, its chunks sum to {sum}", + b.sha256, b.size + ))); + } + } for file in &self.files { let mut total = 0u64; for term in &file.terms { @@ -126,17 +140,21 @@ impl Reconstruction { block.chunks.len() ))); } - let span: u64 = block.chunks[term.chunk_start as usize..term.chunk_end as usize] - .iter() - .map(|c| c.len) - .sum(); + let span = checked_len_sum( + block.chunks[term.chunk_start as usize..term.chunk_end as usize] + .iter() + .map(|c| c.len), + &term.block, + )?; if span != term.length { return Err(ModelError::Invalid(format!( "{}: term length {span} != declared {}", file.path, term.length ))); } - total += term.length; + total = total.checked_add(term.length).ok_or_else(|| { + ModelError::Invalid(format!("{}: term lengths overflow", file.path)) + })?; } if total != file.size { return Err(ModelError::Invalid(format!( @@ -360,16 +378,26 @@ pub struct BlockSlice { /// Byte offset of each chunk inside a block, as a prefix sum over the /// chunk table: `offsets[i]` is where chunk `i`'s bytes begin. -fn chunk_offsets(block: &BlockEntry) -> Vec { - block - .chunks - .iter() - .scan(0u64, |off, c| { - let start = *off; - *off += c.len; - Some(start) - }) - .collect() +fn chunk_offsets(block: &BlockEntry) -> Result, ModelError> { + let mut off = 0u64; + let mut out = Vec::with_capacity(block.chunks.len()); + for c in &block.chunks { + out.push(off); + off = off + .checked_add(c.len) + .ok_or_else(|| overflow(&block.sha256))?; + } + Ok(out) +} + +fn overflow(what: &str) -> ModelError { + ModelError::Invalid(format!("chunk lengths overflow in {what}")) +} + +/// Sum lengths, refusing a total that wraps `u64`. +fn checked_len_sum(mut lens: impl Iterator, what: &str) -> Result { + lens.try_fold(0u64, |acc, l| acc.checked_add(l)) + .ok_or_else(|| overflow(what)) } /// Byte range inside a block covering the chunks a term names. @@ -383,8 +411,8 @@ fn term_span(block: &BlockEntry, term: &Term) -> Result<(u64, u64), ModelError> block.chunks.len() ))); } - let offsets = chunk_offsets(block); - let len: u64 = block.chunks[start..end].iter().map(|c| c.len).sum(); + let offsets = chunk_offsets(block)?; + let len = checked_len_sum(block.chunks[start..end].iter().map(|c| c.len), &term.block)?; Ok((offsets[start], len)) } @@ -407,19 +435,26 @@ pub fn map_file_range( let block = blocks .get(term.block.as_str()) .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; - let term_end = cursor + term.length; + // The same guard `rebuild_file` uses, so a reconstruction that + // skipped `parse()` gets an error here rather than a slice panic. + term_span(block, term)?; + let term_end = cursor + .checked_add(term.length) + .ok_or_else(|| ModelError::Invalid("term lengths overflow".into()))?; if term_end <= start || cursor >= end_exclusive { cursor = term_end; continue; } - let offsets = chunk_offsets(block); + let offsets = chunk_offsets(block)?; for (i, chunk) in block.chunks[term.chunk_start as usize..term.chunk_end as usize] .iter() .enumerate() { // This chunk covers file bytes [chunk_lo, chunk_hi). let chunk_lo = cursor; - let chunk_hi = cursor + chunk.len; + let chunk_hi = cursor + .checked_add(chunk.len) + .ok_or_else(|| overflow(&term.block))?; cursor = chunk_hi; let s = start.max(chunk_lo); let e = end_exclusive.min(chunk_hi); @@ -487,7 +522,9 @@ pub fn rebuild_file( } out.write_all(data)?; file_hasher.update(data); - written += chunk.len; + written = written + .checked_add(chunk.len) + .ok_or_else(|| overflow(&term.block))?; rel += chunk.len as usize; } } @@ -870,4 +907,102 @@ mod tests { assert_eq!(out, tuned); assert_eq!(fetched, packed.file.size); } + fn hand_rec( + chunk_lens: &[u64], + block_size: u64, + term_len: u64, + file_size: u64, + ) -> Reconstruction { + let chunks: Vec = chunk_lens + .iter() + .enumerate() + .map(|(i, l)| ChunkMeta { + sha256: format!("{i:064x}"), + len: *l, + }) + .collect(); + let n = chunks.len() as u32; + Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.to_string(), + files: vec![FileEntry { + path: "f".into(), + size: file_size, + sha256: "0".repeat(64), + terms: vec![Term { + block: "b".repeat(64), + chunk_start: 0, + chunk_end: n, + length: term_len, + }], + }], + blocks: vec![BlockEntry { + sha256: "b".repeat(64), + size: block_size, + chunks, + }], + } + } + + #[test] + fn a_well_formed_hand_built_reconstruction_validates() { + hand_rec(&[3, 4], 7, 7, 7).validate().unwrap(); + } + + #[test] + fn chunk_lengths_that_wrap_u64_are_refused() { + // [u64::MAX, 1] wraps to 0: a zero-length term over both chunks + // would otherwise pass against a zero-size file. + let rec = hand_rec(&[u64::MAX, 1], 0, 0, 0); + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + } + + #[test] + fn term_lengths_that_wrap_the_file_total_are_refused() { + let mut rec = hand_rec(&[u64::MAX], u64::MAX, u64::MAX, 1); + let t = rec.files[0].terms[0].clone(); + rec.files[0].terms.push(t.clone()); + rec.files[0].terms.push(t); + // MAX + MAX + MAX wraps to MAX - 2... pick a size the wrap hits. + rec.files[0].size = u64::MAX.wrapping_mul(3); + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + } + + #[test] + fn duplicate_block_rows_are_refused() { + let mut rec = hand_rec(&[3, 4], 7, 7, 7); + let dup = rec.blocks[0].clone(); + rec.blocks.push(dup); + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + } + + #[test] + fn a_block_size_that_disagrees_with_its_chunks_is_refused() { + let rec = hand_rec(&[3, 4], 99, 7, 7); + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + } + + #[test] + fn map_file_range_errors_instead_of_panicking_without_parse() { + // Built by hand, never validated: the term names chunks the block + // does not have. + let mut rec = hand_rec(&[3, 4], 7, 7, 7); + rec.files[0].terms[0].chunk_end = 9; + let file = rec.files[0].clone(); + assert!(matches!( + map_file_range(&file, &rec, 0, 7), + Err(ModelError::Invalid(_)) + )); + } + + #[test] + fn chunk_offsets_overflow_is_an_error_not_a_wrap() { + // The block table sums past u64 outside the selected chunks. + let mut rec = hand_rec(&[1, u64::MAX, u64::MAX], 0, 1, 1); + rec.files[0].terms[0].chunk_end = 1; + let file = rec.files[0].clone(); + assert!(matches!( + map_file_range(&file, &rec, 0, 1), + Err(ModelError::Invalid(_)) + )); + } } diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 96ab0389..44f4d0df 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -19,6 +19,18 @@ use tokio::io::AsyncWriteExt; use super::{BlockId, BlockStore, BlockStoreError, PutOutcome}; +/// Removes the staged file when the write future is dropped mid-stream. +/// The explicit `cleanup` calls cover every returned error; this covers +/// cancellation, where no later statement runs. Removing an already-removed +/// path is a harmless no-op, so it needs no disarm. +struct StagedFile(PathBuf); + +impl Drop for StagedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + pub struct FsBlockStore { root: PathBuf, } @@ -130,6 +142,8 @@ 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()), @@ -305,6 +319,29 @@ mod tests { ); } + #[tokio::test] + async fn a_cancelled_put_leaves_no_staged_file() { + let dir = tempfile::tempdir().unwrap(); + let s = store(&dir); + let id = id_of(b"never finishes"); + // Bytes arrive, then the body stalls and the caller drops the write. + let body = futures::stream::iter(vec![Ok(Bytes::from(vec![1u8; 4096]))]) + .chain(futures::stream::pending()) + .boxed(); + let r = tokio::time::timeout( + std::time::Duration::from_millis(300), + s.put_verified(&id, body, u64::MAX), + ) + .await; + assert!(r.is_err()); + assert_eq!( + std::fs::read_dir(dir.path().join("blocks/tmp")) + .unwrap() + .count(), + 0 + ); + } + #[tokio::test] async fn wrong_id_is_rejected_and_leaves_nothing() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index 1eb11788..a8ff1086 100644 --- a/crates/twigpine-node/src/blockstore/s3.rs +++ b/crates/twigpine-node/src/blockstore/s3.rs @@ -51,6 +51,53 @@ fn complete_refusal_is_definite(status: u16, code: Option<&str>) -> bool { } } +/// Aborts an open multipart upload when the write future is dropped before +/// the complete request is sent. Explicit error paths abort inline; this +/// covers cancellation, where no later statement runs. The abort needs the +/// runtime, so it is spawned from `Drop`. +struct AbortOnDrop { + s3: S3Client, + bucket: String, + key: String, + upload_id: String, + armed: bool, +} + +impl AbortOnDrop { + fn disarm(&mut self) { + self.armed = false; + } +} + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + if !self.armed { + return; + } + let Ok(handle) = tokio::runtime::Handle::try_current() else { + return; + }; + let (s3, bucket, key, upload_id) = ( + self.s3.clone(), + self.bucket.clone(), + self.key.clone(), + self.upload_id.clone(), + ); + handle.spawn(async move { + if let Err(e) = s3 + .abort_multipart_upload() + .bucket(bucket) + .key(&key) + .upload_id(upload_id) + .send() + .await + { + tracing::warn!(key = %key, "multipart abort after cancel failed: {e}"); + } + }); + } +} + pub struct S3BlockStore { s3: S3Client, bucket: String, @@ -200,6 +247,13 @@ impl BlockStore for S3BlockStore { .await .map_err(Self::backend)?; let upload_id = upload.upload_id().unwrap_or_default().to_string(); + let mut guard = AbortOnDrop { + s3: self.s3.clone(), + bucket: self.bucket.clone(), + key: key.clone(), + upload_id: upload_id.clone(), + armed: true, + }; let mut hasher = Sha256::new(); let mut len: u64 = 0; @@ -235,14 +289,17 @@ impl BlockStore for S3BlockStore { if let Err(e) = result { self.abort(&key, &upload_id).await; + guard.disarm(); return Err(e); } if len == 0 { self.abort(&key, &upload_id).await; + guard.disarm(); return Err(BlockStoreError::EmptyBlock); } if hex::encode(hasher.finalize()) != id.as_str() { self.abort(&key, &upload_id).await; + guard.disarm(); return Err(BlockStoreError::DigestMismatch); } if !part_buf.is_empty() { @@ -251,9 +308,13 @@ impl BlockStore for S3BlockStore { .await { self.abort(&key, &upload_id).await; + guard.disarm(); return Err(e); } } + // From here the commit may land with its answer lost, so a drop must + // not abort: the caller reconciles with `size()`. + guard.disarm(); let completed = CompletedMultipartUpload::builder() .set_parts(Some(parts)) .build(); @@ -272,6 +333,7 @@ impl BlockStore for S3BlockStore { let verdict = Self::classify_complete_failure(&e); if !matches!(verdict, BlockStoreError::Unknown) { self.abort(&key, &upload_id).await; + guard.disarm(); } Err(verdict) } @@ -384,6 +446,8 @@ mod tests { hang_on_complete: Mutex, /// Largest single part body the mock has received. max_part_len: Mutex, + /// Count of AbortMultipartUpload requests received. + aborts: Mutex, } async fn head_handler( @@ -532,6 +596,7 @@ mod tests { Query(q): Query>, ) -> Response { if q.contains_key("uploadId") { + *st.aborts.lock().unwrap() += 1; st.parts.lock().unwrap().retain(|(k, _), _| k != &key); } else { st.map.lock().unwrap().remove(&key); @@ -621,6 +686,34 @@ mod tests { assert_eq!(s.size(&id).await.unwrap(), None); } + #[tokio::test] + async fn a_cancelled_put_aborts_the_multipart_upload() { + let (url, st) = spawn_mock(false).await; + let s = store(&url); + let first = vec![7u8; PART_SIZE]; + let id = id_of(&first); + // One full part goes up, then the body stalls forever. + let body = futures::stream::iter(vec![Ok(Bytes::from(first))]) + .chain(futures::stream::pending()) + .boxed(); + let r = + tokio::time::timeout(Duration::from_secs(3), s.put_verified(&id, body, u64::MAX)).await; + assert!( + r.is_err(), + "the stalled put must be cancelled by the timeout" + ); + // The abort runs on a spawned task after the drop. + for _ in 0..50 { + if *st.aborts.lock().unwrap() > 0 { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(*st.aborts.lock().unwrap(), 1, "cancel must abort once"); + assert!(st.parts.lock().unwrap().is_empty()); + assert!(st.map.lock().unwrap().is_empty()); + } + #[tokio::test] async fn range_edge_contract_matches_the_trait() { let (url, _st) = spawn_mock(false).await; @@ -736,7 +829,7 @@ mod tests { /// as definitely absent. #[tokio::test] async fn lost_complete_answer_reports_unknown_then_head_resolves() { - let (url, _st) = spawn_mock(true).await; + let (url, st) = spawn_mock(true).await; let s = S3BlockStore::for_testing("blocks", &url, Duration::from_millis(300)); let body = vec![9u8; 1024]; let id = id_of(&body); @@ -745,6 +838,9 @@ mod tests { .await .unwrap_err(); assert!(matches!(err, BlockStoreError::Unknown), "got {err:?}"); + // A lost complete answer may have committed: nothing may abort it. + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(*st.aborts.lock().unwrap(), 0); // The write actually committed server-side; a HEAD sees it. assert_eq!( store(&url).size(&id).await.unwrap(), From 8d6cae263a8ddd7af240484c312cc607126c84b4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:15:46 -0600 Subject: [PATCH 30/53] fix(node): ignore expired sessions in cap sums, refund dedup of released blocks, write resume state owner-only Open-session byte sums used for the per-owner and node-wide caps (and the claim-time node total) now require expires_at > now, matching the PUT and GET liveness rule, so a session past its TTL stops counting before the sweep flips its state. A block PUT that links a block a verifying or published release already carries refunds the admission charge; that release was billed at claim. Blocks held only by other open sessions stay charged. The CLI resume file holds the session bearer and now goes through secret_file::write (0600, no symlink follow), then fsync. --- crates/twigpine-cli/src/model.rs | 27 ++- crates/twigpine-node/src/db/model_queries.rs | 172 ++++++++++++++++++- 2 files changed, 190 insertions(+), 9 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index dd2c2ff1..017c3847 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -444,9 +444,10 @@ fn load_state(path: &Path) -> PublishState { /// resume set, so it is written and fsync'd rather than left in page cache. fn save_state(path: &Path, state: &PublishState) -> Result<()> { let bytes = serde_json::to_vec(state)?; - let mut f = std::fs::File::create(path).with_context(|| format!("write {}", path.display()))?; - f.write_all(&bytes)?; - f.sync_all()?; + // The file holds the session bearer, so it goes through the owner-only + // writer, then is fsync'd (the helper does not sync). + crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; + std::fs::File::open(path)?.sync_all()?; Ok(()) } @@ -1060,6 +1061,26 @@ mod tests { assert!(managed_block_paths("nothing here\n").is_empty()); } + #[cfg(unix)] + #[test] + fn save_state_is_owner_only_even_over_a_loose_file() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(STATE_FILE_NAME); + let state = PublishState { + session_id: "bearer".to_string(), + uploaded: vec![], + }; + save_state(&path, &state).unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&path), 0o600); + // A resume file left loose by an earlier run is tightened on rewrite. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + save_state(&path, &state).unwrap(); + assert_eq!(mode(&path), 0o600); + assert_eq!(load_state(&path), state); + } + #[test] fn publish_state_round_trips() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 3db76275..57a0abfd 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -174,11 +174,12 @@ impl Db { AND s.bytes_received + $1 + COALESCE(( SELECT SUM(o.bytes_received) FROM model_upload_sessions o WHERE o.owner_did = s.owner_did AND o.state = 'open' AND o.id <> s.id + AND o.expires_at > $4 ), 0) <= $5 AND COALESCE((SELECT SUM(q.bytes_used) FROM model_quota_usage q), 0) + COALESCE(( SELECT SUM(o2.bytes_received) FROM model_upload_sessions o2 - WHERE o2.state = 'open' + WHERE o2.state = 'open' AND o2.expires_at > $4 ), 0) + $1 <= $6 RETURNING {SESSION_COLS}" @@ -211,8 +212,12 @@ impl Db { } /// Book the stored block against the session in one transaction. `true` - /// when this PUT was a duplicate within the session (the admission - /// credit was refunded). + /// when the admission credit was refunded: a duplicate within the + /// session, or a block a verifying or published release already carries + /// (that release was billed at claim, and dedup stays free). A block + /// held only by other open sessions is still charged here, because a + /// refund would let sessions hold bytes nobody bills once the first + /// one expires. pub async fn model_record_block( &self, session_id: &str, @@ -241,7 +246,18 @@ impl Db { .execute(&mut *tx) .await? .rows_affected(); - if linked == 0 { + let refund = linked == 0 + || sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + WHERE rb.block_sha256 = $1 + AND r.state IN ('verifying', 'published'))", + ) + .bind(block_sha) + .fetch_one(&mut *tx) + .await?; + if refund { sqlx::query( "UPDATE model_upload_sessions SET bytes_received = GREATEST(bytes_received - $1, 0) @@ -253,7 +269,7 @@ impl Db { .await?; } tx.commit().await?; - Ok(linked == 0) + Ok(refund) } pub async fn model_release_by_commit( @@ -493,11 +509,14 @@ impl Db { /// Node-wide used bytes: claimed quota plus every open session's bytes. pub async fn model_tx_node_used(&self, tx: &mut Transaction<'_, Postgres>) -> Result { // SUM over bigint returns numeric; cast back so the i64 decode holds. + // A session past its wall-clock expiry is dead before the sweep + // flips its state, so it does not count against the cap. Ok(sqlx::query_scalar::<_, Option>( "SELECT (COALESCE((SELECT SUM(bytes_used) FROM model_quota_usage), 0) + COALESCE((SELECT SUM(bytes_received) FROM model_upload_sessions - WHERE state = 'open'), 0))::bigint", + WHERE state = 'open' AND expires_at > $1), 0))::bigint", ) + .bind(ts_now()) .fetch_one(&mut **tx) .await? .unwrap_or(0)) @@ -921,6 +940,147 @@ mod tests { tx.commit().await.unwrap(); } + #[sqlx::test] + async fn caps_ignore_wall_clock_dead_open_sessions(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + // A same-owner peer and a different-owner peer each hold 900 bytes. + let peer_same = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + let peer_other = db.model_open_session("did:other", "r1", 60).await.unwrap(); + for s in [&peer_same, &peer_other] { + db.model_admit_bytes(&s.id, 900, 3600, 10_000, 100_000) + .await + .unwrap() + .expect("peer admission"); + } + // Past the wall-clock TTL the rows still say 'open' until the sweep. + sqlx::query("UPDATE model_upload_sessions SET expires_at = $1") + .bind("2000-01-01T00:00:00+00:00") + .execute(&pool) + .await + .unwrap(); + + // Claim-side node total must not count the dead sessions. + let mut tx = db.model_begin().await.unwrap(); + assert_eq!(db.model_tx_node_used(&mut tx).await.unwrap(), 0); + tx.rollback().await.unwrap(); + + // Per-owner term: the dead same-owner peer must not eat the cap. + let live = db.model_open_session("did:owner", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live.id, 200, 3600, 1000, 100_000) + .await + .unwrap() + .is_some()); + // Node-wide term: both dead peers (1800) must not eat a 1000 cap. + let live2 = db.model_open_session("did:third", "r1", 60).await.unwrap(); + assert!(db + .model_admit_bytes(&live2.id, 200, 3600, 10_000, 1000) + .await + .unwrap() + .is_some()); + } + + async fn seed_release_with_block(pool: &sqlx::PgPool, state: &str, commit: &str, sha: &str) { + sqlx::query( + "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't') + ON CONFLICT DO NOTHING", + ) + .bind(sha) + .execute(pool) + .await + .unwrap(); + let rid: i64 = sqlx::query_scalar( + "INSERT INTO model_releases + (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, + claim_signature, claim_signature_input, claim_signing_string, + claim_body, created_at) + VALUES ('r1', $1, 'main', 'did:owner', $2, 'm', 's', 'i', 'ss', '\\x00', 't') + RETURNING id", + ) + .bind(commit) + .bind(state) + .fetch_one(pool) + .await + .unwrap(); + sqlx::query("INSERT INTO model_release_blocks (release_id, block_sha256) VALUES ($1, $2)") + .bind(rid) + .bind(sha) + .execute(pool) + .await + .unwrap(); + } + + async fn session_bytes(pool: &sqlx::PgPool, id: &str) -> i64 { + sqlx::query_scalar("SELECT bytes_received FROM model_upload_sessions WHERE id = $1") + .bind(id) + .fetch_one(pool) + .await + .unwrap() + } + + #[sqlx::test] + async fn record_block_refunds_only_bytes_a_live_release_already_carries(pool: sqlx::PgPool) { + let db = migrated(pool.clone()).await; + + // Block already carried by a published release: a new session's + // link is free, the release was billed at claim. + let carried = "d".repeat(64); + seed_release_with_block(&pool, "published", "c1", &carried).await; + let s = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(db + .model_record_block(&s.id, &carried, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 0); + + // Block only in a rejected release: nothing bills it, so the + // session keeps the charge. + let dead = "e".repeat(64); + seed_release_with_block(&pool, "rejected", "c2", &dead).await; + let s2 = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + db.model_admit_bytes(&s2.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s2.id, &dead, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s2.id).await, 100); + + // Block held only by another open session: that session is the + // one billed, and a refund here would let a session pair hold + // unbilled bytes once the first expires. + let held = "f".repeat(64); + let a = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + let b = db + .model_open_session("did:owner", "r1", 3600) + .await + .unwrap(); + for x in [&a, &b] { + db.model_admit_bytes(&x.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + } + assert!(!db.model_record_block(&a.id, &held, 100, 100).await.unwrap()); + assert!(!db.model_record_block(&b.id, &held, 100, 100).await.unwrap()); + assert_eq!(session_bytes(&pool, &b.id).await, 100); + } + #[sqlx::test] async fn session_blocks_ignore_expired_sessions(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; From b518cad5490cb6c866117e2a2bdc56bc3b447147 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:30:38 -0600 Subject: [PATCH 31/53] fix(node): refund and skip the session link only for blocks the owner's own live release carries A refunded link outlives its release: a rejection frees the quota and deletes the release's block rows, leaving the session holding the block unbilled while its expiry keeps sliding. Claim already authorizes a publisher's own verifying or published release blocks without a link, so the PUT is neither charged nor linked in that case. Blocks carried by another publisher's release, or held by other open sessions, stay charged and linked. --- crates/twigpine-node/src/db/model_queries.rs | 93 ++++++++++++++------ 1 file changed, 65 insertions(+), 28 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 57a0abfd..4779b787 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -213,11 +213,13 @@ impl Db { /// Book the stored block against the session in one transaction. `true` /// when the admission credit was refunded: a duplicate within the - /// session, or a block a verifying or published release already carries - /// (that release was billed at claim, and dedup stays free). A block - /// held only by other open sessions is still charged here, because a - /// refund would let sessions hold bytes nobody bills once the first - /// one expires. + /// session, or a block a verifying or published release of the session's + /// own owner already carries. Claim authorizes that release's blocks + /// without a session link and billed them at claim, so the block is + /// neither charged nor linked here; a link would outlive the release and + /// hold the block unbilled once it is rejected. Blocks carried by another + /// publisher's release, or held only by other open sessions, are still + /// charged and linked. pub async fn model_record_block( &self, session_id: &str, @@ -236,27 +238,33 @@ impl Db { .bind(ts_now()) .execute(&mut *tx) .await?; - let linked = sqlx::query( - "INSERT INTO model_session_blocks (session_id, block_sha256) - VALUES ($1, $2) - ON CONFLICT (session_id, block_sha256) DO NOTHING", + let own_release_carries = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT 1 FROM model_release_blocks rb + JOIN model_releases r ON r.id = rb.release_id + JOIN model_upload_sessions s ON s.owner_did = r.publisher_did + WHERE rb.block_sha256 = $1 AND s.id = $2 + AND r.state IN ('verifying', 'published'))", ) - .bind(session_id) .bind(block_sha) - .execute(&mut *tx) - .await? - .rows_affected(); - let refund = linked == 0 - || sqlx::query_scalar::<_, bool>( - "SELECT EXISTS ( - SELECT 1 FROM model_release_blocks rb - JOIN model_releases r ON r.id = rb.release_id - WHERE rb.block_sha256 = $1 - AND r.state IN ('verifying', 'published'))", + .bind(session_id) + .fetch_one(&mut *tx) + .await?; + let linked = if own_release_carries { + 0 + } else { + sqlx::query( + "INSERT INTO model_session_blocks (session_id, block_sha256) + VALUES ($1, $2) + ON CONFLICT (session_id, block_sha256) DO NOTHING", ) + .bind(session_id) .bind(block_sha) - .fetch_one(&mut *tx) - .await?; + .execute(&mut *tx) + .await? + .rows_affected() + }; + let refund = linked == 0; if refund { sqlx::query( "UPDATE model_upload_sessions @@ -980,7 +988,13 @@ mod tests { .is_some()); } - async fn seed_release_with_block(pool: &sqlx::PgPool, state: &str, commit: &str, sha: &str) { + async fn seed_release_with_block( + pool: &sqlx::PgPool, + publisher: &str, + state: &str, + commit: &str, + sha: &str, + ) { sqlx::query( "INSERT INTO model_blocks (sha256, size, created_at) VALUES ($1, 100, 't') ON CONFLICT DO NOTHING", @@ -994,11 +1008,12 @@ mod tests { (repo_id, commit_sha, branch, publisher_did, state, manifest_sha256, claim_signature, claim_signature_input, claim_signing_string, claim_body, created_at) - VALUES ('r1', $1, 'main', 'did:owner', $2, 'm', 's', 'i', 'ss', '\\x00', 't') + VALUES ('r1', $1, 'main', $3, $2, 'm', 's', 'i', 'ss', '\\x00', 't') RETURNING id", ) .bind(commit) .bind(state) + .bind(publisher) .fetch_one(pool) .await .unwrap(); @@ -1022,10 +1037,11 @@ mod tests { async fn record_block_refunds_only_bytes_a_live_release_already_carries(pool: sqlx::PgPool) { let db = migrated(pool.clone()).await; - // Block already carried by a published release: a new session's - // link is free, the release was billed at claim. + // Block already carried by the owner's published release: claim + // authorizes it without a link and billed it, so the PUT is free + // and leaves no link behind to outlive the release. let carried = "d".repeat(64); - seed_release_with_block(&pool, "published", "c1", &carried).await; + seed_release_with_block(&pool, "did:owner", "published", "c1", &carried).await; let s = db .model_open_session("did:owner", "r1", 3600) .await @@ -1039,11 +1055,32 @@ mod tests { .await .unwrap()); assert_eq!(session_bytes(&pool, &s.id).await, 0); + let links: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM model_session_blocks WHERE session_id = $1") + .bind(&s.id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(links, 0); + + // Another publisher's published release bills its owner, not this + // session, and the session needs the link to claim the block. + let theirs = "9".repeat(64); + seed_release_with_block(&pool, "did:other", "published", "c3", &theirs).await; + db.model_admit_bytes(&s.id, 100, 3600, 1000, 10_000) + .await + .unwrap() + .unwrap(); + assert!(!db + .model_record_block(&s.id, &theirs, 100, 100) + .await + .unwrap()); + assert_eq!(session_bytes(&pool, &s.id).await, 100); // Block only in a rejected release: nothing bills it, so the // session keeps the charge. let dead = "e".repeat(64); - seed_release_with_block(&pool, "rejected", "c2", &dead).await; + seed_release_with_block(&pool, "did:owner", "rejected", "c2", &dead).await; let s2 = db .model_open_session("did:owner", "r1", 3600) .await From 2a3497ce17e36844fcd19039db6e2a456312f88a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:37:22 -0600 Subject: [PATCH 32/53] docs(node): state that a rejected release is final for its commit --- crates/twigpine-node/src/models/claim.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 1d06e483..45abb9c2 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -171,7 +171,10 @@ pub async fn claim_release( db.model_tx_advisory_lock(&mut tx, CLAIM_LOCK_KEY).await?; // Replay by request digest, then idempotent re-claim by (repo, commit): - // both return the original row. + // both return the original row, whatever its state. A rejected release + // is final for that commit: verification judges the pinned, immutable + // commit, so a retry would re-run the same checks, and the publisher + // retries by minting a new commit. if let Some(existing) = db .model_tx_release_by_digest(&mut tx, &material.request_digest) .await? From 9d9018666df6769481d2db13f2038e3024706bc7 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:58:31 -0600 Subject: [PATCH 33/53] fix(node): dedupe packed block rows and harden reconstruction range mapping Uniform input could seal two identical pending blocks, writing a duplicate block row and pushing the same bytes to the sink twice. seal_pending now patches the placeholder term ids and returns early when an entry with the same id and chunk layout exists, and refuses a second layout for a sealed id. - validate() refuses block rows with zero size or no chunks. - DedupIndex indexes one chunk layout per block id (first writer wins). - map_file_range and rebuild_file share a per-call prefix-offset cache; term_span returns the span from it. - map_file_range refuses terms whose declared length disagrees with their chunk span, and range maps that do not cover the requested bytes. - detect_format flags .pkl/.pickle extensions as pickle. - Document partial-output behavior of rebuild_file and retained sink writes on pack_file_with error. --- crates/twigpine-core/src/model/manifest.rs | 40 ++- .../twigpine-core/src/model/reconstruction.rs | 303 ++++++++++++++++-- 2 files changed, 315 insertions(+), 28 deletions(-) diff --git a/crates/twigpine-core/src/model/manifest.rs b/crates/twigpine-core/src/model/manifest.rs index 2085ecc0..758d9084 100644 --- a/crates/twigpine-core/src/model/manifest.rs +++ b/crates/twigpine-core/src/model/manifest.rs @@ -208,6 +208,9 @@ pub fn detect_format(first_bytes: &[u8], path: &str) -> FileFormat { if first_bytes.starts_with(b"PK\x03\x04") && matches!(ext, "bin" | "pt" | "pth" | "ckpt") { return FileFormat::Pickle; } + if matches!(ext, "pkl" | "pickle") { + return FileFormat::Pickle; + } if matches!( ext, // `tokenizer.model` is deliberately absent: it is a sentencepiece @@ -310,10 +313,21 @@ mod tests { #[test] fn one_changed_byte_invalidates_the_signature() { let (key, did) = keypair(6); - let mut bytes = sample_manifest(&did).to_bytes().unwrap(); + let bytes = sample_manifest(&did).to_bytes().unwrap(); let sig = sign(&key, &bytes); - bytes[10] ^= 1; - assert!(verify(&bytes, &sig, &did).is_err()); + // Tamper inside the signed bytes without breaking the JSON, so the + // check proves the signature, not the parser, caught it. + let mut tampered = bytes.clone(); + let at = tampered + .windows(b"alice/llm".len()) + .position(|w| w == b"alice/llm") + .unwrap(); + tampered[at..at + b"alice/llm".len()].copy_from_slice(b"alice/lln"); + Manifest::parse(&tampered).unwrap(); + assert!(matches!( + verify(&tampered, &sig, &did), + Err(ManifestError::BadSignature) + )); } #[test] @@ -368,6 +382,11 @@ mod tests { detect_format(b"PK\x03\x04z", "archive.zip"), FileFormat::Other ); + // Protocol-0 pickle bytes carry no 0x80 opcode prefix: only the + // extension names them. + assert_eq!(detect_format(b"(dp0\n.", "model.pkl"), FileFormat::Pickle); + assert_eq!(detect_format(b"(dp0\n.", "x.pickle"), FileFormat::Pickle); + assert_eq!(detect_format(b"(dp0\n.", "model.bin"), FileFormat::Other); assert_eq!(detect_format(b"{\"a\":1}", "config.json"), FileFormat::Text); // Sentencepiece models are protobufs, not text. assert_eq!(detect_format(b"", "tokenizer.model"), FileFormat::Other); @@ -410,9 +429,18 @@ mod tests { .unwrap(); let parsed = verify(&bytes, &sig, &did).unwrap(); assert_eq!(parsed.repo, "alice/llm"); - // And the frozen signature rejects tampering. + // And the frozen signature rejects tampering that stays valid + // JSON, so the signature is what fails, not the parser. let mut tampered = bytes.clone(); - *tampered.last_mut().unwrap() ^= 1; - assert!(verify(&tampered, &sig, &did).is_err()); + let at = tampered + .windows(b"alice/llm".len()) + .position(|w| w == b"alice/llm") + .unwrap(); + tampered[at..at + b"alice/llm".len()].copy_from_slice(b"alice/lln"); + Manifest::parse(&tampered).unwrap(); + assert!(matches!( + verify(&tampered, &sig, &did), + Err(ManifestError::BadSignature) + )); } } diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index 8297d91c..f0dd8d7c 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -9,7 +9,7 @@ //! The schema string is part of the signed surface: a reader rejects a tag it //! does not know rather than guessing at a later layout. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::io::{Read, Write}; use serde::{Deserialize, Serialize}; @@ -101,6 +101,12 @@ impl Reconstruction { pub fn validate(&self) -> Result<(), ModelError> { let mut blocks: HashMap<&str, &BlockEntry> = HashMap::new(); for b in &self.blocks { + if b.size == 0 || b.chunks.is_empty() { + return Err(ModelError::Invalid(format!( + "block {} carries no bytes", + b.sha256 + ))); + } if blocks.insert(b.sha256.as_str(), b).is_some() { return Err(ModelError::Invalid(format!( "duplicate block row {}", @@ -184,6 +190,8 @@ impl Default for Reconstruction { pub struct DedupIndex { /// chunk sha256 -> (block sha256, chunk index inside that block) by_chunk: HashMap, + /// Block ids already indexed: one chunk layout per block id. + indexed_blocks: HashSet, } impl DedupIndex { @@ -201,6 +209,9 @@ impl DedupIndex { pub fn add(&mut self, rec: &Reconstruction) { for block in &rec.blocks { + if !self.indexed_blocks.insert(block.sha256.clone()) { + continue; + } for (i, chunk) in block.chunks.iter().enumerate() { // First writer wins: two priors carrying the same chunk are // interchangeable, so keep the earliest. @@ -244,17 +255,32 @@ fn seal_pending std::io::Result<()>>( term.block = block.sha256.clone(); } } + let chunks: Vec = block + .chunks + .iter() + .map(|c| ChunkMeta { + sha256: c.sha256.clone(), + len: c.len as u64, + }) + .collect(); + if let Some(existing) = block_entries.iter().find(|e| e.sha256 == block.sha256) { + // Uniform input can seal the same block bytes twice: the second + // seal adds no row and no sink write, only the id patch above. + if existing.chunks == chunks { + return Ok(()); + } + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "block {} sealed twice with different chunk layouts", + block.sha256 + ), + )); + } block_entries.push(BlockEntry { sha256: block.sha256.clone(), size: block.data.len() as u64, - chunks: block - .chunks - .iter() - .map(|c| ChunkMeta { - sha256: c.sha256.clone(), - len: c.len as u64, - }) - .collect(), + chunks, }); on_block(block) } @@ -291,7 +317,9 @@ pub fn pack_file( /// `pack_file` with each sealed block handed to `on_block` as it finishes: /// the caller can upload and drop it while the file is still packing, so a -/// file of any size packs in block-sized memory. +/// file of any size packs in block-sized memory. If packing fails after +/// `on_block` accepted earlier blocks, those blocks stay in the sink: an +/// error does not mean nothing was stored. pub fn pack_file_with std::io::Result<()>>( path: &str, reader: R, @@ -376,17 +404,18 @@ pub struct BlockSlice { pub len: u64, } -/// Byte offset of each chunk inside a block, as a prefix sum over the -/// chunk table: `offsets[i]` is where chunk `i`'s bytes begin. +/// Prefix offsets over a block's chunk table: `offsets[i]` is where chunk +/// `i`'s bytes begin and the final entry is the block's total length. fn chunk_offsets(block: &BlockEntry) -> Result, ModelError> { let mut off = 0u64; - let mut out = Vec::with_capacity(block.chunks.len()); + let mut out = Vec::with_capacity(block.chunks.len() + 1); for c in &block.chunks { out.push(off); off = off .checked_add(c.len) .ok_or_else(|| overflow(&block.sha256))?; } + out.push(off); Ok(out) } @@ -400,8 +429,9 @@ fn checked_len_sum(mut lens: impl Iterator, what: &str) -> Result Result<(u64, u64), ModelError> { +/// Byte range inside a block covering the chunks a term names, over a +/// prefix-offset table the caller computed once per block. +fn term_span(offsets: &[u64], block: &BlockEntry, term: &Term) -> Result<(u64, u64), ModelError> { let start = term.chunk_start as usize; let end = term.chunk_end as usize; if start >= end || end > block.chunks.len() { @@ -411,9 +441,7 @@ fn term_span(block: &BlockEntry, term: &Term) -> Result<(u64, u64), ModelError> block.chunks.len() ))); } - let offsets = chunk_offsets(block)?; - let len = checked_len_sum(block.chunks[start..end].iter().map(|c| c.len), &term.block)?; - Ok((offsets[start], len)) + Ok((offsets[start], offsets[end] - offsets[start])) } pub fn map_file_range( @@ -429,15 +457,26 @@ pub fn map_file_range( ))); } let blocks = rec.block_index(); + let mut offsets_cache: HashMap<&str, Vec> = HashMap::new(); let mut out: Vec = Vec::new(); let mut cursor = 0u64; for term in &file.terms { let block = blocks .get(term.block.as_str()) .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; + if !offsets_cache.contains_key(term.block.as_str()) { + offsets_cache.insert(term.block.as_str(), chunk_offsets(block)?); + } + let offsets = &offsets_cache[term.block.as_str()]; // The same guard `rebuild_file` uses, so a reconstruction that // skipped `parse()` gets an error here rather than a slice panic. - term_span(block, term)?; + let (_span_offset, span_len) = term_span(offsets, block, term)?; + if span_len != term.length { + return Err(ModelError::Invalid(format!( + "{}: term declares {} bytes, its chunks span {span_len}", + file.path, term.length + ))); + } let term_end = cursor .checked_add(term.length) .ok_or_else(|| ModelError::Invalid("term lengths overflow".into()))?; @@ -445,7 +484,6 @@ pub fn map_file_range( cursor = term_end; continue; } - let offsets = chunk_offsets(block)?; for (i, chunk) in block.chunks[term.chunk_start as usize..term.chunk_end as usize] .iter() .enumerate() @@ -476,6 +514,13 @@ pub fn map_file_range( } cursor = term_end; } + let served: u64 = out.iter().map(|s| s.len).sum(); + if served != end_exclusive - start { + return Err(ModelError::Invalid(format!( + "{}: range {start}..{end_exclusive} maps to {served} bytes", + file.path + ))); + } Ok(out) } @@ -488,7 +533,10 @@ pub type BlockRangeFetch<'a> = dyn FnMut(&str, u64, u64) -> std::io::Result( file: &FileEntry, rec: &Reconstruction, @@ -496,13 +544,18 @@ pub fn rebuild_file( out: &mut W, ) -> Result { let blocks = rec.block_index(); + let mut offsets_cache: HashMap<&str, Vec> = HashMap::new(); let mut file_hasher = sha2::Sha256::new(); let mut written = 0u64; for term in &file.terms { let block = blocks .get(term.block.as_str()) .ok_or_else(|| ModelError::Invalid(format!("unknown block {}", term.block)))?; - let (offset, span_len) = term_span(block, term)?; + if !offsets_cache.contains_key(term.block.as_str()) { + offsets_cache.insert(term.block.as_str(), chunk_offsets(block)?); + } + let offsets = &offsets_cache[term.block.as_str()]; + let (offset, span_len) = term_span(offsets, block, term)?; let bytes = fetch(&term.block, offset, span_len)?; if bytes.len() as u64 != span_len { return Err(ModelError::Invalid(format!( @@ -967,6 +1020,34 @@ mod tests { assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); } + #[test] + fn zero_size_block_rows_are_refused() { + // A dangling empty row unreferenced by any term. + let mut rec = hand_rec(&[3, 4], 7, 7, 7); + rec.files[0].terms.clear(); + rec.files[0].size = 0; + rec.blocks[0].size = 0; + rec.blocks[0].chunks.clear(); + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + // A row whose chunks are all zero-length is empty too. + let mut rec = hand_rec(&[0, 0], 0, 0, 0); + rec.files[0].terms.clear(); + rec.files[0].size = 0; + assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); + // An empty file stays legal: no terms, no blocks, zero bytes. + let rec = Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.into(), + files: vec![FileEntry { + path: "empty".into(), + size: 0, + sha256: "0".repeat(64), + terms: vec![], + }], + blocks: vec![], + }; + rec.validate().unwrap(); + } + #[test] fn duplicate_block_rows_are_refused() { let mut rec = hand_rec(&[3, 4], 7, 7, 7); @@ -994,6 +1075,184 @@ mod tests { )); } + #[test] + fn a_resealed_identical_block_is_not_duplicated() { + // Uniform input chunks identically, so two windows of pending + // chunks seal into blocks with the same content id: the second seal + // must patch terms but add neither a block row nor a sink write. + let bytes = vec![0u8; 134 * 1024 * 1024]; + let mut sink: Vec = Vec::new(); + let (file, entries) = pack_file_with( + "zeros.bin", + Cursor::new(bytes.clone()), + &DedupIndex::new(), + |b| { + sink.push(b); + Ok(()) + }, + ) + .unwrap(); + let ids: std::collections::HashSet<&str> = + entries.iter().map(|e| e.sha256.as_str()).collect(); + assert_eq!(ids.len(), entries.len(), "duplicate block row sealed"); + let mut counts: HashMap<&str, usize> = HashMap::new(); + for t in &file.terms { + *counts.entry(t.block.as_str()).or_default() += 1; + } + assert!( + counts.values().any(|n| *n > 1), + "no term revisited a block id" + ); + let sink_ids: std::collections::HashSet<&str> = + sink.iter().map(|b| b.sha256.as_str()).collect(); + assert_eq!(sink_ids.len(), sink.len(), "sink got a block id twice"); + assert!(entries.len() > 1, "expected at least two unique blocks"); + let rec = Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.into(), + files: vec![file.clone()], + blocks: entries, + }; + rec.validate().unwrap(); + let store: HashMap> = sink + .iter() + .map(|b| (b.sha256.clone(), b.data.clone())) + .collect(); + let mut out = Vec::new(); + rebuild_file( + &file, + &rec, + &mut |id, off, len| { + let block = store.get(id).expect("block"); + Ok(block[off as usize..(off + len) as usize].to_vec()) + }, + &mut out, + ) + .unwrap(); + assert_eq!(out, bytes); + } + + #[test] + fn sealing_the_same_block_id_with_a_different_layout_is_an_error() { + let mk = |data: &[u8]| crate::model::chunking::Chunk { + sha256: sha256_hex(data), + len: data.len(), + offset: 0, + data: data.to_vec(), + }; + let mut block_entries = Vec::new(); + let mut terms: Vec = Vec::new(); + let mut pending = vec![mk(&[1, 2]), mk(&[3, 4])]; + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &mut |_| Ok(()), + ) + .unwrap(); + assert_eq!(block_entries.len(), 1); + // Same block bytes, split differently: the second seal must fail + // rather than write a conflicting row for the same id. + let mut pending = vec![mk(&[1, 2, 3, 4])]; + let err = seal_pending(&mut pending, &mut terms, &mut block_entries, &mut |_| { + panic!("a mismatched reseal must not reach the sink") + }) + .unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn the_dedup_index_keeps_one_layout_per_block_id() { + let block_id = "x".repeat(64); + let mk_block = |chunks: &[&str]| BlockEntry { + sha256: block_id.clone(), + size: chunks.len() as u64, + chunks: chunks + .iter() + .map(|s| ChunkMeta { + sha256: s.to_string(), + len: 1, + }) + .collect(), + }; + let mut prior_a = Reconstruction::new(); + prior_a.blocks.push(mk_block(&["a", "b"])); + let mut prior_b = Reconstruction::new(); + prior_b.blocks.push(mk_block(&["ab"])); + let idx = DedupIndex::from_reconstructions(&[&prior_a, &prior_b]); + assert!(idx.by_chunk.contains_key("a")); + assert!(idx.by_chunk.contains_key("b")); + assert_eq!( + idx.by_chunk.get("a").map(|(b, _)| b.as_str()), + Some(block_id.as_str()) + ); + assert!( + !idx.by_chunk.contains_key("ab"), + "a second layout for an indexed block id must not enter the index" + ); + } + + #[test] + fn a_term_length_that_disagrees_with_its_span_is_refused() { + // Two one-byte chunks, terms declaring 0 and 2 bytes: a hand-built + // reconstruction whose declared lengths lie about the spans. + let block_id = "b".repeat(64); + let rec = Reconstruction { + schema: RECONSTRUCTION_SCHEMA_V1.into(), + files: vec![FileEntry { + path: "f".into(), + size: 2, + sha256: "0".repeat(64), + terms: vec![ + Term { + block: block_id.clone(), + chunk_start: 0, + chunk_end: 1, + length: 0, + }, + Term { + block: block_id.clone(), + chunk_start: 1, + chunk_end: 2, + length: 2, + }, + ], + }], + blocks: vec![BlockEntry { + sha256: block_id, + size: 2, + chunks: vec![ + ChunkMeta { + sha256: "a".repeat(64), + len: 1, + }, + ChunkMeta { + sha256: "c".repeat(64), + len: 1, + }, + ], + }], + }; + let file = rec.files[0].clone(); + assert!(matches!( + map_file_range(&file, &rec, 0, 1), + Err(ModelError::Invalid(_)) + )); + } + + #[test] + fn a_range_the_terms_do_not_cover_is_refused() { + // The file declares two bytes but its single term covers one: + // asking for the second byte must error rather than return a short + // map, while an empty range still maps to nothing. + let rec = hand_rec(&[1], 1, 1, 2); + let file = rec.files[0].clone(); + assert!(matches!( + map_file_range(&file, &rec, 1, 2), + Err(ModelError::Invalid(_)) + )); + assert!(map_file_range(&file, &rec, 0, 0).unwrap().is_empty()); + } + #[test] fn chunk_offsets_overflow_is_an_error_not_a_wrap() { // The block table sums past u64 outside the selected chunks. From a3edf0726052346f23594764e9fa6ce4db5132d6 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:06:27 -0600 Subject: [PATCH 34/53] fix(node): check sealed blocks against prior layouts and restore the overflow test seal_pending now consults the dedup index's per-block chunk layouts: a reseal of a block id a prior already stores adds no row and no upload when the layout matches, and fails InvalidData when it does not. - DedupIndex keeps layouts (block id -> chunk list) instead of bare ids. - pack_file docs note the returned entries omit blocks a prior carries. - chunk_lengths_that_wrap_u64_are_refused uses sizes that only the checked sums refuse; the empty-block guard was catching it first. --- .../twigpine-core/src/model/reconstruction.rs | 141 ++++++++++++++++-- 1 file changed, 128 insertions(+), 13 deletions(-) diff --git a/crates/twigpine-core/src/model/reconstruction.rs b/crates/twigpine-core/src/model/reconstruction.rs index f0dd8d7c..51f9ad68 100644 --- a/crates/twigpine-core/src/model/reconstruction.rs +++ b/crates/twigpine-core/src/model/reconstruction.rs @@ -9,7 +9,7 @@ //! The schema string is part of the signed surface: a reader rejects a tag it //! does not know rather than guessing at a later layout. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::io::{Read, Write}; use serde::{Deserialize, Serialize}; @@ -190,8 +190,9 @@ impl Default for Reconstruction { pub struct DedupIndex { /// chunk sha256 -> (block sha256, chunk index inside that block) by_chunk: HashMap, - /// Block ids already indexed: one chunk layout per block id. - indexed_blocks: HashSet, + /// Block id -> chunk layout, one per block id: seal_pending refuses a + /// second layout for an id a prior already carries. + layouts: HashMap>, } impl DedupIndex { @@ -209,9 +210,11 @@ impl DedupIndex { pub fn add(&mut self, rec: &Reconstruction) { for block in &rec.blocks { - if !self.indexed_blocks.insert(block.sha256.clone()) { + if self.layouts.contains_key(&block.sha256) { continue; } + self.layouts + .insert(block.sha256.clone(), block.chunks.clone()); for (i, chunk) in block.chunks.iter().enumerate() { // First writer wins: two priors carrying the same chunk are // interchangeable, so keep the earliest. @@ -230,6 +233,7 @@ fn seal_pending std::io::Result<()>>( pending: &mut Vec, terms: &mut [Term], block_entries: &mut Vec, + dedup: &DedupIndex, on_block: &mut F, ) -> std::io::Result<()> { if pending.is_empty() { @@ -263,6 +267,20 @@ fn seal_pending std::io::Result<()>>( len: c.len as u64, }) .collect(); + if let Some(prior_layout) = dedup.layouts.get(&block.sha256) { + // A prior reconstruction already stores this block: its row lives + // there, so a same-layout reseal adds neither a row nor an upload. + if *prior_layout == chunks { + return Ok(()); + } + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "block {} sealed with a chunk layout that differs from a prior's", + block.sha256 + ), + )); + } if let Some(existing) = block_entries.iter().find(|e| e.sha256 == block.sha256) { // Uniform input can seal the same block bytes twice: the second // seal adds no row and no sink write, only the id patch above. @@ -287,6 +305,8 @@ fn seal_pending std::io::Result<()>>( /// What `pack_file` produced: the file's entry, the new blocks to store and /// upload, and the block entries the reconstruction object must carry. +/// Blocks a prior reconstruction already holds appear as terms into the +/// prior's rows, not as rows here. pub struct PackedFile { pub file: FileEntry, pub new_blocks: Vec, @@ -317,7 +337,9 @@ pub fn pack_file( /// `pack_file` with each sealed block handed to `on_block` as it finishes: /// the caller can upload and drop it while the file is still packing, so a -/// file of any size packs in block-sized memory. If packing fails after +/// file of any size packs in block-sized memory. The returned block entries +/// omit blocks a prior already carries, the same way terms into prior +/// blocks carry no row of their own. If packing fails after /// `on_block` accepted earlier blocks, those blocks stay in the sink: an /// error does not mean nothing was stored. pub fn pack_file_with std::io::Result<()>>( @@ -377,12 +399,24 @@ pub fn pack_file_with std::io::Result<()>>( }), } if pending_bytes >= BLOCK_TARGET { - seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + dedup, + &mut on_block, + )?; pending_bytes = 0; } } } - seal_pending(&mut pending, &mut terms, &mut block_entries, &mut on_block)?; + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + dedup, + &mut on_block, + )?; let file = FileEntry { path: path.to_string(), @@ -1003,9 +1037,9 @@ mod tests { #[test] fn chunk_lengths_that_wrap_u64_are_refused() { - // [u64::MAX, 1] wraps to 0: a zero-length term over both chunks - // would otherwise pass against a zero-size file. - let rec = hand_rec(&[u64::MAX, 1], 0, 0, 0); + // [u64::MAX, 2] wraps to 1, matching the declared sizes, so only + // the checked sums refuse it. + let rec = hand_rec(&[u64::MAX, 2], 1, 1, 1); assert!(matches!(rec.validate(), Err(ModelError::Invalid(_)))); } @@ -1141,11 +1175,13 @@ mod tests { }; let mut block_entries = Vec::new(); let mut terms: Vec = Vec::new(); + let dedup = DedupIndex::new(); let mut pending = vec![mk(&[1, 2]), mk(&[3, 4])]; seal_pending( &mut pending, &mut terms, &mut block_entries, + &dedup, &mut |_| Ok(()), ) .unwrap(); @@ -1153,13 +1189,91 @@ mod tests { // Same block bytes, split differently: the second seal must fail // rather than write a conflicting row for the same id. let mut pending = vec![mk(&[1, 2, 3, 4])]; - let err = seal_pending(&mut pending, &mut terms, &mut block_entries, &mut |_| { - panic!("a mismatched reseal must not reach the sink") - }) + let err = seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &dedup, + &mut |_| panic!("a mismatched reseal must not reach the sink"), + ) + .unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn sealing_a_prior_block_id_with_a_different_layout_is_an_error() { + // The prior stored the block as one chunk; the same bytes pending + // here split into two. The id matches, the layout does not. + let prior_id = sha256_hex(&[1, 2, 3, 4]); + let mut prior = Reconstruction::new(); + prior.blocks.push(BlockEntry { + sha256: prior_id, + size: 4, + chunks: vec![ChunkMeta { + sha256: sha256_hex(&[1, 2, 3, 4]), + len: 4, + }], + }); + let dedup = DedupIndex::from_reconstructions(&[&prior]); + let mk = |data: &[u8]| crate::model::chunking::Chunk { + sha256: sha256_hex(data), + len: data.len(), + offset: 0, + data: data.to_vec(), + }; + let mut block_entries = Vec::new(); + let mut terms: Vec = Vec::new(); + let mut pending = vec![mk(&[1, 2]), mk(&[3, 4])]; + let err = seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &dedup, + &mut |_| panic!("a reseal against a prior must not reach the sink"), + ) .unwrap_err(); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); } + #[test] + fn sealing_a_block_a_prior_already_carries_adds_no_row_or_upload() { + let prior_id = sha256_hex(&[1, 2, 3, 4]); + let mut prior = Reconstruction::new(); + prior.blocks.push(BlockEntry { + sha256: prior_id.clone(), + size: 4, + chunks: vec![ChunkMeta { + sha256: prior_id.clone(), + len: 4, + }], + }); + let dedup = DedupIndex::from_reconstructions(&[&prior]); + let mut block_entries = Vec::new(); + let mut terms = vec![Term { + block: String::new(), + chunk_start: 0, + chunk_end: 1, + length: 4, + }]; + let mk = |data: &[u8]| crate::model::chunking::Chunk { + sha256: sha256_hex(data), + len: data.len(), + offset: 0, + data: data.to_vec(), + }; + let mut pending = vec![mk(&[1, 2, 3, 4])]; + seal_pending( + &mut pending, + &mut terms, + &mut block_entries, + &dedup, + &mut |_| panic!("a block a prior stores is not uploaded again"), + ) + .unwrap(); + assert!(block_entries.is_empty()); + assert_eq!(terms[0].block, prior_id); + } + #[test] fn the_dedup_index_keeps_one_layout_per_block_id() { let block_id = "x".repeat(64); @@ -1179,6 +1293,7 @@ mod tests { let mut prior_b = Reconstruction::new(); prior_b.blocks.push(mk_block(&["ab"])); let idx = DedupIndex::from_reconstructions(&[&prior_a, &prior_b]); + assert_eq!(idx.layouts[&block_id].len(), 2); assert!(idx.by_chunk.contains_key("a")); assert!(idx.by_chunk.contains_key("b")); assert_eq!( From 590207909b755ac9a0f6c5e84f62a8fb7dcafb8a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:28:06 -0600 Subject: [PATCH 35/53] fix(node): fsync the publish resume file through a writable handle and correct the publish confirm text save_state reopened the file read-only for sync_all, which fails with Access is denied on Windows and broke publish_state_round_trips there. Sync through a write handle instead. The confirm prompt claimed IPFS pinning and Arweave anchoring, which this path does not do. State what it does: blocks go to the node's block store and the signed manifest to git. --- crates/twigpine-cli/src/model.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 017c3847..4ad197db 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -447,7 +447,10 @@ fn save_state(path: &Path, state: &PublishState) -> Result<()> { // The file holds the session bearer, so it goes through the owner-only // writer, then is fsync'd (the helper does not sync). crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; - std::fs::File::open(path)?.sync_all()?; + std::fs::OpenOptions::new() + .write(true) + .open(path)? + .sync_all()?; Ok(()) } @@ -623,8 +626,10 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } } eprintln!( - "publishing is permanent: blocks are pinned to IPFS and the manifest anchors \ - to Arweave, so the bytes stay fetchable even if this repo is later removed" + "publishing stores the blocks in this node's configured block store and commits a \ + signed release manifest to git: the bytes stay available only while this node \ + keeps them and the repo stays readable, and nothing is pinned to IPFS or \ + anchored to Arweave" ); if !args.yes && !confirm_publish()? { println!("aborted"); From f72024b96c4813d3f19a179b687887cc5c662004 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:31:56 -0600 Subject: [PATCH 36/53] test(node): assert owner claim POST on a private repo returns 400 --- crates/twigpine-node/tests/models_api.rs | 28 +++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index b0402401..3f2cedca 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -862,9 +862,11 @@ async fn release_get_published_unknown_and_private(pool: sqlx::PgPool) { } /// The reconstruction GET and the claims POST hide a repo that is not fully -/// public: every caller class gets the same 404, none reach the store or the -/// commit lookup. The deny sweep cannot drive the hostile-only legs for the -/// reconstruction route, so they live here. +/// 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; @@ -927,5 +929,25 @@ async fn reconstruction_and_claims_deny_on_private_repo(pool: sqlx::PgPool) { 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; } From 9beba1377797255c66a50e80634a0e8cebc4b7dc Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:31:56 -0600 Subject: [PATCH 37/53] fix(cli): exit non-zero when publish is still verifying past the poll budget --- crates/twigpine-cli/src/model.rs | 40 +++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 4ad197db..450c5eb5 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -5,7 +5,9 @@ //! large ones into content blocks with cross-release dedup, uploads the new //! blocks under an upload session (resuming from a `.git` state file after an //! interruption), commits the signed manifest, pushes, claims the release, -//! and polls until the node's verification publishes it. +//! 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}; @@ -44,7 +46,9 @@ const POLL_BUDGET: Duration = Duration::from_secs(300); #[derive(Subcommand)] pub enum ModelCmd { - /// Publish the working tree as a signed model release + /// 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), } @@ -552,6 +556,15 @@ async fn upload_block( 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 { @@ -998,12 +1011,11 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } _ => { if Instant::now() >= deadline { - println!( - "release {release_id} is still verifying after {}s; its status is at\n \ - GET {release_path}", - POLL_BUDGET.as_secs() - ); - return Ok(()); + return Err(still_verifying_error( + release_id, + POLL_BUDGET.as_secs(), + &release_path, + )); } tokio::time::sleep(POLL_INTERVAL).await; } @@ -1059,6 +1071,18 @@ mod tests { 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"); From 2ef2b63730afeb1930d9138f251deb39a15723d0 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:31:56 -0600 Subject: [PATCH 38/53] fix(node): reject a release after five consecutive verify failures --- crates/twigpine-node/src/models/verify.rs | 213 +++++++++++++++++++++- 1 file changed, 209 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index df4300c5..535d0da6 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -357,7 +357,7 @@ async fn ensure_release_refs_hidden( { continue; } - crate::git::store::run_git_bounded( + let out = crate::git::store::run_git_bounded( git_bin, disk_path, &["config", "--add", key, value], @@ -367,6 +367,18 @@ async fn ensure_release_refs_hidden( ) .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(()) } @@ -420,6 +432,9 @@ pub async fn reject_release( 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() => {} @@ -432,10 +447,200 @@ pub async fn run_verify_worker(state: AppState) { continue; } }; - for id in ids { - if let Err(e) = verify_release(&state, id).await { - tracing::warn!("model release {id} verification errored: {e}"); + 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"); } } From 0b919ddb5bc3114d1fc5bea8f0a2fbe985b9486b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:42:54 -0600 Subject: [PATCH 39/53] style: cargo fmt --- crates/twigpine-cli/src/model.rs | 5 ++- crates/twigpine-node/src/models/verify.rs | 54 +++++++++++++++-------- 2 files changed, 39 insertions(+), 20 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 450c5eb5..661b61fb 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -1080,7 +1080,10 @@ mod tests { 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}"); + assert!( + msg.contains("/api/v1/repos/o/r/models/releases/cc"), + "{msg}" + ); } #[test] diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 535d0da6..02fe4a77 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -544,12 +544,19 @@ mod tests { &manifest_bytes, ) .expect("manifest"); - std::fs::write(dir.path().join(".twigpine/model-release.sig"), sig) - .expect("sig"); + 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"], + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "r1", + ], ); let commit = git(dir.path(), &["rev-parse", "HEAD"]); @@ -588,28 +595,29 @@ mod tests { 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"); + 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"); + 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"); + 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}" @@ -620,7 +628,15 @@ mod tests { git(dir.path(), &["add", "a.txt"]); git( dir.path(), - &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "r2"], + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "r2", + ], ); let commit2 = git(dir.path(), &["rev-parse", "HEAD"]); let record = state From c1c6c40ede6e2a13df90a5cc957b1ba08b2990a6 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:31:56 -0600 Subject: [PATCH 40/53] fix(cli): isolate release staging, literal pathspecs, remote push check, gitignore guards --- crates/twigpine-cli/src/model.rs | 359 ++++++++++++++++++++++++++----- 1 file changed, 311 insertions(+), 48 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index 661b61fb..f4fb31a1 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -119,6 +119,25 @@ fn git_lines(root: &Path, args: &[&str]) -> Result> { .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")?; @@ -206,6 +225,24 @@ fn detect_remote(root: &Path) -> Result<(String, String, String)> { 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)); } } @@ -259,6 +296,9 @@ struct Scan { /// 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 @@ -280,13 +320,14 @@ fn tracked_paths(root: &Path) -> Result> { /// Paths listed inside the managed .gitignore block (empty when there is no /// block): previously published chunked files. -/// One repo-relative path as a gitignore pattern line: pattern -/// metacharacters and a trailing space are backslash-escaped. +/// 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::new(); + let mut out = String::from("/"); let mut chars = p.chars().peekable(); while let Some(c) = chars.next() { - if matches!(c, '\\' | '!' | '#' | '[' | ']') { + if matches!(c, '\\' | '!' | '#' | '[' | ']' | '*' | '?') { out.push('\\'); } if c == ' ' && chars.peek().is_none() { @@ -298,6 +339,9 @@ fn escape_gitignore_path(p: &str) -> String { } 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() { @@ -346,16 +390,23 @@ fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { 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 (or a tracked file - // deleted in the worktree, whose staged deletion `git add -A` picks - // up) is simply not in the publishable set. - let Ok(meta) = std::fs::symlink_metadata(root.join(path)) else { - return; + // 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; @@ -392,6 +443,7 @@ fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { scan.chunked_files.sort(); scan.refused.sort(); scan.skipped_ignored.sort(); + scan.deleted.sort(); Ok(scan) } @@ -484,16 +536,30 @@ fn read_head(path: &Path, n: u64) -> Result> { Ok(buf) } -/// Bytes of the staged index blob for `path`: exactly what the release -/// commit will store, filters and symlink handling included. -fn staged_blob(root: &Path, path: &str) -> Result> { +/// 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. - let out = git(root, &["ls-files", "-s", "-z", "--", path])?; + // 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`: the sha is the second blank field. - let sha = stdout + // ` \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()) @@ -788,11 +854,17 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. - let needed: HashSet = rec + // 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) { @@ -826,47 +898,76 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { println!("uploaded reconstruction object"); } - // 7. Managed .gitignore block, then stage exactly the publishable set - // through a NUL pathspec: a bare `git add -A` would sweep in work the - // scan never saw (files created or un-ignored during the upload, or - // index changes staged for something else). + // 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 { + for p in scan.git_files.iter().chain(&scan.deleted) { spec.extend_from_slice(p.as_bytes()); spec.push(0); } - for p in [ - ".gitignore", - ".twigpine/model-release.json", - ".twigpine/model-release.sig", - ] { - spec.extend_from_slice(p.as_bytes()); + if gitignore_path.is_file() { + spec.extend_from_slice(b".gitignore"); spec.push(0); } - std::fs::write(&pathspec_path, spec)?; + 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?; } - let staged = git( - &root, - &[ - "add", - "-A", - "--pathspec-file-nul", - &format!("--pathspec-from-file={}", pathspec_path.display()), - ], - ); - let _ = std::fs::remove_file(&pathspec_path); - staged?; - // 8. Hash the git-stored files from the index (the exact bytes the - // commit stores), then write and stage the manifest. + // 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, path)?; + let bytes = staged_blob(&root, &index_path, path)?; files.push(ManifestFile { path: path.clone(), size: bytes.len() as u64, @@ -909,20 +1010,26 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { ) ), )?; - git( + git_index( &root, + &index_path, &[ + "--literal-pathspecs", "add", ".twigpine/model-release.json", ".twigpine/model-release.sig", ], )?; - // 9. Commit when the index differs, push, and claim HEAD. - let has_changes = git(&root, &["diff", "--cached", "--quiet"]).is_err(); + // 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(&root, &["commit", "-m", &format!("model release {n}")])?; + 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. @@ -936,6 +1043,7 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { } println!("no changes to commit; claiming the existing release commit"); } + let _ = std::fs::remove_file(&index_path); let commit = git_lines(&root, &["rev-parse", "HEAD"])? .into_iter() .next() @@ -1055,7 +1163,7 @@ mod tests { let once = upsert_managed_block(&base, &paths); assert!(once.contains("*.tmp\n")); assert!(once.contains(GITIGNORE_BEGIN)); - assert!(once.contains("weights/a.bin\nb.bin\n")); + assert!(once.contains("/weights/a.bin\n/b.bin\n")); assert!(once.contains(GITIGNORE_END)); assert_eq!(once, upsert_managed_block(&once, &paths), "idempotent"); @@ -1227,4 +1335,159 @@ mod tests { ); 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" + ); + } + + #[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("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(); + git_index( + dir.path(), + &index, + &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "rel"], + ) + .unwrap(); + let tree = tgit(dir.path(), &["ls-tree", "--name-only", "HEAD"]); + assert!(!tree.contains("unrelated.bin"), "{tree}"); + assert!(tree.contains("b.txt"), "{tree}"); + let staged_files = tgit( + dir.path(), + &["diff", "--cached", "--name-only", "--diff-filter=A"], + ); + assert_eq!(staged_files, "unrelated.bin"); + } + + #[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())); + } } From bca662b560168ff3843a91bc67f4de59c76c1196 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:32:04 -0600 Subject: [PATCH 41/53] fix(node): digest replay before parent check, admit lock in claim, capped manifest read, streamed reconstruction, i64 cap validation --- crates/twigpine-node/src/api/models.rs | 9 ++- crates/twigpine-node/src/config.rs | 46 +++++++++++ crates/twigpine-node/src/db/model_queries.rs | 15 +++- crates/twigpine-node/src/git/store.rs | 81 ++++++++++++++++++++ crates/twigpine-node/src/models/claim.rs | 40 ++++++++-- 5 files changed, 182 insertions(+), 9 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index d7db08a1..58952b7f 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -389,11 +389,16 @@ pub async fn get_model_reconstruction( .ok() .flatten() .ok_or_else(|| AppError::NotFound("reconstruction object not stored".into()))?; - let bytes = models::read_block(&store, &sha, size) + // 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")], - bytes, + axum::body::Body::from_stream(stream), )) } diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 59084b4f..16bc8418 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1215,6 +1215,24 @@ 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 +1710,34 @@ 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/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 4779b787..b6a50103 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -28,7 +28,7 @@ type SessionTuple = (String, String, String, String, i64, String); /// Global advisory key serializing block-byte admission across sessions /// (see `model_admit_bytes`). Distinct from `CLAIM_LOCK_KEY` in /// `crate::models`, which serializes claim admission. -const MODEL_ADMIT_LOCK: i64 = 0x6D6F64656C61646D; // "modeladm" +pub(crate) const MODEL_ADMIT_LOCK: i64 = 0x6D6F64656C61646D; // "modeladm" const SESSION_COLS: &str = "id, owner_did, repo_id, expires_at, bytes_received, state"; @@ -280,6 +280,19 @@ impl Db { Ok(refund) } + 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, diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 896723b9..2f4d351d 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -404,6 +404,87 @@ pub(crate) 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/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 45abb9c2..2fe6ec11 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -26,6 +26,11 @@ 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, @@ -33,13 +38,14 @@ pub(crate) async fn git_show( path: &str, ) -> Result>, AppError> { let spec = format!("{commit}:{path}"); - let out = crate::git::store::run_git_bounded( + 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)?; @@ -142,6 +148,17 @@ pub async fn claim_release( 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. @@ -169,6 +186,10 @@ pub async fn claim_release( 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 @@ -221,15 +242,22 @@ pub async fn claim_release( let parent_blocks: std::collections::HashSet = match &parent { None => std::collections::HashSet::new(), Some((prepo_id, pcommit)) => { - let rows = db - .model_tx_release_blocks_at_commit(&mut tx, prepo_id, pcommit) - .await?; - if rows.is_empty() { + // 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", )); } - rows.into_iter().collect() + db.model_tx_release_blocks_at_commit(&mut tx, prepo_id, pcommit) + .await? + .into_iter() + .collect() } }; for b in &blocks { From bcf17f0a0867c3eb5b1510cf87d529796b040ad6 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:32:04 -0600 Subject: [PATCH 42/53] fix(node): flush before sync, fsync chain on retry and delete, bound store delete, s3 operation timeout --- crates/twigpine-node/src/blockstore/fs.rs | 73 ++++++++++++++--------- crates/twigpine-node/src/blockstore/s3.rs | 14 ++++- crates/twigpine-node/src/models/sweep.rs | 17 +++++- 3 files changed, 72 insertions(+), 32 deletions(-) diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 5ba08827..6890a652 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -38,24 +38,14 @@ pub struct FsBlockStore { 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 dir in tmp.ancestors() { + let Some(parent) = dir.parent() else { break }; + fsync_dir_blocking(parent)?; } Ok(Self { root }) } @@ -142,11 +132,21 @@ 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; @@ -179,8 +179,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 +211,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 +265,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()), diff --git a/crates/twigpine-node/src/blockstore/s3.rs b/crates/twigpine-node/src/blockstore/s3.rs index 8c2c7c0c..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(), }) } diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index ca16a9a4..638fbee2 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -12,6 +12,10 @@ use crate::state::AppState; /// 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, @@ -62,13 +66,20 @@ pub async fn sweep_once(state: &AppState) -> Result { tx.commit().await?; continue; }; - match store.delete(&id).await { - Ok(()) | Err(crate::blockstore::BlockStoreError::NotFound) => {} - Err(e) => { + // 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?; From 51d47a8e04d8e14f750e2f6dc08da47a7371ce78 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:32:04 -0600 Subject: [PATCH 43/53] fix(node): sweep session links by state, grace recheck on delete, session repo index, interrupted chunk reads, extension detection --- .github/workflows/pr-checks.yml | 2 +- crates/twigpine-core/src/model/chunking.rs | 50 +++++++++++++- crates/twigpine-core/src/model/manifest.rs | 15 ++++- crates/twigpine-node/src/db/mod.rs | 9 +++ crates/twigpine-node/src/db/model_queries.rs | 70 ++++++++++++++++---- crates/twigpine-node/src/models/sweep.rs | 4 +- 6 files changed, 133 insertions(+), 17 deletions(-) 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-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-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 942308fa..f2006cf6 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2846,6 +2846,15 @@ const MIGRATIONS: &[Migration] = &[ "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)", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index b6a50103..c8abe4ef 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -731,11 +731,17 @@ impl Db { .await?) } - pub async fn model_drop_sessions_blocks(&self, session_ids: &[String]) -> Result<()> { - sqlx::query("DELETE FROM model_session_blocks WHERE session_id = ANY($1)") - .bind(session_ids) - .execute(&self.pool) - .await?; + /// 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(()) } @@ -796,6 +802,7 @@ impl Db { &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 @@ -810,8 +817,13 @@ impl Db { 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 NOT EXISTS ( + "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 @@ -819,9 +831,11 @@ impl Db { AND NOT EXISTS ( SELECT 1 FROM model_session_blocks sb JOIN model_upload_sessions s ON s.id = sb.session_id - WHERE sb.block_sha256 = $1 AND s.state = 'open')", + 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?) } @@ -939,9 +953,7 @@ mod tests { db.model_expire_sessions().await.unwrap(), vec![s.id.clone()] ); - db.model_drop_sessions_blocks(std::slice::from_ref(&s.id)) - .await - .unwrap(); + 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); @@ -956,11 +968,42 @@ mod tests { vec![sha.clone()] ); let mut tx = db.model_begin().await.unwrap(); - assert!(db.model_tx_block_still_dead(&mut tx, &sha).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; @@ -1240,7 +1283,10 @@ mod tests { assert_eq!(db.model_remark_liveness().await.unwrap(), 0); assert!(db.model_stale_blocks(-1, 10).await.unwrap().is_empty()); let mut tx = db.model_begin().await.unwrap(); - assert!(!db.model_tx_block_still_dead(&mut tx, &sha).await.unwrap()); + assert!(!db + .model_tx_block_still_dead(&mut tx, &sha, 3600) + .await + .unwrap()); tx.commit().await.unwrap(); } } diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index 638fbee2..360c68c5 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -32,7 +32,7 @@ pub async fn sweep_once(state: &AppState) -> Result { // session no longer confers liveness. let expired = db.model_expire_sessions().await?; stats.sessions_expired = expired.len() as u64; - db.model_drop_sessions_blocks(&expired).await?; + 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). @@ -58,7 +58,7 @@ pub async fn sweep_once(state: &AppState) -> Result { // held across the store delete so a racing claim blocks rather than // wins a reference to an object we just removed. let mut tx = db.model_begin().await?; - if !db.model_tx_block_still_dead(&mut tx, &sha).await? { + if !db.model_tx_block_still_dead(&mut tx, &sha, grace).await? { tx.commit().await?; continue; } From b42250149c39710f234495103cb8035d443e64dc Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:32:04 -0600 Subject: [PATCH 44/53] docs(node): model routes gated on hosting and store, s3 lifecycle note --- docs/RUN-A-NODE.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) 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). From 02a89fd9730ae87f4ea9c73b2d9d739749ac5606 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:19:50 -0600 Subject: [PATCH 45/53] fix(cli): sync released paths in the real index back to HEAD after commit --- crates/twigpine-cli/src/model.rs | 169 +++++++++++++++++++++++++++---- 1 file changed, 151 insertions(+), 18 deletions(-) diff --git a/crates/twigpine-cli/src/model.rs b/crates/twigpine-cli/src/model.rs index f4fb31a1..2db52e96 100644 --- a/crates/twigpine-cli/src/model.rs +++ b/crates/twigpine-cli/src/model.rs @@ -228,11 +228,8 @@ fn detect_remote(root: &Path) -> Result<(String, String, String)> { // 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(); + 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 { @@ -536,6 +533,39 @@ fn read_head(path: &Path, n: u64) -> Result> { 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. @@ -1044,6 +1074,18 @@ async fn cmd_publish(args: PublishArgs) -> Result<()> { 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() @@ -1408,7 +1450,8 @@ mod tests { 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"); + 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"] @@ -1441,6 +1484,33 @@ mod tests { ); } + 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(); @@ -1448,30 +1518,85 @@ mod tests { tgit(dir.path(), &["add", "a.txt"]); tgit( dir.path(), - &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init"], + &[ + "-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("tmp-index"); + 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(); - git_index( - dir.path(), - &index, - &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "rel"], - ) - .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}"); - let staged_files = tgit( + 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(), - &["diff", "--cached", "--name-only", "--diff-filter=A"], + &[ + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "commit", + "-qm", + "init", + ], ); - assert_eq!(staged_files, "unrelated.bin"); + 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] @@ -1482,7 +1607,15 @@ mod tests { tgit(dir.path(), &["add", "gone.txt", "kept.txt"]); tgit( dir.path(), - &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init"], + &[ + "-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(); From 7ddab0a35b8eb98b8642384f878f80babb6d8c31 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:19:52 -0600 Subject: [PATCH 46/53] fix(node): map a relative blockstore root's top parent to the current directory --- crates/twigpine-node/src/blockstore/fs.rs | 46 +++++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/blockstore/fs.rs b/crates/twigpine-node/src/blockstore/fs.rs index 6890a652..dc0f95cd 100644 --- a/crates/twigpine-node/src/blockstore/fs.rs +++ b/crates/twigpine-node/src/blockstore/fs.rs @@ -35,6 +35,22 @@ 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"); @@ -43,9 +59,8 @@ impl FsBlockStore { // 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 dir in tmp.ancestors() { - let Some(parent) = dir.parent() else { break }; - fsync_dir_blocking(parent)?; + for parent in ancestor_parents(&tmp) { + fsync_dir_blocking(&parent)?; } Ok(Self { root }) } @@ -315,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(); From 7eb976a3183d8b6b363c88f17de7daec67e0910e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:57:55 -0600 Subject: [PATCH 47/53] fix(node): read committed paths with ls-tree -z so non-ASCII names verify --- crates/twigpine-node/src/models/verify.rs | 152 +++++++++++++++++++++- 1 file changed, 149 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index 02fe4a77..ea019937 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -130,7 +130,7 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App let tree = crate::git::store::run_git_bounded( &state.git_bin, &disk_path, - &["ls-tree", "-r", "--name-only", &release.commit_sha], + &["ls-tree", "-rz", "--name-only", &release.commit_sha], b"", std::time::Duration::from_secs(30), "git ls-tree", @@ -143,9 +143,11 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App .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) - .lines() - .filter(|p| !p.starts_with(".twigpine/")) + .split('\0') + .filter(|p| !p.is_empty() && !p.starts_with(".twigpine/")) { if !manifest_git_paths.contains(path) { return reject_release( @@ -659,4 +661,148 @@ mod tests { .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}"); + } } From ac93b895bd8558de11ff4c89d54387d5884c8ceb Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:44:56 -0600 Subject: [PATCH 48/53] style: cargo fmt --- crates/twigpine-node/src/config.rs | 16 +++++++++------- crates/twigpine-node/src/db/model_queries.rs | 10 +++++----- crates/twigpine-node/src/models/claim.rs | 5 +---- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 16bc8418..d36d63dd 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -1220,8 +1220,14 @@ impl Config { // 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), + ( + "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 { @@ -1729,11 +1735,7 @@ mod tests { "--model-node-quota-bytes", "--model-max-session-bytes", ] { - let mut over = Config::parse_from([ - "twigpine-node", - flag, - "9223372036854775808", - ]); + let mut over = Config::parse_from(["twigpine-node", flag, "9223372036854775808"]); assert!(over.validate().is_err(), "{flag} above i64::MAX"); } } diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index c8abe4ef..8164823e 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -280,10 +280,7 @@ impl Db { Ok(refund) } - pub async fn model_release_by_digest( - &self, - digest: &str, - ) -> Result> { + 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" )) @@ -968,7 +965,10 @@ mod tests { vec![sha.clone()] ); let mut tx = db.model_begin().await.unwrap(); - assert!(db.model_tx_block_still_dead(&mut tx, &sha, 3600).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(); } diff --git a/crates/twigpine-node/src/models/claim.rs b/crates/twigpine-node/src/models/claim.rs index 2fe6ec11..d1e48f50 100644 --- a/crates/twigpine-node/src/models/claim.rs +++ b/crates/twigpine-node/src/models/claim.rs @@ -152,10 +152,7 @@ pub async fn claim_release( // 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? - { + if let Some(existing) = db.model_release_by_digest(&material.request_digest).await? { return Ok(existing); } From aaa000af719dad509ecadf8a66d1f5f02886a37a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:53:00 -0600 Subject: [PATCH 49/53] fix(node): upload bookkeeping survives a dropped request and never deletes a shared block --- crates/twigpine-node/src/api/models.rs | 136 ++++++++++++------- crates/twigpine-node/src/db/model_queries.rs | 13 ++ crates/twigpine-node/src/test_harness.rs | 105 ++++++++++++-- crates/twigpine-node/tests/models_api.rs | 98 ++++++++++++- 4 files changed, 292 insertions(+), 60 deletions(-) diff --git a/crates/twigpine-node/src/api/models.rs b/crates/twigpine-node/src/api/models.rs index 58952b7f..01766919 100644 --- a/crates/twigpine-node/src/api/models.rs +++ b/crates/twigpine-node/src/api/models.rs @@ -14,7 +14,7 @@ use serde_json::json; use crate::api::{authorize_repo_read, require_repo_owner}; use crate::auth::{AuthenticatedDid, SignatureMaterial}; -use crate::blockstore::{BlockId, BlockStoreError}; +use crate::blockstore::{BlockId, BlockStoreError, PutOutcome}; use crate::db::{RepoRecord, VisibilityRule}; use crate::error::{AppError, Result}; use crate::models; @@ -198,58 +198,96 @@ pub async fn put_model_block( .into_body() .into_data_stream() .map(|r| r.map_err(|e| std::io::Error::other(e.to_string()))); - if let Err(e) = store - .put_verified(&block_id, Box::pin(stream), models::MAX_BLOCK_BYTES) - .await - { - let _ = db.model_refund_bytes(&session.id, declared as i64).await; - return Err(match e { - BlockStoreError::DigestMismatch => { - AppError::BadRequest(format!("block body does not hash to the named id {sha}")) + // 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}")) + } + }); } - BlockStoreError::TooLarge(cap) => { - AppError::BadRequest(format!("block exceeds the {cap}-byte limit")) + }; + // 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!(), + }); } - 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}")) + }; + 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()) } - other => AppError::Internal(anyhow::anyhow!("block store write failed: {other}")), - }); - } - // Stored and AlreadyPresent both leave the bytes stored. - - // Past this point the object exists; a bookkeeping failure must refund - // the admission or the session's charge leaks until it expires, and - // must delete the store object or the sweep can never find it (its - // candidate list is model_blocks rows). - let size = match store.size(&block_id).await { - Ok(Some(s)) => s, - r => { - let _ = db.model_refund_bytes(&session.id, declared as i64).await; - let _ = store.delete(&block_id).await; - return Err(match r { - Ok(None) => AppError::Internal(anyhow::anyhow!( - "block {sha} absent immediately after write" - )), - Err(e) => AppError::Internal(anyhow::anyhow!("block size lookup failed: {e}")), - Ok(Some(_)) => unreachable!(), - }); } - }; - let duplicate = match db - .model_record_block(&session.id, &sha, size, declared as i64) - .await - { - Ok(d) => d, - Err(e) => { - let _ = db.model_refund_bytes(&session.id, declared as i64).await; - let _ = store.delete(&block_id).await; - return Err(e.into()); - } - }; + }); + 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), diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 8164823e..96523270 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -280,6 +280,19 @@ impl Db { 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" diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index 9032eca0..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); @@ -180,11 +185,7 @@ fn build_state(db: Arc, pool: PgPool, repos_dir: PathBuf) -> AppS // temp dir mounts the model routes so the deny sweep can drive their // gates for real. Writes land inside the node's per-test repos dir and // are removed with it. - let block_dir = repos_dir.join("model-blocks"); - std::fs::create_dir_all(&block_dir).expect("create temp block dir"); - let block_store: Option> = Some(Arc::new( - crate::blockstore::fs::FsBlockStore::new(block_dir).expect("fs block store"), - )); + let block_store: Option> = Some(block_store); AppState { config: Arc::new(Config::parse_from(["twigpine-node"])), db, @@ -247,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(); diff --git a/crates/twigpine-node/tests/models_api.rs b/crates/twigpine-node/tests/models_api.rs index 3f2cedca..f67cc3e6 100644 --- a/crates/twigpine-node/tests/models_api.rs +++ b/crates/twigpine-node/tests/models_api.rs @@ -15,7 +15,8 @@ use support::signing::signed_request; use twigpine_core::cid::sha256_hex; use twigpine_core::http_sig::sign_request; use twigpine_core::identity::Keypair; -use twigpine_node::test_harness::{spawn_node, TestNode}; +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") @@ -545,6 +546,101 @@ async fn put_block_happy_path_duplicate_and_digest_mismatch(pool: sqlx::PgPool) 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 From e0ffc6286d78fe6a7af979bf3c0896682cf32239 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:04:02 -0600 Subject: [PATCH 50/53] fix(node): charge blocks to their payer and reconcile quota on release rejection and repo deletion --- crates/twigpine-node/src/db/mod.rs | 32 +++ crates/twigpine-node/src/db/model_queries.rs | 238 +++++++++++++++++-- 2 files changed, 256 insertions(+), 14 deletions(-) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index f2006cf6..541c19df 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2855,6 +2855,18 @@ const MIGRATIONS: &[Migration] = &[ "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 ────────────────────────────────────────────── @@ -4012,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) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 96523270..0dae0d24 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -604,6 +604,23 @@ impl Db { 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", @@ -681,40 +698,75 @@ impl Db { .bind(reason) .fetch_optional(&mut *tx) .await?; - let Some((publisher,)) = released else { + 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 freed: i64 = sqlx::query_scalar::<_, Option>( - "SELECT COALESCE(SUM(b.size), 0)::bigint FROM model_blocks b + 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 r ON r.id = r2.release_id + JOIN model_releases r2r ON r2r.id = r2.release_id WHERE r2.block_sha256 = b.sha256 AND r2.release_id <> $1 - AND r.state IN ('verifying', 'published'))", + AND r2r.state IN ('verifying', 'published')) + GROUP BY COALESCE(b.payer_did, r.publisher_did)", ) .bind(release_id) - .fetch_one(&mut *tx) - .await? - .unwrap_or(0); + .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) + .execute(&mut **tx) .await?; - if freed > 0 { + for (payer, bytes) in per_payer { sqlx::query( "UPDATE model_quota_usage SET bytes_used = GREATEST(bytes_used - $2, 0) WHERE did = $1", ) - .bind(&publisher) - .bind(freed) - .execute(&mut *tx) + .bind(&payer) + .bind(bytes) + .execute(&mut **tx) .await?; } - tx.commit().await?; Ok(()) } @@ -1302,4 +1354,162 @@ mod tests { .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", &[sha.clone()]).await; + let rb = claim_as(&db, "did:b", "cb", "r1", &[sha.clone()]).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", &[sha.clone()]).await; + let rb = claim_as(&db, "did:b", "cb", "r1", &[sha.clone()]).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", &[sha.clone()]).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", &[sha.clone()]).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); + } } From 69c3e6a88ba23597140ea42621ece770253aa773 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:31:13 -0600 Subject: [PATCH 51/53] fix(node): publish only while the repo is still fully public and drop the ref only for a rejected release --- crates/twigpine-node/src/db/model_queries.rs | 137 +++++++++++++++++++ crates/twigpine-node/src/models/verify.rs | 52 +++++-- 2 files changed, 175 insertions(+), 14 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index 0dae0d24..b29d61b5 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -93,6 +93,19 @@ impl From for ModelRelease { } } +/// 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"; @@ -676,6 +689,56 @@ impl Db { 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<()> { @@ -1512,4 +1575,78 @@ mod tests { 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/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index ea019937..a0901724 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -311,24 +311,48 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App // Publish: hidden ref first, then the state flip, so a crash leaves a // verifying row the worker retries rather than a dangling ref. write_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await?; - if !state.db.model_mark_published(release_id).await? { - // The stale-verify sweep rejected the row while this pass ran: - // drop the ref just written so it does not advertise a rejected - // commit. - let ref_name = format!("refs/gitlawb/releases/{}", release.commit_sha); - let _ = crate::git::store::run_git_bounded( - &state.git_bin, - &disk_path, - &["update-ref", "-d", &ref_name], - b"", - std::time::Duration::from_secs(30), - "git update-ref", - ) - .await; + 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?; + remove_release_ref(&state.git_bin, &disk_path, &release.commit_sha).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 From dccec6dc55912b09bd4bdf48d8f543a7129aa7b3 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:11:05 -0600 Subject: [PATCH 52/53] style: satisfy clippy in the payer ledger tests --- crates/twigpine-node/src/db/model_queries.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/db/model_queries.rs b/crates/twigpine-node/src/db/model_queries.rs index b29d61b5..11b1e94c 100644 --- a/crates/twigpine-node/src/db/model_queries.rs +++ b/crates/twigpine-node/src/db/model_queries.rs @@ -1470,8 +1470,8 @@ mod tests { .await .unwrap(); // A claims the block (pays 100); B's later claim is free. - let ra = claim_as(&db, "did:a", "ca", "r1", &[sha.clone()]).await; - let rb = claim_as(&db, "did:b", "cb", "r1", &[sha.clone()]).await; + 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); @@ -1505,8 +1505,8 @@ mod tests { .execute(&pool) .await .unwrap(); - let ra = claim_as(&db, "did:a", "ca", "r1", &[sha.clone()]).await; - let rb = claim_as(&db, "did:b", "cb", "r1", &[sha.clone()]).await; + 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); @@ -1540,13 +1540,13 @@ mod tests { .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", &[sha.clone()]).await; + 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", &[sha.clone()]).await; + 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 From 9c7432bb8d63b03198070f75e2e1931d612569eb Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:18:54 -0600 Subject: [PATCH 53/53] fix(node): remove a rejected release's hidden pin on every reject path --- crates/twigpine-node/src/models/sweep.rs | 3 +- crates/twigpine-node/src/models/verify.rs | 60 ++++++++++++++++++++++- 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/models/sweep.rs b/crates/twigpine-node/src/models/sweep.rs index 360c68c5..8337773e 100644 --- a/crates/twigpine-node/src/models/sweep.rs +++ b/crates/twigpine-node/src/models/sweep.rs @@ -37,8 +37,7 @@ pub async fn sweep_once(state: &AppState) -> Result { // A `verifying` row that outlived its window wedges the publisher's // one-verifying slot; reject it (which also frees the reservation). for id in db.model_stale_verifying(STALE_VERIFY_SECS).await? { - db.model_reject_release(id, "verification timed out") - .await?; + crate::models::verify::reject_release(state, id, "verification timed out").await?; } // Re-mark liveness both ways: blocks that lost every live reference get diff --git a/crates/twigpine-node/src/models/verify.rs b/crates/twigpine-node/src/models/verify.rs index a0901724..ef94330b 100644 --- a/crates/twigpine-node/src/models/verify.rs +++ b/crates/twigpine-node/src/models/verify.rs @@ -319,7 +319,6 @@ pub async fn verify_release(state: &AppState, release_id: i64) -> Result<(), App crate::db::model_queries::PublishOutcome::Published => {} crate::db::model_queries::PublishOutcome::NoLongerPublic => { reject_release(state, release_id, "repository is no longer fully public").await?; - remove_release_ref(&state.git_bin, &disk_path, &release.commit_sha).await; } crate::db::model_queries::PublishOutcome::NotVerifying => { // The row settled while this pass ran: a rejected release's ref @@ -450,6 +449,21 @@ pub async fn reject_release( ) -> 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(()) } @@ -829,4 +843,48 @@ mod tests { ); 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" + ); + } }