From 5fb129f1f34b13fcfc811c98a1cd11e663942838 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:20:33 +0800 Subject: [PATCH] Read a Retyped Option From the Preset Cache as a JSON Profile Would (#17047) A vendor's installed preset cache survives an app upgrade, and the dictionary records the type every option was written as. When a build reads a cache written by a build that typed an option differently, the reader dropped the option and the preset fell back to the collection default, which is not what the vendor's JSON says. enable_arc_fitting became an enum in 2.5.0-beta, so every vendor whose bundle was not bumped between the alpha and the beta now loads with arc fitting off from the alpha's cache, and the alpha reads the beta's cache the same way. Read such a value by the writer's type and hand its text to set_deserialize through a scratch config, so handle_legacy and the bool/enum substitution run on it exactly as for a JSON profile and a failed parse leaves nothing behind. A text this build cannot place is still dropped, reported once per key per file. --- docs/HLSD/preset-cache.md | 25 +++-- src/libslic3r/PresetCacheFormat.cpp | 128 ++++++++++++++++------ src/libslic3r/PresetCacheFormat.hpp | 20 +++- tests/libslic3r/test_vendor_cache.cpp | 146 +++++++++++++++++++++++--- 4 files changed, 259 insertions(+), 60 deletions(-) diff --git a/docs/HLSD/preset-cache.md b/docs/HLSD/preset-cache.md index ed7403f5ef..41a52bd633 100644 --- a/docs/HLSD/preset-cache.md +++ b/docs/HLSD/preset-cache.md @@ -95,9 +95,16 @@ declaration order at static init — cannot: inserting one option into the middl *succeeds on the wrong option*, silently, wherever the two share a type. Because a name-keyed payload instead drops the individual options this build cannot place, the file as a whole stays readable, and there is no schema fingerprint — no checksum over -the option schema that would reject every cache on every release. An option this build -no longer defines, or now defines with a different type, gets exactly what it gets from -a JSON profile: read, dropped, and the rest of the preset loads. +the option schema that would reject every cache on every release. An option this build no +longer defines gets exactly what it gets from a JSON profile: read, dropped, and the rest +of the preset loads. An option this build now defines with a different type is read by the +type the writer recorded and handed to `set_deserialize` as its text, again as a JSON +profile's value would be: `handle_legacy` maps an old spelling (a bool's `1` onto an +enum's `enabled`) and an enum name a bool cannot parse is substituted. Only a text this +build cannot parse into the new type is dropped, that option alone. Dropping a retyped +option outright would leave the key at the collection default in every preset that sets +it, which is not what the JSON says, and an installed cache outlives the app upgrade that +retyped the key. The ordinal-keyed cereal hooks in `PrintConfig.hpp` are untouched — they are also the undo/redo wire format, where the process cannot change underneath them. The cache has @@ -365,8 +372,11 @@ The system is designed so that no cache problem is fatal: - **Corrupt, truncated or foreign file** — rejected at the header, vendor parsed. A cache is written to a temp file beside its target and moved into place, so a write that dies partway leaves the previous cache intact rather than a truncated one. -- **An option this build no longer has, or now types differently** — that option alone - is dropped, exactly as a JSON profile's would be. The preset and the file load. +- **An option this build no longer has** — that option alone is dropped, exactly as a + JSON profile's would be. The preset and the file load. +- **An option this build now types differently** — its value is read as the writer + typed it and parsed from its text as a JSON profile's would be, legacy conversions + included; only a text this build cannot parse into the new type is dropped. - **Cache from a build with a different cache layout** — rejected on `CACHE_VERSION`. A vendor with JSONs beside it is parsed and re-cached; a cache-only vendor reads as not installed and the updater reinstalls it. @@ -393,7 +403,10 @@ enumerates only `*.json` will find no vendors at all in a packaged build. - **Adding, removing, retyping or reordering a config option** needs nothing. The payload names its keys and its enum values, so an option a cache carries and this build does not is dropped; one this build has and the cache does not is simply - absent, as it would be from a JSON that predates it. + absent, as it would be from a JSON that predates it. A retyped option is read + through `handle_legacy`, so give it the same conversion a JSON profile needs and the + cache follows; an installed cache survives the upgrade that retyped the key, so that + conversion is what every user who upgrades reads. - **Changing a hand-written `serialize()`** — `VendorProfile` or its nested types — or the `CachedPreset` field list — written and read by `visit_entry` in `PresetCacheFormat.cpp`, one list for the save, the load and the name peek alike — or diff --git a/src/libslic3r/PresetCacheFormat.cpp b/src/libslic3r/PresetCacheFormat.cpp index 0a2d82cca7..26c8240c4f 100644 --- a/src/libslic3r/PresetCacheFormat.cpp +++ b/src/libslic3r/PresetCacheFormat.cpp @@ -117,10 +117,9 @@ void CacheDictionary::load(cereal::BinaryInputArchive& ar) throw std::runtime_error("preset cache: dictionary is missing its unnamed-enum slot"); // Resolved once per file: every option read after this is a vector index. m_defs.resize(m_keys.size()); - for (size_t i = 0; i < m_keys.size(); ++ i) { - const ConfigOptionDef* def = print_config_def.get(m_keys[i]); - m_defs[i] = (def != nullptr && uint16_t(def->type) == m_types[i]) ? def : nullptr; - } + m_reported.assign(m_keys.size(), char(0)); + for (size_t i = 0; i < m_keys.size(); ++ i) + m_defs[i] = print_config_def.get(m_keys[i]); } // ---- one config ----------------------------------------------------------- @@ -138,10 +137,14 @@ static void save_enum_option(cereal::BinaryOutputArchive& ar, const ConfigOption } } -// `config` may be null, in which case the option is read and dropped. +// `config` may be null, in which case the option is read and dropped. With +// `text` given, the value is also returned as the text a JSON profile would +// carry — the names, comma-separated for a vector, with an int the writer +// could not name as a number or "nil" — for read_config to place a key this +// build types differently through handle_legacy. static void load_enum_option(cereal::BinaryInputArchive& ar, ConfigOptionType type, const ConfigOptionDef* def, DynamicPrintConfig* config, - const CacheDictionary& dict) + const CacheDictionary& dict, std::string* text = nullptr) { uint32_t cnt = 0; ar(cnt); @@ -151,32 +154,38 @@ static void load_enum_option(cereal::BinaryInputArchive& ar, ConfigOptionType ty // whatever follows this option still loads. bool usable = def != nullptr && config != nullptr; std::vector values; - values.reserve(cnt); + if (usable) + values.reserve(cnt); for (uint32_t i = 0; i < cnt; ++ i) { uint16_t idx = 0; ar(idx); if (! dict.valid_enum_index(idx)) throw std::runtime_error("preset cache: enum value index past the end of the dictionary"); - if (idx == CacheDictionary::ENUM_UNNAMED) { - // An int the writer could not name — a nil, or an option whose - // definition carried no enum_keys_map. It travels verbatim. - int32_t raw = 0; + // An int the writer could not name — a nil, or an option whose + // definition carried no enum_keys_map — follows its index verbatim. + int32_t raw = 0; + if (idx == CacheDictionary::ENUM_UNNAMED) ar(raw); - values.push_back(int(raw)); - continue; - } - if (! usable) - continue; // the index above was this element's whole payload - if (def->enum_keys_map == nullptr) { - usable = false; // this build no longer maps this option's names - continue; - } - const auto it = def->enum_keys_map->find(dict.enum_name_at(idx)); - if (it == def->enum_keys_map->end()) { + if (usable) { + if (idx == CacheDictionary::ENUM_UNNAMED) { + values.push_back(int(raw)); + continue; + } + const auto it = def->enum_keys_map == nullptr ? def->enum_keys_map->end() : def->enum_keys_map->find(dict.enum_name_at(idx)); + if (def->enum_keys_map != nullptr && it != def->enum_keys_map->end()) { + values.push_back(it->second); + continue; + } usable = false; // a value this build dropped: the option goes with it - continue; } - values.push_back(it->second); + if (text != nullptr) { + if (! text->empty()) + *text += ','; + if (idx != CacheDictionary::ENUM_UNNAMED) + *text += dict.enum_name_at(idx); + else + *text += raw == ConfigOptionIntsNullable::nil_value() ? std::string("nil") : std::to_string(raw); + } } if (! usable) return; @@ -209,6 +218,41 @@ void save_config(cereal::BinaryOutputArchive& ar, const DynamicPrintConfig& conf } } +// The nullable form of a vector type reads the same bytes as the plain form +// and serializes a nil entry as "nil", which a nullable option parses back. +static bool has_nullable_form(ConfigOptionType type) +{ + return type == coFloats || type == coInts || type == coPercents || type == coBools || type == coFloatsOrPercents; +} + +// Place the value of a key this build types differently from the writer, the +// way a JSON profile's text is placed: handle_legacy maps the old spelling (a +// bool's 1 onto an enum's enabled) and a bool or enum that still does not +// parse is substituted, silently as for a system preset. The parse goes +// through a scratch config: set_deserialize_raw creates an option before +// parsing into it, so a failed parse must leave nothing behind, and the +// placing of one key must not take the whole cache down. +static void set_from_text(DynamicPrintConfig& config, const CacheDictionary& dict, uint16_t idx, + const std::string& text, ConfigSubstitutionContext& substitutions) +{ + const std::string& key = dict.key_at(idx); + DynamicPrintConfig parsed; + bool placed = false; + try { + placed = parsed.set_deserialize_nothrow(key, text, substitutions); + } catch (const std::exception&) { + placed = false; + } + if (placed) { + config.apply(parsed); + return; + } + if (dict.first_report(idx)) + // The key and the types only: the value may be a G-code template. + BOOST_LOG_TRIVIAL(warning) << "preset cache: dropped " << key << ", written as type " << int(dict.type_at(idx)) + << ", which this build cannot read as type " << int(dict.def_at(idx)->type); +} + // `config` null means: read everything, keep nothing. static void read_config(cereal::BinaryInputArchive& ar, DynamicPrintConfig* config, const CacheDictionary& dict) { @@ -216,26 +260,42 @@ static void read_config(cereal::BinaryInputArchive& ar, DynamicPrintConfig* conf ar(cnt); if (config != nullptr) config->clear(); - // Reused across the loop: constructing a ConfigOptionDef per dropped option - // would allocate its strings and vectors for nothing. + // Reused across the loop: constructing a ConfigOptionDef per option read by + // the writer's type would allocate its strings and vectors for nothing. ConfigOptionDef scratch; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::EnableSilent); for (uint32_t i = 0; i < cnt; ++ i) { uint16_t idx = 0; ar(idx); if (! dict.valid_key_index(idx)) throw std::runtime_error("preset cache: option index past the end of the dictionary"); - const ConfigOptionType type = dict.type_at(idx); - const ConfigOptionDef* def = dict.def_at(idx); + const ConfigOptionType type = dict.type_at(idx); + const ConfigOptionDef* def = dict.def_at(idx); + const bool as_written = def != nullptr && def->type == type; + // Built from the bytes where this build defines the key as written. + // Otherwise read by the type the writer recorded: dropped where this + // build has no such key, the same outcome a JSON profile gets, and + // placed from its text, as a JSON profile's value is, where it has the + // key under another type. + const bool retyped = def != nullptr && ! as_written && config != nullptr; + std::string text; + std::string* text_out = retyped ? &text : nullptr; if (type == coEnum || type == coEnums) { - load_enum_option(ar, type, def, config, dict); - } else if (def != nullptr && config != nullptr) { + load_enum_option(ar, type, as_written ? def : nullptr, config, dict, text_out); + if (! retyped) + continue; + } else if (as_written && config != nullptr) { config->set_key_value(def->opt_key, def->load_option_from_archive(ar)); + continue; } else { - // Read by the type the writer recorded, then drop: the same outcome - // a JSON profile gets for an option this build no longer has. - scratch.type = type; - std::unique_ptr discard(scratch.load_option_from_archive(ar)); + scratch.type = type; + scratch.nullable = has_nullable_form(type); + std::unique_ptr value(scratch.load_option_from_archive(ar)); + if (! retyped) + continue; + text = value->serialize(); } + set_from_text(*config, dict, idx, text, substitutions); } } diff --git a/src/libslic3r/PresetCacheFormat.hpp b/src/libslic3r/PresetCacheFormat.hpp index c6e5fcb65a..ee7b22fe3e 100644 --- a/src/libslic3r/PresetCacheFormat.hpp +++ b/src/libslic3r/PresetCacheFormat.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -61,17 +62,22 @@ public: // ---- reading ---- - // The definition an index resolves to in THIS build, or nullptr where the - // key is unknown here or is now defined with a different type. A nullptr - // entry's value is still read — using type_at(idx), the type the writer - // recorded — and then dropped, which is what a JSON profile gets for an - // option this build no longer has. + // The definition THIS build has for an index's key, or nullptr where the key + // is unknown here. type_at(idx) is the type the writer recorded; the value + // is read by that type whatever this build's is. With no definition it is + // then dropped, which is what a JSON profile gets for an option this build + // no longer has; with a definition of another type it is placed as a JSON + // profile's text would be (see read_config), so the key is never left at + // the collection default while a JSON profile would have mapped it. const ConfigOptionDef* def_at(uint16_t idx) const { return m_defs[idx]; } + const std::string& key_at(uint16_t idx) const { return m_keys[idx]; } ConfigOptionType type_at(uint16_t idx) const { return ConfigOptionType(m_types[idx]); } const std::string& enum_name_at(uint16_t idx) const { return m_enum_values[idx]; } // m_defs, not m_keys: only load() sizes it, so this is false for every index // on a dictionary that was collected rather than read. bool valid_key_index(uint16_t idx) const { return size_t(idx) < m_defs.size(); } + // True the first time it is asked for an index, false after. + bool first_report(uint16_t idx) const { return ! std::exchange(m_reported[idx], char(1)); } bool valid_enum_index(uint16_t idx) const { return size_t(idx) < m_enum_values.size(); } // The layout these two agree on is covered by CACHE_VERSION (PresetCacheFormat.cpp); @@ -99,6 +105,10 @@ private: std::unordered_map m_enum_index; // Reading, resolved once by load(). std::vector m_defs; + // Keys whose value read_config already reported dropping from this file, + // so a key set by every preset is logged once, not once per preset. The + // entries of one file are read in sequence, never concurrently. + mutable std::vector m_reported; }; // One config, keyed through `dict`. Options print_config_def does not know are diff --git a/tests/libslic3r/test_vendor_cache.cpp b/tests/libslic3r/test_vendor_cache.cpp index b78ce77e1f..ee590f823f 100644 --- a/tests/libslic3r/test_vendor_cache.cpp +++ b/tests/libslic3r/test_vendor_cache.cpp @@ -15,6 +15,7 @@ #include #include "libslic3r/Semver.hpp" #include "libslic3r/Config.hpp" +#include "libslic3r/PrintConfig.hpp" #include #include #include @@ -36,7 +37,6 @@ #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PresetCacheFormat.hpp" #include "libslic3r/Preset.hpp" -#include "libslic3r/PrintConfig.hpp" #include "libslic3r/Utils.hpp" using namespace Slic3r; @@ -1958,35 +1958,151 @@ TEST_CASE("an option the build no longer knows is dropped, and the rest still lo CHECK(out.opt_string("printer_model") == "Test Model"); } -TEST_CASE("an option whose type changed is dropped, and the rest still load", "[VendorCache]") +namespace { + +// A payload from a build whose dictionary this build did not produce: only +// such a dictionary can type a key differently from print_config_def. `write` +// emits the option values in the order of `keys`. +DynamicPrintConfig load_foreign_payload(const std::vector& keys, const std::vector& types, + const std::vector& enum_names, + const std::function& write) { - // A payload from a build where layer_height was a coString. This one has it - // as a coFloat, so nothing can be done with the value - but the dictionary - // says how it was written, so its bytes are still consumed and printer_model - // behind it still lands. Hand-written rather than round-tripped: only a - // dictionary this build did not produce can disagree with it. std::ostringstream os(std::ios::binary); { cereal::BinaryOutputArchive ar(os); - const std::vector keys { "layer_height", "printer_model" }; - const std::vector types { uint16_t(coString), uint16_t(coString) }; - const std::vector enums { std::string() }; // the ENUM_UNNAMED slot + std::vector enums { std::string() }; // the ENUM_UNNAMED slot + enums.insert(enums.end(), enum_names.begin(), enum_names.end()); ar(keys, types, enums); - ar(uint32_t(2)); - ar(uint16_t(0)); ar(ConfigOptionString("0.28")); - ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + ar(uint32_t(keys.size())); + write(ar); } - std::istringstream is(os.str(), std::ios::binary); cereal::BinaryInputArchive ar(is); CacheDictionary rdict; rdict.load(ar); DynamicPrintConfig out; REQUIRE_NOTHROW(load_config(ar, out, rdict)); - CHECK(out.option("layer_height") == nullptr); + return out; +} + +} // namespace + +TEST_CASE("an option whose type changed is read as a JSON profile's text, and the rest still load", "[VendorCache]") +{ + // A payload from a build where layer_height was a coString. This one has it + // as a coFloat, so the value goes in as the text "0.28" would from a JSON + // profile, and printer_model behind it still lands. + REQUIRE(print_config_def.get("layer_height")->type == coFloat); + const DynamicPrintConfig out = load_foreign_payload( + { "layer_height", "printer_model" }, { uint16_t(coString), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionString("0.28")); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("layer_height") != nullptr); + CHECK_THAT(out.opt_float("layer_height"), Catch::Matchers::WithinAbs(0.28, 1e-9)); CHECK(out.opt_string("printer_model") == "Test Model"); } +TEST_CASE("a bool an older build cached is read by the enum that replaced it", "[VendorCache]") +{ + // enable_arc_fitting was a coBool until it became an enum. A cache written + // before that carries true/false; this build maps them through handle_legacy + // to enabled/disabled, as it does for a JSON profile, instead of dropping the + // key and leaving the preset at the collection default. + REQUIRE(print_config_def.get("enable_arc_fitting")->type == coEnum); + const DynamicPrintConfig out = load_foreign_payload( + { "enable_arc_fitting", "printer_model" }, { uint16_t(coBool), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionBool(true)); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("enable_arc_fitting") != nullptr); + CHECK(out.option("enable_arc_fitting")->serialize() == "enabled"); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("an enum a newer build cached is read by the bool this build still has", "[VendorCache]") +{ + // The other direction: a cache from a build that turned a bool into an enum, + // read by a build where the key is still a bool. The enum travels by name, + // and the name is substituted the way a JSON profile's would be. + REQUIRE(print_config_def.get("reduce_crossing_wall")->type == coBool); + const DynamicPrintConfig out = load_foreign_payload( + { "reduce_crossing_wall", "printer_model" }, { uint16_t(coEnum), uint16_t(coString) }, { "enabled" }, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(uint32_t(1)); ar(uint16_t(1)); // one value, enum name index 1 = "enabled" + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("reduce_crossing_wall") != nullptr); + CHECK(out.opt_bool("reduce_crossing_wall") == true); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("a retyped value this build cannot parse is dropped, and the rest still load", "[VendorCache]") +{ + // A string that is no number for a key this build types as a float: nothing + // to substitute it with, so the key alone is dropped, as from a JSON profile. + REQUIRE(print_config_def.get("layer_height")->type == coFloat); + const DynamicPrintConfig out = load_foreign_payload( + { "layer_height", "printer_model" }, { uint16_t(coString), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionString("thick")); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + CHECK(out.option("layer_height") == nullptr); + CHECK(out.keys() == t_config_option_keys{ "printer_model" }); +} + +TEST_CASE("a nullable vector cached under another type keeps its nil entries", "[VendorCache]") +{ + // default_acceleration is a nullable coFloats. Written as coInts by a build + // that typed it so, its nil entry must come back as nil, not as the int the + // sentinel happens to be. + const ConfigOptionDef* def = print_config_def.get("default_acceleration"); + REQUIRE(def->type == coFloats); + REQUIRE(def->nullable); + const DynamicPrintConfig out = load_foreign_payload( + { "default_acceleration", "printer_model" }, { uint16_t(coInts), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionInts({ ConfigOptionIntsNullable::nil_value(), 5000 })); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + const auto* accel = out.option("default_acceleration"); + REQUIRE(accel != nullptr); + REQUIRE(accel->values.size() == 2); + CHECK(accel->is_nil(0)); + CHECK_THAT(accel->values[1], Catch::Matchers::WithinAbs(5000., 1e-9)); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("skip_config consumes a config with options this build cannot place", "[VendorCache]") +{ + // The entries a name peek reads past may be ones this build would replay + // from text; skipping must still consume exactly their bytes. + std::ostringstream os(std::ios::binary); + { + cereal::BinaryOutputArchive ar(os); + const std::vector keys { "enable_arc_fitting", "sparse_infill_pattern", "no_such_option" }; + const std::vector types { uint16_t(coBool), uint16_t(coEnum), uint16_t(coString) }; + const std::vector enums { std::string(), "zig-zag" }; + ar(keys, types, enums); + ar(uint32_t(3)); + ar(uint16_t(0)); ar(ConfigOptionBool(true)); + ar(uint16_t(1)); ar(uint32_t(1)); ar(uint16_t(1)); + ar(uint16_t(2)); ar(ConfigOptionString("x")); + ar(std::string("sentinel")); + } + std::istringstream is(os.str(), std::ios::binary); + cereal::BinaryInputArchive ar(is); + CacheDictionary rdict; + rdict.load(ar); + skip_config(ar, rdict); + std::string sentinel; + ar(sentinel); + CHECK(sentinel == "sentinel"); +} + TEST_CASE("skip_config consumes a config without building one", "[VendorCache]") { DynamicPrintConfig in;