From 16f00d4cf9c7056961c4aed24df332f4a9b96ad0 Mon Sep 17 00:00:00 2001 From: kaltenbrunnermarkus <153593707+kaltenbrunnermarkus@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:16:12 +0000 Subject: [PATCH] Opening: validate the document once when a model cache is present (#10501) * claim: Opening: validate the document once when a model cache is present * Opening: validate the document once when a model cache is present Opening a design that keeps its model parsed and validated document.json twice: reading the model cache checked it before decoding the cached bodies, and read_document, which follows straight after, runs the same migrations and validation and fails the open when they fail. The open path now reads the model without that check; geometry(), read_design_geometry and the preview keep it. A broken document fails the open with the same error as before. 3,000-feature design with its model cache, bench-open parse step: 426 -> 293 ms (median of 8, heavy machine load). Saving the opened design gives a byte-identical file. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Markus Kaltenbrunner Co-authored-by: Claude Opus 5.5 --- crates/io/src/design.rs | 47 +++++++++++++++++++++++++++- crates/io/src/design/native_cache.rs | 23 +++++++++++++- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 3a293b8cb..9e3a040e2 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -734,6 +734,12 @@ impl DesignContainerReader { pub fn read_document(mut self) -> Result { read_document(&mut self.reader) } + + /// [`Self::geometry`] when [`Self::read_document`] follows: it validates the document. + fn geometry_before_document(&mut self) -> Option { + let document = self.reader.document(16 << 20).ok()?; + native_cache::read_geometry_before_document(&mut self.reader, &document).ok() + } } pub(super) fn read(bytes: &[u8]) -> Result { @@ -750,7 +756,7 @@ pub fn read_design_file(path: &str, notify: Option) if is_container_source(&mut source)? { let mut reader = DesignContainerReader::new(source)?; // A design with its model opens without a picture first: the model is the session. - let model = reader.geometry(); + let model = reader.geometry_before_document(); if let Some(notify) = notify && model.is_none() && let Ok(preview) = read_preview(&mut reader.reader) @@ -1280,6 +1286,45 @@ mod tests { assert!(read_design_geometry(&bytes).is_some()); } + /// Opening a design with its model validates its document once, where the document is read + /// (`read_document`); reading the model first validated it a second time, a whole parse and + /// validation of a large design. A broken document still fails the open, as it did. + #[test] + fn opening_with_a_model_cache_validates_the_document_once() { + let validated = || native_cache::VALIDATED.with(std::cell::Cell::get); + let doc = document(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap(); + let before = validated(); + let alone = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap(); + assert_eq!(validated(), before + 1, "the model alone checks its document"); + let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap(); + let model = reader.geometry_before_document().unwrap(); + assert_eq!(validated(), before + 1, "opening leaves it to read_document"); + assert_eq!(reader.read_document().unwrap().to_json(), doc.to_json()); + assert_eq!(model.records, alone.records); + assert_eq!(model.bodies.len(), alone.bodies.len()); + + // A broken document whose cache is signed for it: the open fails with read_document's + // error, as when the model was read with the document validated (and so missed). + let entries = parts(&bytes); + let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap(); + let mut metadata: Value = serde_json::from_slice(&entries["document.json"]).unwrap(); + metadata["features"] = json!(5); + let truncated = entries["document.json"][..entries["document.json"].len() / 2].to_vec(); + for broken in [serde_json::to_vec(&metadata).unwrap(), truncated] { + let mut entries = entries.clone(); + manifest["document"] = json!(digest(&broken)); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); + entries.insert("document.json".into(), broken); + let bytes = package(&entries); + assert!(DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().is_none()); + let expected = read(&bytes).unwrap_err().to_string(); + let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap(); + let _ = reader.geometry_before_document(); + assert_eq!(reader.read_document().unwrap_err().to_string(), expected); + } + } + /// A saved model of four features (5, 50, 20 and 1 ms) whose states each hold the eight /// bodies all of them share and eight of their own (a body each feature replaces). No /// document evaluated it. diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index 9f4c2b197..dfc3e8426 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -348,6 +348,12 @@ fn current(manifest: &Value, document: &[u8]) -> bool { && source_trusted(env!("SOLIDCRAFT_EVALUATION_SOURCE"), cfg!(any(test, feature = "trust-unknown-source"))) } +#[cfg(test)] +thread_local! { + /// How often reading a model cache validated its document (tests count it). + pub(super) static VALIDATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// A build of unknown source (no git) never trusts a cache, unless `in_tests`: test builds /// trust it so the cache tests also pass in a source tarball (the `trust-unknown-source` /// feature is only enabled by dev-dependencies). @@ -356,6 +362,17 @@ pub(super) fn source_trusted(commit: &str, in_tests: bool) -> bool { } pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { + read_geometry(reader, document, true) +} + +/// [`read_geometry_with`] for a reader whose document is read next: reading it runs the same +/// migrations and validation and fails the open when they fail, so validating it here as well +/// parsed and validated a large design twice (the model is dropped with the failed open). +pub(super) fn read_geometry_before_document(reader: &mut PackageReader, document: &[u8]) -> Result { + read_geometry(reader, document, false) +} + +fn read_geometry(reader: &mut PackageReader, document: &[u8], validate: bool) -> Result { let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; if container.get("format").and_then(Value::as_str) != Some(VERSION) { return Err(invalid("container version")); @@ -365,7 +382,11 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, return Err(invalid("model cache key")); } // Validate the small parametric metadata before decoding any geometry. - Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; + if validate { + #[cfg(test)] + VALIDATED.with(|n| n.set(n.get() + 1)); + Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; + } let data = reader.limited_part(PAYLOAD, max_design())?; if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) { return Err(invalid("model cache payload key"));