diff --git a/CHANGELOG.md b/CHANGELOG.md index 3be5081f..04ec22cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,9 +56,12 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and turns it off). marimo unpickles an entry while it answers the cache lookup, which is about a second for each of the six-axis arm's assemblies; the kernel now asks its memory right after the cell's key is hashed and before the disk, and hands out the same objects when the entry is one this process holds. Only plain data and the SDK's value types are - kept. They are functional except for `set_metadata` and `auto_tag_faces`, which change the value they are called on: - those two are watched, and an entry holding a value that one of them changed is dropped, so the next restore reads - the disk copy as before (a change made through a part of an assembly, `assembly.get_component(...)`, is not seen). + kept. They are functional except for the semantic state of a shape: `apply_tag`, `set_metadata` and `auto_tag_faces` + change the shape they are called on and return the same object, so a later cell that tags a shape it received would + change what the producing cell has kept (the disk copy has none of it). Every root of shapes now counts its writes + (`AnyShape._semantic_revision`); an entry whose counts moved since it was kept is dropped and the next restore reads + the disk copy as before. Reading a shape or consuming it in an operator does not count. Parts and assemblies are + followed to their bodies and components. The limit is twelve entries, not a number of bytes, and costs about 300 MB on the six-axis arm; only the editor's kernel has a memory (`sca run` and the tests do not). With a marimo whose `cache_attempt_from_hash` has another signature than the one this was written for, a line on stderr says so and the memory is off. `SCA_EDITOR_TRACE=1` with diff --git a/src/cpp/bindings/python/bind_topo.cpp b/src/cpp/bindings/python/bind_topo.cpp index 9e02f1b1..2884effe 100644 --- a/src/cpp/bindings/python/bind_topo.cpp +++ b/src/cpp/bindings/python/bind_topo.cpp @@ -133,7 +133,10 @@ void bind_common(Cls& cls) { } // namespace void bind_topo(py::module_& m) { - py::class_(m, "AnyShape").def_property_readonly("topo_id", &Shape::topo_id); + py::class_(m, "AnyShape") + .def_property_readonly("topo_id", &Shape::topo_id) + // How many writes to semantic state the root of this shape has had: equal before and after means unchanged. + .def("_semantic_revision", &Shape::semantic_revision); auto vertex = py::class_(m, "Vertex"); vertex.def("get_coordinates", &Vertex::coordinates).def("get_incident_edges", &Vertex::incident_edges); diff --git a/src/cpp/include/scad/topo/shape.hpp b/src/cpp/include/scad/topo/shape.hpp index 22b7ea8c..052ecd93 100644 --- a/src/cpp/include/scad/topo/shape.hpp +++ b/src/cpp/include/scad/topo/shape.hpp @@ -79,6 +79,9 @@ class Shape { std::shared_ptr graph_node() const; // A key equal for exactly the handles for which same_entity holds (the hash of a handle). std::size_t entity_key() const noexcept; + // How many writes to semantic state (tags, bindings, lineage, metadata) the entities of this handle's root have had. + // Equal numbers before and after mean nobody changed the shape in between. + std::uint64_t semantic_revision() const noexcept; template T as() const { @@ -200,6 +203,8 @@ class Shape { TopoDS_Shape shape_; std::shared_ptr entity_; std::shared_ptr registry_; + // The write door of the semantic state: counts the write (see semantic_revision). + SemanticState& writable_state(); }; // --------------------------------------------------------------------------- diff --git a/src/cpp/src/topo/internal.hpp b/src/cpp/src/topo/internal.hpp index 01204c03..f3c53067 100644 --- a/src/cpp/src/topo/internal.hpp +++ b/src/cpp/src/topo/internal.hpp @@ -2,6 +2,8 @@ #pragma once #include +#include +#include #include #include #include @@ -271,6 +273,12 @@ class Registry { explicit Registry(TopoDS_Shape root) : root_(std::move(root)) {} const TopoDS_Shape& root() const noexcept { return root_; } + + // Counts the writes to the semantic state (tags, bindings, lineage, metadata) of any entity of this root. A holder + // of a shape that must know whether somebody changed it since (the editor kernel's memory of what a cell made) + // compares the number it read before with the number now; an operation that only reads a shape leaves it alone. + std::uint64_t revision() const noexcept { return revision_.load(std::memory_order_relaxed); } + void touch() noexcept { revision_.fetch_add(1, std::memory_order_relaxed); } std::shared_ptr acquire(Kind kind, const TopoDS_Shape& shape); // Ancestor relations of the root, built on first use: for each `child` @@ -310,6 +318,7 @@ class Registry { }; TopoDS_Shape root_; + std::atomic revision_{0}; Table tables_[7]; std::vector> ancestor_tables_; }; diff --git a/src/cpp/src/topo/shape.cpp b/src/cpp/src/topo/shape.cpp index 42545c96..e132d73e 100644 --- a/src/cpp/src/topo/shape.cpp +++ b/src/cpp/src/topo/shape.cpp @@ -68,7 +68,7 @@ bool Shape::same_entity(const Shape& other) const noexcept { } void Shape::set_graph_node(std::shared_ptr node) const { - entity_->state().graph_node = std::move(node); + entity_->state().graph_node = std::move(node); // a link for the recorder, not a change a reader of the shape sees } std::shared_ptr Shape::graph_node() const { const SemanticState* state = entity_->state_if(); @@ -79,6 +79,10 @@ std::size_t Shape::entity_key() const noexcept { return std::hash{}(entity_.get()) * 31u + std::hash{}(registry_.get()); } +std::uint64_t Shape::semantic_revision() const noexcept { + return registry_->revision(); +} + // Shape::clone_view lives with the rest of the semantic state, in shape_tags.cpp. std::vector Shape::known_parents() const { diff --git a/src/cpp/src/topo/shape_tags.cpp b/src/cpp/src/topo/shape_tags.cpp index bebd7dcd..20b3aa45 100644 --- a/src/cpp/src/topo/shape_tags.cpp +++ b/src/cpp/src/topo/shape_tags.cpp @@ -153,9 +153,14 @@ bool any_downward(const std::vector& bindings) { // --------------------------------------------------------------------------- // Storing bindings // --------------------------------------------------------------------------- +SemanticState& Shape::writable_state() { + registry_->touch(); + return entity_->state(); +} + void Shape::add_binding(TagBinding binding) { binding.validate(); - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); const bool duplicate = std::any_of(state.bindings.begin(), state.bindings.end(), [&](const TagBinding& b) { return b.binding_id == binding.binding_id; }); if (duplicate) @@ -189,7 +194,7 @@ void Shape::add_tag_lineage(const TagBinding& binding, LineageDerivation derivat void Shape::add_lineage_witness(TagLineageWitness witness) { witness.validate(); - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); const bool duplicate = std::any_of(state.lineage.begin(), state.lineage.end(), [&](const TagLineageWitness& w) { return same_witness(w, witness); }); if (!duplicate) @@ -204,6 +209,7 @@ std::size_t Shape::remove_tag_bindings(std::string_view tag, TagProducerKind mat const auto doomed = [&](const TagBinding& b) { return b.tag == normalized && b.producer().kind == matching; }; const auto removed = static_cast(std::count_if(state->bindings.begin(), state->bindings.end(), doomed)); if (removed != 0) { + registry_->touch(); state->bindings.erase(std::remove_if(state->bindings.begin(), state->bindings.end(), doomed), state->bindings.end()); } @@ -218,6 +224,7 @@ std::size_t Shape::remove_tag_bindings(std::string_view tag, const TagProducer& const auto doomed = [&](const TagBinding& b) { return b.tag == normalized && b.producer() == matching; }; const auto removed = static_cast(std::count_if(state->bindings.begin(), state->bindings.end(), doomed)); if (removed != 0) { + registry_->touch(); state->bindings.erase(std::remove_if(state->bindings.begin(), state->bindings.end(), doomed), state->bindings.end()); } @@ -240,13 +247,16 @@ bool Shape::remove_tag_binding(std::string_view binding_id) { state->bindings.erase(std::remove_if(state->bindings.begin(), state->bindings.end(), [&](const TagBinding& b) { return b.binding_id == binding_id; }), state->bindings.end()); - return state->bindings.size() != before; + const bool removed = state->bindings.size() != before; + if (removed) + registry_->touch(); + return removed; } void Shape::replace_local_tag_bindings(std::vector bindings) { for (const auto& b : bindings) b.validate(); - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); state.bindings.erase(std::remove_if(state.bindings.begin(), state.bindings.end(), is_local), state.bindings.end()); if (any_downward(bindings)) registry_->has_downward_bindings = true; @@ -259,7 +269,7 @@ void Shape::set_legacy_tags(const std::vector& tags) { imported.reserve(tags.size()); for (const auto& tag : tags) imported.push_back(legacy_tag_binding(normalize_tag(tag, true), "Imported from a direct legacy _tags assignment.")); - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); state.bindings = std::move(imported); state.lineage.clear(); } @@ -510,7 +520,7 @@ std::vector Shape::explain_tag(std::string_view tag, TagScope scope) cons // Metadata and runtime values // --------------------------------------------------------------------------- void Shape::set_metadata(std::string key, Value value) { - entity_->state().set_value(false, std::move(key), std::move(value)); + writable_state().set_value(false, std::move(key), std::move(value)); } bool Shape::has_metadata_key(std::string_view key) const { @@ -519,7 +529,7 @@ bool Shape::has_metadata_key(std::string_view key) const { } void Shape::set_metadata_deferred(std::string_view key, const Value& value) { - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); if (state.has_key(false, key)) state.metadata().set(std::string(key), value); else @@ -527,7 +537,7 @@ void Shape::set_metadata_deferred(std::string_view key, const Value& value) { } void Shape::set_metadata_recipe(std::string_view key, unsigned char recipe, const Value& args) { - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); if (state.has_key(false, key)) state.metadata().set(std::string(key), PackedValue::from_recipe(recipe, args).unpack()); else @@ -535,7 +545,7 @@ void Shape::set_metadata_recipe(std::string_view key, unsigned char recipe, cons } void Shape::set_runtime_deferred(std::string_view key, const Value& value) { - SemanticState& state = entity_->state(); + SemanticState& state = writable_state(); if (state.has_key(true, key)) state.runtime().set(std::string(key), value); else @@ -559,7 +569,7 @@ const Value& Shape::metadata() const { } void Shape::set_runtime(std::string key, Value value) { - entity_->state().set_value(true, std::move(key), std::move(value)); + writable_state().set_value(true, std::move(key), std::move(value)); } Value Shape::get_runtime(std::string_view key, Value fallback) const { @@ -585,12 +595,13 @@ void Shape::copy_tag_state_from(const Shape& source) { const SemanticState* from = source.entity_->state_if(); if (from == nullptr) { if (SemanticState* to = entity_->sem.get()) { + registry_->touch(); to->bindings.clear(); to->lineage.clear(); } return; } - SemanticState& to = entity_->state(); + SemanticState& to = writable_state(); to.bindings = from->bindings; to.lineage = from->lineage; if (any_downward(to.bindings)) @@ -602,7 +613,7 @@ void Shape::copy_tag_state_from(const Shape& source) { void Shape::copy_semantic_state_from(const Shape& source) { copy_tag_state_from(source); const SemanticState* from = source.entity_->state_if(); - SemanticState& to = entity_->state(); + SemanticState& to = writable_state(); to.clear_dictionaries(); if (from == nullptr) return; diff --git a/src/simplecadapi/runtime/cache.py b/src/simplecadapi/runtime/cache.py index e1f55b9c..3558a9d6 100644 --- a/src/simplecadapi/runtime/cache.py +++ b/src/simplecadapi/runtime/cache.py @@ -34,6 +34,8 @@ from collections.abc import Callable, Collection, Iterator, Mapping, Sequence from pathlib import Path from typing import Any +from simplecadapi._cpp import Assembly, Part + from .._glue.notice import say from ._marimo import ( CachedLifecycle, @@ -223,7 +225,8 @@ the kernel is a process that imported it once.""" def _shareable(value: Any) -> bool: """Whether *value* may be handed to a later run as the same object: plain data and the SDK's value types. - Those are functional (an operation returns a new value), so a later cell cannot change what an earlier one made. + Those are functional (an operation returns a new value) except for the semantic state of a shape, which + :func:`_semantic_state` watches; so a later cell cannot change what an earlier one made without the memory noticing. A list or a dict a cell made could be changed by the next cell that reads it, so it is not shared. """ @@ -235,51 +238,26 @@ def _shareable(value: Any) -> bool: return kind.__module__ == "simplecadapi.core" or kind.__module__.startswith("simplecadapi.product.") -_MUTATORS = ("set_metadata", "auto_tag_faces") -_changed: set[int] = set() -"""Ids of values something changed in place (a later cell calling ``set_metadata`` on a value it was given).""" +def _semantic_state(value: Any) -> tuple[int, ...]: + """The semantic revision of every shape inside *value*: what a later cell could change in place. - -def _watch_changes() -> None: - """Note which value a ``set_metadata``/``auto_tag_faces`` call changes, for every SDK type that has them. - - The SDK's values are functional except for these: they change the value they are called on, and a memory that hands - the same object to a later run would hand out the change (the disk copy is a fresh object each time). The ids are - kept in :data:`_changed`; a memory entry holding one of them is not handed out again (a wrong id only costs a read). + The SDK's values are functional except for the semantic state of a shape (tags, bindings, metadata): ``apply_tag``, + ``set_metadata`` and ``auto_tag_faces`` change the shape they are called on, and return the very same object. A + memory that hands the same object to a later run would hand out the change as well (the copy on the disk is a fresh + object each time and has none of it). Each root of shapes counts its writes (``AnyShape._semantic_revision``); an + entry whose numbers moved since it was kept is not handed out again. A Part is its body, an Assembly its + components; reading a shape, or consuming it in an operator, does not count. """ - import functools - - from .. import _cpp - - native = getattr(_cpp, "_native", None) - for kind in vars(native).values() if native is not None else (): - if not isinstance(kind, type): - continue - for name in _MUTATORS: - original = kind.__dict__.get(name) - if original is None or getattr(original, "_sca_watched", False): - continue - - def watched(self, *args, __original=original, **kwargs): - if len(_changed) > 100_000: - _changed.clear() - _changed.add(id(self)) - return __original(self, *args, **kwargs) - - functools.update_wrapper(watched, original) - watched._sca_watched = True # type: ignore[attr-defined] - setattr(kind, name, watched) - - -_watch_changes() - - -def _held(value: Any) -> "Iterator[Any]": - yield value + if hasattr(value, "_semantic_revision"): + return (value._semantic_revision(),) + if isinstance(value, Part): + return _semantic_state(value.body) + if isinstance(value, Assembly): + return tuple(n for component in value.components for n in _semantic_state(component.item)) if isinstance(value, (tuple, frozenset)): - for item in value: - yield from _held(item) + return tuple(n for item in value for n in _semantic_state(item)) + return () class _CellMemory: @@ -292,7 +270,8 @@ class _CellMemory: def __init__(self, limit: int = _MEMORY_ENTRIES) -> None: self._limit = limit - self._entries: "OrderedDict[tuple[int, str, str], tuple[Any, dict[str, Any], dict[str, Any]]]" = OrderedDict() + # (loader, values, meta, the semantic revisions the values had when they were kept) + self._entries: "OrderedDict[tuple[int, str, str], tuple[Any, dict[str, Any], dict[str, Any], tuple]]" = OrderedDict() self._lock = threading.Lock() @staticmethod @@ -305,8 +284,8 @@ class _CellMemory: entry = self._entries.get(key) if entry is None or entry[0] is not loader: # (an id is reused once its loader is gone) return None - if any(id(held) in _changed for value in entry[1].values() for held in _held(value)): - del self._entries[key] # something changed a value in place since it was kept + if tuple(_semantic_state(value) for value in entry[1].values()) != entry[3]: + del self._entries[key] # something changed a shape in place since it was kept return None self._entries.move_to_end(key) return entry[1], entry[2] @@ -316,9 +295,9 @@ class _CellMemory: if stateful or not all(_shareable(value) for value in values.values()): return key = self._key(loader, key) - _changed.difference_update(id(held) for value in values.values() for held in _held(value)) + revisions = tuple(_semantic_state(value) for value in values.values()) with self._lock: - self._entries[key] = (loader, values, meta) + self._entries[key] = (loader, values, meta, revisions) self._entries.move_to_end(key) while len(self._entries) > self._limit: self._entries.popitem(last=False) diff --git a/test/test_cell_memory.py b/test/test_cell_memory.py index 6063a973..5c54ed94 100644 --- a/test/test_cell_memory.py +++ b/test/test_cell_memory.py @@ -265,5 +265,83 @@ class AValueAnotherCellChangedIsNotHandedOutTest(unittest.TestCase): self.assertIsNotNone(self.memory.recall(self.loader, Key("e"))) +class EveryChangeInPlaceIsSeenTest(unittest.TestCase): + """A shape counts the writes to its semantic state; an entry whose counts moved is not handed out again. + + apply_tag changes the shape it is given and returns that very object, so a later cell that tags what it received + (the skill's ``annotate`` block) changes what the producing cell kept. Reading, and consuming a shape in an + operator, change nothing and must keep the entry (otherwise the memory never hits). + """ + + def setUp(self) -> None: + self.memory = _CellMemory(limit=8) + self.loader = object() + + def kept(self, value) -> None: + self.memory.remember(self.loader, Key("e"), {"value": value}, {}) + + def handed_out(self) -> bool: + return self.memory.recall(self.loader, Key("e")) is not None + + def test_apply_tag_on_the_shape_drops_the_entry(self) -> None: + import simplecadapi as scad + + box = scad.make_box_rsolid(2, 2, 2) + self.kept(box) + self.assertTrue(self.handed_out()) + scad.apply_tag(shape=box, tag="role.annotated") + self.assertFalse(self.handed_out()) + + def test_apply_tag_on_a_face_of_the_shape_drops_the_entry(self) -> None: + import simplecadapi as scad + from simplecadapi import ql + + box = scad.make_box_rsolid(2, 2, 2) + self.kept(box) + scad.apply_tag(shape=ql.select(ql.faces().resolve(box)).first(), tag="face.annotated") + self.assertFalse(self.handed_out()) + + def test_a_tag_on_the_body_of_a_part_or_a_component_of_an_assembly_is_seen(self) -> None: + import simplecadapi as scad + + body = scad.make_box_rsolid(2, 2, 2) + part = scad.make_part_rpart(part_id="p", body=body, name="p") + assembly = scad.add_component_rassembly( + scad.make_assembly_rassembly("asm"), part, component_id="c", placement=scad.identity_placement_rplacement() + ) + for held in (part, assembly): + with self.subTest(type(held).__name__): + self.memory.clear() + self.kept(held) + self.assertTrue(self.handed_out()) + scad.apply_tag(shape=body, tag=f"role.{type(held).__name__.lower()}") + self.assertFalse(self.handed_out()) + + def test_reading_and_consuming_a_shape_keeps_the_entry(self) -> None: + import simplecadapi as scad + from simplecadapi import ql + + box = scad.make_box_rsolid(20, 20, 20) + tool = scad.make_cylinder_rsolid(3, 30) + self.kept(box) + scad.list_tags(shape=box) + box.get_volume() + ql.select(ql.faces().resolve(box)).all() + scad.cut_rsolid(box, tool) + scad.union_rsolid(box, tool) + scad.translate_shape(box, (1, 2, 3)) + scad.make_part_rpart(part_id="q", body=box, name="q") + scad.fillet_rsolid(solid=box, edges=ql.edges().where(ql.prop("geom.length", ">=", 19.9)).take(2), radius=1.0) + self.assertTrue(self.handed_out()) + + def test_a_tag_applied_before_the_value_was_kept_is_part_of_it(self) -> None: + import simplecadapi as scad + + box = scad.make_box_rsolid(2, 2, 2) + scad.apply_tag(shape=box, tag="role.before") + self.kept(box) + self.assertTrue(self.handed_out()) + + if __name__ == "__main__": unittest.main()