diff --git a/CHANGELOG.md b/CHANGELOG.md index 34242b957..757e0b88f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed +- A copied import no longer reaches the file watcher as an external change, + so a background reclassification cannot race the import's own finalization. + Payload proof also ignores the brief staging sibling of an atomic + `metadata.json` replacement; any other unbound entry is still refused. - A copied import finished before stable volume identities, such as a GGUF reranker or audio model, can again be finished with "Verify and finish import" after a reboot renumbers its drive. Its receipt recorded a raw diff --git a/rust/crates/pumas-core/src/metadata/atomic.rs b/rust/crates/pumas-core/src/metadata/atomic.rs index 9a39b8659..090318a0c 100644 --- a/rust/crates/pumas-core/src/metadata/atomic.rs +++ b/rust/crates/pumas-core/src/metadata/atomic.rs @@ -234,6 +234,27 @@ impl DurablePublicationAdapter for PublicationSyncFault { struct OsDurablePublicationAdapter; +/// Whether `name` is exactly a staging name the durable publisher creates +/// beside `target` (`...tmp`). A concurrent atomic +/// replacement of `target` makes such a sibling briefly visible. +pub(crate) fn is_durable_staging_name(target: &str, name: &str) -> bool { + let Some(rest) = name + .strip_prefix(target) + .and_then(|rest| rest.strip_prefix('.')) + .and_then(|rest| rest.strip_suffix(".tmp")) + else { + return false; + }; + let Some((uuid, attempt)) = rest.split_once('.') else { + return false; + }; + uuid.len() == 36 + && Uuid::try_parse(uuid).is_ok() + && !attempt.is_empty() + && attempt.bytes().all(|byte| byte.is_ascii_digit()) + && attempt.parse::().is_ok() +} + impl DurablePublicationAdapter for OsDurablePublicationAdapter { fn temp_name(&self, target: &OsStr, attempt: u8) -> OsString { let mut name = target.to_os_string(); diff --git a/rust/crates/pumas-core/src/metadata/mod.rs b/rust/crates/pumas-core/src/metadata/mod.rs index 21d1dc6b1..ad6dd4072 100644 --- a/rust/crates/pumas-core/src/metadata/mod.rs +++ b/rust/crates/pumas-core/src/metadata/mod.rs @@ -8,6 +8,7 @@ mod atomic; mod manager; +pub(crate) use atomic::is_durable_staging_name; pub use atomic::{atomic_read_json, atomic_write_json}; pub(crate) use atomic::{ AtomicJsonTarget, AtomicPublication, AtomicPublishFailure, AtomicPublishFailureKind, diff --git a/rust/crates/pumas-core/src/model_library/download_recovery/import_custody.rs b/rust/crates/pumas-core/src/model_library/download_recovery/import_custody.rs index 981b0a655..2b3c62006 100644 --- a/rust/crates/pumas-core/src/model_library/download_recovery/import_custody.rs +++ b/rust/crates/pumas-core/src/model_library/download_recovery/import_custody.rs @@ -404,6 +404,15 @@ impl DownloadRecoveryDestination { } } +/// Root control documents are not payload. Neither is the staging sibling a +/// concurrent atomic replacement of one of them briefly makes visible: it is +/// never bound, and its transient presence must not fail payload proof. +fn is_import_mutable_document_entry(name: &str) -> bool { + IMPORT_MUTABLE_DOCUMENTS.iter().any(|document| { + name == *document || crate::metadata::is_durable_staging_name(document, name) + }) +} + fn observe_directory( directory: &Dir, relative: &Path, @@ -417,7 +426,13 @@ fn observe_directory( .to_str() .ok_or_else(invalid_capability_path)? .replace(std::path::MAIN_SEPARATOR, "/"); - let metadata = directory.symlink_metadata(&name)?; + let root_document = relative.as_os_str().is_empty() + && name.to_str().is_some_and(is_import_mutable_document_entry); + let metadata = match directory.symlink_metadata(&name) { + // A concurrent atomic replacement renamed its staging file away. + Err(error) if root_document && error.kind() == io::ErrorKind::NotFound => continue, + result => result?, + }; if metadata.is_symlink() { return Err(invalid_capability_path().into()); } @@ -434,11 +449,7 @@ fn observe_directory( }), ); } else if metadata.is_file() { - if relative.as_os_str().is_empty() - && name - .to_str() - .is_some_and(|name| IMPORT_MUTABLE_DOCUMENTS.contains(&name)) - { + if root_document { continue; } let mut options = OpenOptions::new(); @@ -575,4 +586,45 @@ mod tests { b"preserve" ); } + + #[test] + fn concurrent_document_staging_is_not_payload_but_other_entries_are() { + let temp = tempfile::tempdir().unwrap(); + let root = DownloadDestinationRoot::open(temp.path()).unwrap(); + let _grant = root.try_acquire_execution_grant().unwrap(); + let stage = root.create_import_stage().unwrap(); + stage + .create_import_file("weights") + .unwrap() + .write_all(b"weights") + .unwrap(); + let proof = stage.capture_import_payload(&["weights".into()]).unwrap(); + let directory = stage.display_path().to_path_buf(); + // An atomic replacement of a root document stages beside it. + let staging = format!("metadata.json.{}.0.tmp", uuid::Uuid::new_v4()); + assert!(crate::metadata::is_durable_staging_name( + "metadata.json", + &staging + )); + std::fs::write(directory.join(&staging), b"{}").unwrap(); + stage.verify_import_bindings(&proof).unwrap(); + std::fs::remove_file(directory.join(&staging)).unwrap(); + // Lookalikes, staging names of payload files, out-of-range attempts and + // staging-named directories are unbound entries that refuse the proof. + for name in [ + "metadata.json.unbound.0.tmp".to_string(), + format!("weights.{}.0.tmp", uuid::Uuid::new_v4()), + format!("metadata.json.{}.256.tmp", uuid::Uuid::new_v4()), + ] { + std::fs::write(directory.join(&name), b"x").unwrap(); + assert!(stage.verify_import_bindings(&proof).is_err(), "{name}"); + std::fs::remove_file(directory.join(&name)).unwrap(); + } + let staged_directory = directory.join(&staging); + std::fs::create_dir(&staged_directory).unwrap(); + assert!(stage.verify_import_bindings(&proof).is_err()); + std::fs::remove_dir(&staged_directory).unwrap(); + stage.verify_import_bindings(&proof).unwrap(); + stage.remove_import_stage_all().unwrap(); + } } diff --git a/rust/crates/pumas-core/src/model_library/importer/staging.rs b/rust/crates/pumas-core/src/model_library/importer/staging.rs index 6437749b9..3ca7d4c83 100644 --- a/rust/crates/pumas-core/src/model_library/importer/staging.rs +++ b/rust/crates/pumas-core/src/model_library/importer/staging.rs @@ -484,6 +484,11 @@ impl ModelImporter { if let Err(error) = self.import_boundary(ImportBoundary::DescendantsReleased, &stage) { return settle_released(&publication, &stage, error, spec, security_tier); } + // Publication indexes the model itself below. Like other owned moves, + // its destination must not reach the watcher as an external change, + // or reconciliation reclassifies the model concurrently with the + // importer's own finalization and its callers' first observations. + self.library.notify_owned_move_destination(&target_path); let publication_outcome = match stage.publish_model_directory_noreplace(&target) { Err(error) => return settle_released(&publication, &stage, error, spec, security_tier), Ok(outcome) => outcome, diff --git a/rust/crates/pumas-core/src/model_library/importer/staging/tests.rs b/rust/crates/pumas-core/src/model_library/importer/staging/tests.rs index a8e6e70d3..3f592eda3 100644 --- a/rust/crates/pumas-core/src/model_library/importer/staging/tests.rs +++ b/rust/crates/pumas-core/src/model_library/importer/staging/tests.rs @@ -1072,8 +1072,8 @@ async fn copied_import_metadata_notifier_observes_write_paths_without_authorizin let paths = notifications.lock().unwrap().clone(); assert_eq!( paths.len(), - 2, - "Pending and Ready metadata writes both notify" + 3, + "Pending metadata, the owned publication destination and Ready metadata notify" ); assert_eq!(paths[0].file_name().unwrap(), "metadata.json"); assert!(paths[0] @@ -1087,7 +1087,10 @@ async fn copied_import_metadata_notifier_observes_write_paths_without_authorizin !paths[0].exists(), "notification is the former stage path, not retained filesystem authority" ); + // Publication is an owned move: its destination is announced before the + // rename so the watcher never mistakes it for an external change. assert_eq!(paths[1], fixture.target().join("metadata.json")); + assert_eq!(paths[2], fixture.target().join("metadata.json")); assert!(fixture.target().join("metadata.json").is_file()); fixture.tasks.shutdown_owned().await.unwrap(); } diff --git a/rust/crates/pumas-core/src/model_library/importer/staging/tests/publication.rs b/rust/crates/pumas-core/src/model_library/importer/staging/tests/publication.rs index 3ef8ddadb..abc4b1a90 100644 --- a/rust/crates/pumas-core/src/model_library/importer/staging/tests/publication.rs +++ b/rust/crates/pumas-core/src/model_library/importer/staging/tests/publication.rs @@ -416,7 +416,9 @@ async fn copied_import_final_metadata_notifier_keeps_checksum_as_historical_evid fixture .library .set_metadata_write_notifier(Some(Arc::new(move |path| { - if observed.fetch_add(1, Ordering::SeqCst) == 1 { + // Call 1 announces the publication destination before its rename; + // call 2 is the final metadata write in the published directory. + if observed.fetch_add(1, Ordering::SeqCst) == 2 { let weights = path.parent().unwrap().join("model.onnx"); let bytes = std::fs::read(&weights).unwrap(); std::fs::write(weights, vec![b'x'; bytes.len()]).unwrap(); @@ -424,7 +426,7 @@ async fn copied_import_final_metadata_notifier_keeps_checksum_as_historical_evid }))); let result = fixture.importer.import(&fixture.spec).await.unwrap(); assert!(result.success); - assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_eq!(calls.load(Ordering::SeqCst), 3); assert_eq!(receipt_at(&fixture.target())["state"], "confirmed"); let metadata = fixture .library