aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#351 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/d91bae27e1ff2119.bundle -o d91bae27e1ff2119.bundle git fetch d91bae27e1ff2119.bundle refs/pull/351/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
351
111bbad676aa28fbb5bfc7dff0b91d88e0377bf7
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":351,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/351","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:54Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 3888964a..611f5aa4 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:285ca7eafbe46d808ebe5e4fb533e464bfdf0fedaf3eef486ac2e2c8826baf6f", - "compiled_at": "2026-10-08T19:33:05Z", + "compiled_at": "2026-10-08T20:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:b2e77d9577057a43570b304d3c75c36e12e91f38ab76fbbf97b87fa5a5a96309", + "digest": "sha256:196df91c4dffb0c6a9b222fe2c3c3ee5e865b138d3d02a1c325fd1f4f8aaa28a", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", "files": 1614, - "generated_at_commit": "2285c3fde7a8fcd7a29f7806b74dccaa9c54b98f", - "source_tree": "sha256:c74bb8a193cbaf631ea4fd95214bffb37e9fc4c4ca9a1c56d92de1fa4feae86b" + "generated_at_commit": "041c1c55c687e4f9a7356b430e4999407155d12f", + "source_tree": "sha256:2e9f957f3001cefcfcd094c246ff1325579e647787070b73d5c7caf0a2537d39" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 0a61190e..ccc4baae 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "804855137b5e132ba9042140b09c6245ef2b4d80daca6df80b1a379c46b44ea4", - "last_commit": "bbd3f91", + "digest": "7567abda48e58459b6d772bf39b5673e562c8f682b6302aed9969890963f983a", + "last_commit": "3b08e67", "name": "src", "purpose": "" } ], - "children_root": "sha256:ef6f15538546cd814625d4700947b75d96e62670ee1d0c79a943d7045f77b3f8", - "compiled_at": "2026-10-08T19:20:34Z", + "children_root": "sha256:8b5adc18c6c32950b20593baff81821dc21dfe55e4f4779cdd586506f9d872ae", + "compiled_at": "2026-10-08T20:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:c9ff168e1db6ead04f3c865c37c39fa3eede7bd2c93462610fa5f384222fcbd2", + "digest": "sha256:79f8da26bb1b1013faa66a3f74d015cd8a7366a181f36f79ac0ba9d603b136eb", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 34, - "generated_at_commit": "5785cbeed29084095880b8f6b8563c359d6922aa", - "source_tree": "sha256:85a71ccc5581f2d4ac89c1ca018bd199899bd09cd5f4003ad5426b7f36a06320" + "generated_at_commit": "041c1c55c687e4f9a7356b430e4999407155d12f", + "source_tree": "sha256:ae881ec12d7dcc2557dacf88f51cad9992dae61ae73046c94d87b2cdd6c8a9c2" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index a2ee2276..64c3d744 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T19:20:34Z", + "compiled_at": "2026-10-08T20:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:804855137b5e132ba9042140b09c6245ef2b4d80daca6df80b1a379c46b44ea4", + "digest": "sha256:7567abda48e58459b6d772bf39b5673e562c8f682b6302aed9969890963f983a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 26, - "generated_at_commit": "5785cbeed29084095880b8f6b8563c359d6922aa", - "source_tree": "sha256:b06fa9c9ed0aeeaf6d8c4d076451519bca60c49ab93bddcb066418870e700c50" + "generated_at_commit": "041c1c55c687e4f9a7356b430e4999407155d12f", + "source_tree": "sha256:d9e19feccb9c847221ee79f7727e0fa2c519f11c9919a9e76c3fae007b7c8e04" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index ba4f05d7..a611d325 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -930,8 +930,12 @@ struct DaemonModelManifest { tokenizer_path: Option<std::path::PathBuf>, /// Why no checkpoint file was resolved (None when one was found). fallback_reason: Option<String>, - /// Hex SHA-256 of the loaded model file (set only when its weights loaded). + /// Hex SHA-256 of what was loaded (set only when its weights loaded): the file's own + /// digest for a single file, the manifest digest over the index and every shard for a + /// sharded checkpoint (see [`checkpoint_digest`]). model_sha256: Option<String>, + /// Which form `model_sha256` has: `file` or `index+shards` (set with it). + model_digest_kind: Option<&'static str>, /// Hex SHA-256 of the loaded tokenizer file (set only when it parsed). tokenizer_sha256: Option<String>, } @@ -1027,6 +1031,7 @@ fn checkpoint_manifest( checkpoint_path: Some(path), fallback_reason: None, model_sha256: None, + model_digest_kind: None, tokenizer_sha256: None, } } @@ -1100,6 +1105,7 @@ fn resolve_daemon_manifest_with(policy: &CheckpointPolicy) -> DaemonModelManifes searched )), model_sha256: None, + model_digest_kind: None, tokenizer_sha256: None, } } @@ -1137,6 +1143,9 @@ struct DaemonModel { weights: aien_inference_abi::TransformerWeights, tokenizer: Option<aien_inference_abi::ChatTokenizer>, label: String, + /// The `CHECKPOINT_SHARDS` line for a sharded checkpoint (logged after the + /// "checkpoint loaded" line, which keeps its pinned form); None otherwise. + shards_line: Option<String>, #[allow(dead_code)] // read by tests now and by the PREFILL-E2E receipt (Cut 8) reference_weights: bool, } @@ -1159,6 +1168,7 @@ fn model_identity( }; Some(aien_runtime::generation::ModelIdentity { model_sha256: manifest.model_sha256.clone()?, + model_digest_kind: manifest.model_digest_kind?.to_string(), model_path: path_text(manifest.checkpoint_path.as_deref()?), tokenizer_sha256: manifest.tokenizer_sha256.clone()?, tokenizer_path: path_text(manifest.tokenizer_path.as_deref()?), @@ -1182,6 +1192,83 @@ fn sha256_file_hex(path: &std::path::Path) -> std::io::Result<String> { Ok(hex::encode(hasher.finalize())) } +/// The digest of a checkpoint's weight bytes (sc#338), over exactly the files the +/// loader reads ([`aien_inference_abi::checkpoint_files`]). +struct CheckpointDigest { + /// A single file: its own sha256. A sharded checkpoint: the sha256 of the + /// manifest text `aien-checkpoint-digest v1\nindex <index sha256>\n` followed by + /// one `<shard sha256> <shard name>\n` line per shard, sorted by name (the + /// shard lines are `sha256sum` lines). + sha256: String, + /// `file` or `index+shards`. + kind: &'static str, + /// The index's own sha256 (sharded only). + index_sha256: Option<String>, + /// `(shard name, shard sha256)` in name order (sharded only). + shards: Vec<(String, String)>, +} + +/// Errors name the file only when it is not `path` itself (the caller names `path`). +/// A directory is refused, as it was when `path` itself was hashed. +fn checkpoint_digest(path: &std::path::Path) -> Result<CheckpointDigest, String> { + if path.is_dir() { + return Err("is a directory, not a safetensors file or shard index".to_string()); + } + let files = aien_inference_abi::checkpoint_files(path).map_err(|e| e.to_string())?; + let sha = |p: &std::path::Path| { + sha256_file_hex(p).map_err(|e| { + if p == path { + e.to_string() + } else { + format!("{}: {}", p.display(), e) + } + }) + }; + let Some(index) = files.index else { + let Some((_, file)) = files.weights.first() else { + return Err("names no weight file".to_string()); + }; + return Ok(CheckpointDigest { + sha256: sha(file)?, + kind: "file", + index_sha256: None, + shards: Vec::new(), + }); + }; + if files.weights.is_empty() { + return Err("its shard index names no shard".to_string()); + } + use sha2::{Digest, Sha256}; + let index_sha256 = sha(&index)?; + let mut manifest = format!("aien-checkpoint-digest v1\nindex {index_sha256}\n"); + let mut shards = Vec::with_capacity(files.weights.len()); + for (name, file) in &files.weights { + let digest = sha(file)?; + manifest.push_str(&format!("{digest} {name}\n")); + shards.push((name.clone(), digest)); + } + Ok(CheckpointDigest { + sha256: hex::encode(Sha256::digest(manifest.as_bytes())), + kind: "index+shards", + index_sha256: Some(index_sha256), + shards, + }) +} + +/// The `CHECKPOINT_SHARDS` log line (sc#338): every shard's sha256 and the index's, +/// so a run's log ties `model_sha256` to the shard bytes. None for a single file. +fn checkpoint_shards_line(d: &CheckpointDigest) -> Option<String> { + let index = d.index_sha256.as_deref()?; + let shards: Vec<String> = d.shards.iter().map(|(n, s)| format!("{n}:{s}")).collect(); + Some(format!( + "CHECKPOINT_SHARDS model_sha256={} model_digest_kind={} index_sha256={} shards=[{}]", + d.sha256, + d.kind, + index, + shards.join(",") + )) +} + /// The single decision point for every checkpoint fallback. Under /// AIEN_REQUIRE_CHECKPOINT=1 it refuses with an error naming the reason (which names /// the path); otherwise it prints exactly one warn-level line and lets the caller degrade. @@ -1213,6 +1300,7 @@ fn reference_fallback( ), weights: aien_inference_abi::TransformerWeights::reference_test_weights(&config), tokenizer: None, + shards_line: None, reference_weights: true, manifest, }) @@ -1250,7 +1338,7 @@ fn load_daemon_model_with( .unwrap_or_else(|| "no checkpoint resolved".to_string()); return reference_fallback(manifest, require_checkpoint, reason); }; - let model_sha256 = match sha256_file_hex(&path) { + let digest = match checkpoint_digest(&path) { Ok(digest) => digest, Err(error) => { let reason = format!("checkpoint {} is unreadable: {}", path.display(), error); @@ -1319,7 +1407,8 @@ fn load_daemon_model_with( return reference_fallback(manifest, require_checkpoint, reason); } }; - manifest.model_sha256 = Some(model_sha256); + manifest.model_sha256 = Some(digest.sha256.clone()); + manifest.model_digest_kind = Some(digest.kind); let mut tokenizer = None; match manifest.tokenizer_path.clone() { @@ -1377,6 +1466,7 @@ fn load_daemon_model_with( weights, tokenizer, label, + shards_line: checkpoint_shards_line(&digest), reference_weights: false, }) } @@ -1431,6 +1521,7 @@ fn build_native_daemon_backend() -> Result<DaemonBackendParts, String> { tokenizer, label: model_label, manifest, + shards_line, .. } = { let open_session = || { @@ -1451,6 +1542,9 @@ fn build_native_daemon_backend() -> Result<DaemonBackendParts, String> { }; load_daemon_model_with(manifest, policy.require_checkpoint, Some(&resident))? }; + if let Some(line) = &shards_line { + println!(" {line}"); + } let identity = model_identity(&manifest, tokenizer.is_some()); // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). The env names // AIEN_REQUIRE_BLACKWELL (the GB10 chip, campaign spec) and AIEN_GPU_BACKEND=omega both @@ -2340,6 +2434,7 @@ mod tests { tokenizer_path: Some("/nonexistent/tokenizer.json".into()), fallback_reason: None, model_sha256: Some("aa".into()), + model_digest_kind: Some("index+shards"), tokenizer_sha256: Some("bb".into()), }; let id = model_identity(&loaded, true).expect("identity"); @@ -2348,11 +2443,13 @@ mod tests { ("aa", "bb") ); assert_eq!(id.model_path, "/nonexistent/model.safetensors"); + assert_eq!(id.model_digest_kind, "index+shards"); // No parsed tokenizer, no weights digest, or no tokenizer digest: no identity. assert!(model_identity(&loaded, false).is_none()); for strip in [0, 1] { let mut m = DaemonModelManifest { model_sha256: loaded.model_sha256.clone(), + model_digest_kind: loaded.model_digest_kind, tokenizer_sha256: loaded.tokenizer_sha256.clone(), checkpoint_path: loaded.checkpoint_path.clone(), tokenizer_path: loaded.tokenizer_path.clone(), @@ -2650,6 +2747,177 @@ mod tests { ); } + /// Copies the tiny Qwen3 fixture into `dir` as two shards plus a + /// `model.safetensors.index.json` (tensors split by sorted name, half each). + fn write_two_shard_qwen3_tiny(dir: &std::path::Path) -> std::path::PathBuf { + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../aien-inference-abi/fixtures/qwen3-tiny"); + std::fs::copy(fixture.join("config.json"), dir.join("config.json")).unwrap(); + let bytes = std::fs::read(fixture.join("model.safetensors")).unwrap(); + let header_len = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize; + let header: serde_json::Map<String, serde_json::Value> = + serde_json::from_slice(&bytes[8..8 + header_len]).unwrap(); + let data = &bytes[8 + header_len..]; + let mut names: Vec<&String> = header.keys().filter(|k| *k != "__metadata__").collect(); + names.sort(); + let (first, second) = names.split_at(names.len() / 2); + let mut weight_map = serde_json::Map::new(); + for (file, part) in [ + ("model-00001-of-00002.safetensors", first), + ("model-00002-of-00002.safetensors", second), + ] { + let mut shard_header = serde_json::Map::new(); + let mut payload = Vec::new(); + for name in part { + let mut info = header[*name].clone(); + let offsets = info["data_offsets"].as_array().unwrap(); + let (a, b) = ( + offsets[0].as_u64().unwrap() as usize, + offsets[1].as_u64().unwrap() as usize, + ); + let start = payload.len(); + payload.extend_from_slice(&data[a..b]); + info["data_offsets"] = serde_json::json!([start, payload.len()]); + shard_header.insert((*name).clone(), info); + weight_map.insert((*name).clone(), serde_json::json!(file)); + } + let text = serde_json::Value::Object(shard_header).to_string(); + let mut out = (text.len() as u64).to_le_bytes().to_vec(); + out.extend_from_slice(text.as_bytes()); + out.extend_from_slice(&payload); + std::fs::write(dir.join(file), out).unwrap(); + } + let index = dir.join("model.safetensors.index.json"); + std::fs::write( + &index, + serde_json::json!({"metadata": {}, "weight_map": weight_map}).to_string(), + ) + .unwrap(); + index + } + + fn file_sha(path: &std::path::Path) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(std::fs::read(path).unwrap())) + } + + /// sc#338: a sharded checkpoint's `model_sha256` binds the index AND every + /// shard it names (the documented manifest form), not the index alone; a + /// changed shard under the same index changes it. + #[test] + fn a_sharded_checkpoint_digest_binds_every_shard() { + use sha2::{Digest, Sha256}; + let dir = tempfile::tempdir().unwrap(); + let index = write_two_shard_qwen3_tiny(dir.path()); + let load = || { + let policy = CheckpointPolicy { + model_path: Some(index.clone()), + ..CheckpointPolicy::default() + }; + let model = load_daemon_model(resolve_daemon_manifest_with(&policy), false) + .expect("the two-shard fixture loads"); + assert!(!model.reference_weights, "{}", model.label); + model + }; + let model = load(); + assert_eq!(model.manifest.model_digest_kind, Some("index+shards")); + let shard = |n| { + dir.path() + .join(format!("model-0000{n}-of-00002.safetensors")) + }; + let expected = hex::encode(Sha256::digest(format!( + "aien-checkpoint-digest v1\nindex {}\n{} model-00001-of-00002.safetensors\n{} model-00002-of-00002.safetensors\n", + file_sha(&index), + file_sha(&shard(1)), + file_sha(&shard(2)), + ))); + let digest = model.manifest.model_sha256.clone().unwrap(); + assert_eq!(digest, expected); + assert_ne!(digest, file_sha(&index), "not the index alone"); + let line = model + .shards_line + .clone() + .expect("a sharded load logs its shards"); + assert_eq!( + line, + format!( + "CHECKPOINT_SHARDS model_sha256={digest} model_digest_kind=index+shards index_sha256={} shards=[model-00001-of-00002.safetensors:{},model-00002-of-00002.safetensors:{}]", + file_sha(&index), + file_sha(&shard(1)), + file_sha(&shard(2)), + ) + ); + // The "checkpoint loaded" line keeps its pinned form and carries the new digest. + assert!( + model.label.contains(&format!("model_sha256={digest},")), + "{}", + model.label + ); + + // Change one weight byte in the second shard, same index: a new digest. + let mut bytes = std::fs::read(shard(2)).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0x01; + std::fs::write(shard(2), bytes).unwrap(); + let changed = load().manifest.model_sha256.unwrap(); + assert_ne!(changed, digest, "a changed shard must change the digest"); + } + + /// sc#338 review: the digest changes no refusal. A model directory as the + /// checkpoint path is still refused (as when the path itself was hashed), + /// and an index naming no shard is refused, with the path named once. + #[test] + fn a_directory_or_an_index_without_shards_is_still_refused() { + let dir = tempfile::tempdir().unwrap(); + write_two_shard_qwen3_tiny(dir.path()); + let err = load_daemon_model( + resolve_daemon_manifest_with(&strict_policy(Some(dir.path().to_path_buf()))), + true, + ) + .err() + .expect("a directory path is refused"); + assert!(err.contains("AIEN_REQUIRE_CHECKPOINT=1"), "{err}"); + assert!(err.contains("is a directory"), "{err}"); + + let empty = tempfile::tempdir().unwrap(); + let index = empty.path().join("model.safetensors.index.json"); + std::fs::write(&index, r#"{"weight_map":{}}"#).unwrap(); + let err = load_daemon_model( + resolve_daemon_manifest_with(&strict_policy(Some(index.clone()))), + true, + ) + .err() + .expect("an index without shards is refused"); + assert!(err.contains("names no shard"), "{err}"); + assert_eq!( + err.matches(&index.display().to_string()).count(), + 1, + "{err}" + ); + } + + /// sc#338: a single safetensors file keeps `model_sha256` = the file's own + /// sha256 (`model_digest_kind` = `file`) and logs no shard line. + #[test] + fn a_single_file_checkpoint_digest_is_the_file_sha256() { + let dir = tempfile::tempdir().unwrap(); + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../aien-inference-abi/fixtures/qwen3-tiny"); + for f in ["config.json", "model.safetensors"] { + std::fs::copy(fixture.join(f), dir.path().join(f)).unwrap(); + } + let path = dir.path().join("model.safetensors"); + let policy = CheckpointPolicy { + model_path: Some(path.clone()), + ..CheckpointPolicy::default() + }; + let model = load_daemon_model(resolve_daemon_manifest_with(&policy), false).unwrap(); + assert!(!model.reference_weights, "{}", model.label); + assert_eq!(model.manifest.model_digest_kind, Some("file")); + assert_eq!(model.manifest.model_sha256, Some(file_sha(&path))); + assert_eq!(model.shards_line, None); + } + /// Real-checkpoint proof. Ignored in plain `cargo test`; the forge runs it with /// `--include-ignored`, and then an unset AIEN_E2E_CHECKPOINT is a FAILURE, not a skip. #[test] diff --git a/crates/aien-inference-abi/src/checkpoint.rs b/crates/aien-inference-abi/src/checkpoint.rs index 8caf4c54..d9905e3b 100644 --- a/crates/aien-inference-abi/src/checkpoint.rs +++ b/crates/aien-inference-abi/src/checkpoint.rs @@ -519,19 +519,55 @@ pub const SAFETENSORS_INDEX: &str = "model.safetensors.index.json"; enum ResolvedFiles { /// One `.safetensors` file. Single(PathBuf), - /// The shard files named by a `model.safetensors.index.json`, sorted and de-duplicated. - Sharded(Vec<PathBuf>), + /// The `model.safetensors.index.json` and the shard files it names, as `(name in the + /// index, path)`, sorted by name and de-duplicated. + Sharded { + index: PathBuf, + shards: Vec<(String, PathBuf)>, + }, } impl ResolvedFiles { fn into_paths(self) -> Vec<PathBuf> { match self { Self::Single(p) => vec![p], - Self::Sharded(v) => v, + Self::Sharded { shards, .. } => shards.into_iter().map(|(_, p)| p).collect(), } } } +/// The files a checkpoint path names, exactly as the loaders read them (sc#338): what the +/// daemon digests so its record binds the weight bytes, not only the path it was given. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CheckpointFiles { + /// The `model.safetensors.index.json` read; None for a single file. + pub index: Option<PathBuf>, + /// Every weight file as `(name, path)`, sorted by name and de-duplicated: the name the + /// index's `weight_map` gives a shard, or the file name of a single file. + pub weights: Vec<(String, PathBuf)>, +} + +/// Resolves `path` like [`load_checkpoint_with_catalog`] and [`StreamedCheckpoint::open`] +/// do: a `.safetensors` file, a `model.safetensors.index.json`, a model directory holding +/// either, or a shard file whose directory has an index (the whole sharded set). +pub fn checkpoint_files<P: AsRef<Path>>(path: P) -> Result<CheckpointFiles, CheckpointError> { + Ok(match resolve_checkpoint_files(path.as_ref())? { + ResolvedFiles::Single(p) => CheckpointFiles { + index: None, + weights: vec![( + p.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + p, + )], + }, + ResolvedFiles::Sharded { index, shards } => CheckpointFiles { + index: Some(index), + weights: shards, + }, + }) +} + /// Decides which files `path` names: a `.safetensors` file, a `model.safetensors.index.json` /// (sharded), or a model directory holding either. A shard file whose directory has an index /// names the whole sharded set. @@ -567,10 +603,12 @@ fn resolve_checkpoint_files(p: &Path) -> Result<ResolvedFiles, CheckpointError> let mut files: Vec<&str> = weight_map.values().filter_map(|v| v.as_str()).collect(); files.sort_unstable(); files.dedup(); - let dir = index.parent().unwrap_or(Path::new(".")); - Ok(ResolvedFiles::Sharded( - files.into_iter().map(|file| dir.join(file)).collect(), - )) + let dir = index.parent().unwrap_or(Path::new(".")).to_path_buf(); + let shards = files + .into_iter() + .map(|file| (file.to_string(), dir.join(file))) + .collect(); + Ok(ResolvedFiles::Sharded { index, shards }) } /// Loads and validates a checkpoint against `catalog`. `path` is a `.safetensors` file, a @@ -593,7 +631,7 @@ pub fn load_checkpoint_with_catalog<P: AsRef<Path>>( ResolvedFiles::Single(file) => { return parse_safetensors_arc(Arc::from(read(&file)?), catalog); } - ResolvedFiles::Sharded(paths) => paths, + sharded => sharded.into_paths(), }; let mut total = 0usize; for shard in &paths { @@ -1030,4 +1068,39 @@ mod tests { _ => panic!("Expected InvalidHeader on arithmetic overflow"), } } + + /// sc#338: the files the loader reads, named for the daemon's digest: the index and + /// every shard it names (sorted, de-duplicated, by the index's name); a single file + /// has no index. + #[test] + fn checkpoint_files_names_the_index_and_every_shard() { + let dir = std::env::temp_dir().join(format!("aien-ckfiles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let index = dir.join(SAFETENSORS_INDEX); + std::fs::write( + &index, + r#"{"weight_map":{"x":"b.safetensors","y":"a.safetensors","z":"b.safetensors"}}"#, + ) + .unwrap(); + let files = checkpoint_files(&index).unwrap(); + assert_eq!(files.index.as_deref(), Some(index.as_path())); + assert_eq!( + files.weights, + vec![ + ("a.safetensors".to_string(), dir.join("a.safetensors")), + ("b.safetensors".to_string(), dir.join("b.safetensors")), + ] + ); + // A shard file beside an index names the whole set, like the loader. + std::fs::write(dir.join("a.safetensors"), b"").unwrap(); + assert_eq!(checkpoint_files(dir.join("a.safetensors")).unwrap(), files); + let single = dir.join("model.safetensors"); + let files = checkpoint_files(&single).unwrap(); + assert_eq!(files.index, None); + assert_eq!( + files.weights, + vec![("model.safetensors".to_string(), single.clone())] + ); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index 0c1be629..819ad448 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -1987,6 +1987,7 @@ mod tests { fn generation_row(id: u64) -> ComposeRecordView { let identity = crate::generation::ModelIdentity { model_sha256: "m".repeat(64), + model_digest_kind: "file".into(), model_path: "/models/m.safetensors".into(), tokenizer_sha256: "t".repeat(64), tokenizer_path: "/models/tokenizer.json".into(), diff --git a/crates/aien-runtime/src/generation.rs b/crates/aien-runtime/src/generation.rs index 2edcd5e9..50b9a639 100644 --- a/crates/aien-runtime/src/generation.rs +++ b/crates/aien-runtime/src/generation.rs @@ -14,12 +14,16 @@ use sha2::{Digest, Sha256}; /// Marker field (and refused `ComposeNote` kind) of the generation record. pub const GENERATION: &str = "generation"; -/// The model files the daemon loaded, hashed once at load time. -/// `model_sha256` is the sha256 of the single safetensors file's bytes -/// (streamed, 1 MiB chunks); `tokenizer_sha256` that of the tokenizer file. +/// The model files the daemon loaded, hashed once at load time (streamed, +/// 1 MiB chunks). `model_sha256` is the digest of what was loaded, in the form +/// `model_digest_kind` names: `file` (the single safetensors file's sha256) or +/// `index+shards` (sc#338: the manifest digest over the shard index and every +/// shard it names; docs/DAEMON_GENERATION_RECORD.md). `tokenizer_sha256` is the +/// tokenizer file's sha256. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ModelIdentity { pub model_sha256: String, + pub model_digest_kind: String, pub model_path: String, pub tokenizer_sha256: String, pub tokenizer_path: String, @@ -124,6 +128,7 @@ pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> GENERATION: 1, "v": 1, "model_sha256": id.model_sha256, + "model_digest_kind": id.model_digest_kind, "model_path": id.model_path, "tokenizer_sha256": id.tokenizer_sha256, "tokenizer_path": id.tokenizer_path, @@ -353,6 +358,7 @@ pub fn build_compose_record(id: &ModelIdentity, e: &ComposeEvidence, start: Daem "task": e.task, "attempt": e.attempt, "model_sha256": id.model_sha256, + "model_digest_kind": id.model_digest_kind, "model_path": id.model_path, "tokenizer_sha256": id.tokenizer_sha256, "tokenizer_path": id.tokenizer_path, diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 9785ca29..5db76578 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -1045,6 +1045,7 @@ mod generation_record_tests { fn identity() -> Arc<ModelIdentity> { Arc::new(ModelIdentity { model_sha256: "a".repeat(64), + model_digest_kind: "file".into(), model_path: "/m/model.safetensors".into(), tokenizer_sha256: "b".repeat(64), tokenizer_path: "/m/tokenizer.json".into(), diff --git a/crates/aien-runtime/tests/decoding_observed_test.rs b/crates/aien-runtime/tests/decoding_observed_test.rs index 95c07e22..01c2ba1d 100644 --- a/crates/aien-runtime/tests/decoding_observed_test.rs +++ b/crates/aien-runtime/tests/decoding_observed_test.rs @@ -156,6 +156,7 @@ async fn a_backend_without_the_observation_makes_no_claim() { fn record_field_matches_the_report_and_is_absent_without_one() { let id = aien_runtime::generation::ModelIdentity { model_sha256: "m".repeat(64), + model_digest_kind: "file".into(), model_path: "/m".into(), tokenizer_sha256: "t".repeat(64), tokenizer_path: "/t".into(), diff --git a/crates/aien-runtime/tests/generation_record_test.rs b/crates/aien-runtime/tests/generation_record_test.rs index 0090ed76..d993fcce 100644 --- a/crates/aien-runtime/tests/generation_record_test.rs +++ b/crates/aien-runtime/tests/generation_record_test.rs @@ -41,6 +41,7 @@ fn toy_tokenizer_with(mock_tokens: &str) -> ChatTokenizer { fn identity() -> ModelIdentity { ModelIdentity { model_sha256: "ab".repeat(32), + model_digest_kind: "index+shards".into(), model_path: "/models/toy/model.safetensors".into(), tokenizer_sha256: "cd".repeat(32), tokenizer_path: "/models/toy/tokenizer.json".into(), @@ -195,6 +196,7 @@ async fn record_carries_the_digests_of_the_turn() { assert_eq!(r["generation"], 1); assert_eq!(r["v"], 1); assert_eq!(r["model_sha256"], want.model_sha256); + assert_eq!(r["model_digest_kind"], want.model_digest_kind); assert_eq!(r["model_path"], want.model_path); assert_eq!(r["tokenizer_sha256"], want.tokenizer_sha256); assert_eq!(r["tokenizer_path"], want.tokenizer_path); diff --git a/crates/aien-runtime/tests/ops_evidence_test.rs b/crates/aien-runtime/tests/ops_evidence_test.rs index 08760bb9..656f5d72 100644 --- a/crates/aien-runtime/tests/ops_evidence_test.rs +++ b/crates/aien-runtime/tests/ops_evidence_test.rs @@ -232,6 +232,7 @@ async fn a_backend_without_op_accounting_makes_no_claim() { fn record_field_matches_the_evidence_and_is_absent_without_it() { let id = aien_runtime::generation::ModelIdentity { model_sha256: "m".repeat(64), + model_digest_kind: "file".into(), model_path: "/m".into(), tokenizer_sha256: "t".repeat(64), tokenizer_path: "/t".into(), diff --git a/crates/aien-runtime/tests/provenance_link_test.rs b/crates/aien-runtime/tests/provenance_link_test.rs index e7d7c29c..1a59a5e8 100644 --- a/crates/aien-runtime/tests/provenance_link_test.rs +++ b/crates/aien-runtime/tests/provenance_link_test.rs @@ -52,6 +52,7 @@ fn sha(b: &[u8]) -> String { fn identity() -> ModelIdentity { ModelIdentity { model_sha256: "ab".repeat(32), + model_digest_kind: "index+shards".into(), model_path: "/models/toy/model.safetensors".into(), tokenizer_sha256: "cd".repeat(32), tokenizer_path: "/models/toy/tokenizer.json".into(), @@ -290,6 +291,7 @@ async fn assert_linked(d: &Daemon, f: &Flow, want_agent: &str) { assert_eq!(g["generation"], 1); assert_eq!(g["origin"], "compose_proposal"); assert_eq!(g["model_sha256"], want.model_sha256); + assert_eq!(g["model_digest_kind"], want.model_digest_kind); assert_eq!(g["tokenizer_sha256"], want.tokenizer_sha256); assert_eq!(g["task"], f.report["task"]); assert_eq!(g["attempt"], 1); diff --git a/docs/DAEMON_GENERATION_RECORD.md b/docs/DAEMON_GENERATION_RECORD.md index bc95bfc1..f5b71f3c 100644 --- a/docs/DAEMON_GENERATION_RECORD.md +++ b/docs/DAEMON_GENERATION_RECORD.md @@ -6,11 +6,12 @@ have to take the run driver's word for "this text came from this model". ## What the daemon does -1. At start, after the model loads, the CLI holds the sha256 of the model file - (the single safetensors file, streamed in 1 MiB chunks, hashed once) and of - the tokenizer file, with the path each came from. The daemon passes both to - the server (`set_model_identity`). The same digests are in the - "checkpoint loaded" log line. +1. At start, after the model loads, the CLI holds the digest of the model + weights (below: `model_sha256`, files streamed in 1 MiB chunks, hashed once) + and the sha256 of the tokenizer file, with the path each came from. The + daemon passes both to the server (`set_model_identity`). The same digests are + in the "checkpoint loaded" log line; a sharded checkpoint also logs a + `CHECKPOINT_SHARDS` line (below). 2. When a `StreamTurn` finishes, and the compose ledger is open, the daemon appends one record to the ledger and returns its id in `TurnFinished.generation_record` (optional field; absent when there is no @@ -23,7 +24,8 @@ An `effect`-class host note whose JSON has the marker field `generation`: | field | meaning | |---|---| | `generation`, `v` | marker (1) and record version (1) | -| `model_sha256`, `model_path` | the loaded weights file's digest and canonical path | +| `model_sha256`, `model_path` | the digest of the loaded weights (form below) and the canonical path the daemon was given | +| `model_digest_kind` | which form `model_sha256` has: `file` or `index+shards` (below) | | `tokenizer_sha256`, `tokenizer_path` | the loaded tokenizer file's digest and path | | `prompt_ids_sha256` | `token_ids_sha256` of the submitted prompt token ids | | `output_token_ids_sha256` | same hash over the generated token ids | @@ -37,6 +39,47 @@ An `effect`-class host note whose JSON has the marker field `generation`: The envelope ids are chosen by the client. They are recorded, not trusted (names kept to match the envelope fields). +### `model_sha256`: the digest of what was loaded (sc#338) + +The daemon digests exactly the files the weights loader reads (the same +resolution: a `.safetensors` file, a `model.safetensors.index.json`, a model +directory holding either, or a shard file whose directory has an index, which +loads the whole sharded set). + +- `model_digest_kind` = `file`: one safetensors file. `model_sha256` is that + file's sha256 (`sha256sum model.safetensors`). +- `model_digest_kind` = `index+shards`: a sharded checkpoint. `model_sha256` is + the sha256 of this UTF-8 manifest text, with `\n` line ends and a final `\n`: + + ``` + aien-checkpoint-digest v1 + index <sha256 of model.safetensors.index.json> + <shard sha256> <shard name> + ... + ``` + + one shard line per file the index's `weight_map` names, de-duplicated and + sorted by name (byte order), the name exactly as the index writes it. The + shard lines are `sha256sum` lines, so a verifier can rebuild the manifest from + `sha256sum` output in the model directory and hash it. A changed shard, a + changed index, or a renamed shard changes `model_sha256`; the index alone does + not determine it. + The names are written raw: for a shard name holding a backslash or a line + break, `sha256sum` escapes the line (leading `\`), so rebuild that line by + hand. An index that names no shard is refused, and so is a directory given + as the checkpoint path (as it was before sc#338). + +The daemon also logs, on stdout after the "checkpoint loaded" line (which keeps +its pinned form, parsed by interplane#76), for a sharded checkpoint only: + +``` +CHECKPOINT_SHARDS model_sha256=<digest> model_digest_kind=index+shards index_sha256=<sha256> shards=[<name>:<sha256>,...] +``` + +Records written before sc#338 have no `model_digest_kind`; their +`model_sha256` is the sha256 of the file the daemon was given, which for a +sharded checkpoint was the index only. + ### `decoding`: the decoding actually taken (sc#294) The Qwen3 v4 review found greedy decoding documented but not observed: no @@ -125,10 +168,11 @@ silently accepted. intent, replay, commit or effect decision depends on it (`effects::generation_records_change_no_decision`). - Not that the digest is of the very bytes the loader parsed. The CLI hashes the - model and tokenizer files at load, and the loaders then open the same paths - again (the weights loader and tokenizer loader take paths, not bytes). The - digest is of the file read at load time; a swap between the hash and the load - is not detected. + model files (for a sharded checkpoint, the index and every shard) and the + tokenizer file at load, and the loaders then open the same paths again (the + weights loader and tokenizer loader take paths, not bytes). The digest is of + the files read at load time; a swap between the hash and the load is not + detected. - Not that the file on disk still has that digest later, only what was loaded. - Not signed. The ledger's per-record digest detects edits to a record, not a forged append: a process of the same user that can append to the compose