From 6fb19768e224b4f90452b8ffd9e55cd7f45ca24e Mon Sep 17 00:00:00 2001 From: sean-parent Date: Fri, 13 Nov 2026 18:09:08 -0800 Subject: [PATCH] Make ownership traversal linear and memoize checked comparisons Compile reusable ownership ranges, scan them with a fixed-capacity cursor, and reuse successful shape and ownership comparisons throughout checked operations. Add direct work-count regressions without replacing global allocation functions and simplify the complexity contracts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- include/cel/runtime/value.hpp | 75 +++++++++-------- include/cel/runtime/value_type.hpp | 3 + src/type_ops.hpp | 87 +++++++++++++++++-- src/value.cpp | 69 ++++++++------- src/value_ops.hpp | 32 +++---- src/value_type.cpp | 130 +++++++++++++++++++++-------- tests/resource_test.cpp | 97 +++++++++++++++++++++ tests/value_test.cpp | 108 ++++++++++++++++++++++++ 8 files changed, 478 insertions(+), 123 deletions(-) diff --git a/include/cel/runtime/value.hpp b/include/cel/runtime/value.hpp index 70b6bc6..a3ee8e6 100644 --- a/include/cel/runtime/value.hpp +++ b/include/cel/runtime/value.hpp @@ -39,17 +39,20 @@ struct concrete_adapter; /// Holds any type representable by CEL, including client-defined types. /// -/// In the costs below, B counts canonical bytes copied or initialized, F visited fixed -/// fields or native elements, N visited array owners, and L sums ownership-slot selection -/// costs: O(sum of log(field count + 1) along each selected aggregate path). -/// F counts logical visits even when their byte extent is zero. -/// C counts opaque clone/destruction and released executable costs, including client -/// capture destruction; D counts released metadata nodes, edges, -/// and identity/name bytes. W = B + F + N + L + C + D is the affected payload work. -/// Owned result storage includes owner records and newly created metadata, not just byte -/// buffers. Result storage is separate from auxiliary space. Native adapters may use call space -/// proportional to concrete nesting; canonical cloning and retirement use no nesting- -/// dependent call space or allocated traversal storage beyond cloned result owners. +/// Value area includes canonical bytes, logical elements even when zero-sized, and owned +/// runtime objects. Released area also includes executable and type metadata: nodes, edges, +/// and stored names. Owned result storage includes owner records, not just byte buffers. +/// Held client types retain their own copy and destruction costs. +/// +/// Checked operations additionally compare distinct expected/actual descriptor pairs. +/// Across one operation, this costs expected O(P + E + S) time and O(P + E) auxiliary +/// space for compared pairs P, their edges E, and compared identity/name bytes S. +/// This need not be linear in the separate descriptor graph areas. +/// +/// Copies share immutable ownership plans with metadata linear in descriptor edges. +/// Canonical cloning and retirement use constant runtime auxiliary space and no traversal +/// allocations beyond cloned result owners. Native adapters may use call space proportional +/// to concrete nesting; held client operations retain their own space requirements. /// /// Example: `auto number = value::from(2.0); auto copy = number;`. /// @@ -96,8 +99,8 @@ class value { /// Leaves inputs unchanged. /// Throws std::invalid_argument for wrong arity or incompatible shape/ownership operations. /// Failure destroys every initialized child without allocating rollback copies. - /// Complexity: O(W + M) expected time and new owned result storage, where M is - /// the sum of complete compatibility comparison costs; comparisons use auxiliary space. + /// Complexity: linear in combined field area, plus the class's checked-comparison costs; + /// new owned result storage. static value aggregate(value_type type, std::span fields); /// Takes already-owned boundary children without cloning their mutable payloads. /// @@ -105,8 +108,8 @@ class value { /// Throws std::invalid_argument for wrong shapes; failure releases completed transfers. /// Remaining sources retain ownership. /// Throws std::overflow_error for canonical extent overflow before consuming children. - /// Complexity: O(B + F + M + D) expected time and packed result storage, with M - /// the sum of compatibility comparison costs; failure also retires consumed payloads. + /// Complexity: linear in transferred outer bytes, element count, and released metadata, + /// plus checked-comparison costs; packed result storage. Failure also retires consumed area. static value array_owned(value_type element, std::span children); /// Borrows a public owner's canonical bytes. /// @@ -145,7 +148,7 @@ class value { /// /// \pre type is a tuple or record; count <= arity and exactly that prefix consists /// of valid owned representations in data. - /// Complexity: O(F + N + L + C + D) time and O(1) runtime auxiliary space. + /// Complexity: linear in field count and retired area; O(1) runtime auxiliary space. static void destroy_fields(const value_type& type, std::byte* data, std::size_t count) noexcept; public: @@ -157,14 +160,14 @@ class value { /// /// Runtime retirement uses no nesting-dependent call space; client capture destructors /// retain their own costs and behavior. - /// Complexity: O(F + N + L + C + D) time and O(1) runtime auxiliary space. + /// Complexity: linear in released area; O(1) runtime auxiliary space. /// /// See the class's shared copying example. ~value(); /// Copies the source under the class's aggregate and callable copy semantics. /// /// Leaves the source unchanged; failure releases every acquired owner. - /// Complexity: O(W) time and new owned result storage, with O(1) runtime auxiliary + /// Complexity: linear in source area, with new owned result storage and O(1) runtime auxiliary /// space excluding opaque operations. /// /// See the class's shared copying example. @@ -177,14 +180,14 @@ class value { /// /// Leaves other unchanged; self-assignment leaves this value unchanged. /// Failure leaves this unchanged without copying its prior payload. - /// Complexity: O(source/old W) time and new source-sized result storage; runtime - /// auxiliary space is O(1), excluding opaque operations. + /// Complexity: linear in source and released area, with new source-sized result storage; + /// runtime auxiliary space is O(1), excluding opaque operations. /// /// Example: `auto target = value{}; target = source;`. value& operator=(const value& other); /// Releases old ownership, transfers other, and leaves other as unit; self-move is unchanged. /// - /// Complexity: O(old F + N + L + C + D) time and O(1) runtime auxiliary space. + /// Complexity: linear in released area; O(1) runtime auxiliary space. /// /// Example: `auto target = value{}; target = std::move(source); // source is unit.` value& operator=(value&& other) noexcept; @@ -197,7 +200,7 @@ class value { /// Copies a concrete leaf or recursively nested owning vector/tuple into a runtime value. /// /// Leaves source unchanged; pointer members in opaque leaves do not confer pointee ownership. - /// Complexity: O(B + F + first-use native_type construction) time and owned result + /// Complexity: linear in source area, plus first-use native_type construction; owned result /// storage; O(concrete nesting depth) adapter call space. /// /// Example: `auto numbers = value::from(std::vector{1.0, 2.0});`. @@ -210,8 +213,8 @@ class value { /// Returned vectors and tuples own independent mutable payloads; leaf pointers remain pointers. /// /// Throws std::invalid_argument if the complete concrete type does not match. - /// Complexity: O(B + F + M + first-use native_type construction) expected time and - /// owned result storage, where M is the same_shape comparison cost; comparison + /// Complexity: linear in result area, plus same_shape comparison and first-use + /// native_type construction; owned result storage. Comparison /// auxiliary space and O(concrete nesting depth) adapter call space are additional. /// /// Example: `value::from(2.0).as() == 2.0`. @@ -225,8 +228,8 @@ class value { /// /// Throws std::invalid_argument for incompatible elements, releasing earlier copies. /// Throws std::overflow_error if count times canonical element extent overflows. - /// Complexity: O(W + M) expected time and owned result storage, where M sums - /// element compatibility comparison costs; comparisons require auxiliary space. + /// Complexity: linear in combined element area and element count, plus the class's + /// checked-comparison costs across the entire construction; owned result storage. /// /// Example: `auto empty = value::array(value_type::leaf(), {});`. static value array(value_type element, std::span elements); @@ -235,8 +238,8 @@ class value { /// Leaves input fields unchanged, with the class's copy semantics for every component. /// /// Throws std::overflow_error for layout overflow. - /// Complexity: O(W + field count) time and owned result storage; O(field count) - /// temporary descriptor space, in addition to opaque operation costs. + /// Complexity: linear in combined field area and field count; owned result storage and O(field + /// count) temporary descriptor space, in addition to opaque operation costs. /// /// Example: `auto unit = value::tuple({});`. static value tuple(std::span fields); @@ -247,8 +250,8 @@ class value { /// Throws std::invalid_argument for a non-record, wrong arity, or incompatible fields. /// Field compatibility includes complete shape and ownership operations. /// Failure releases earlier children without leaking resources. - /// Complexity: O(W + M) expected time and owned result storage, with M the sum of - /// field compatibility comparison costs; comparisons require auxiliary space. + /// Complexity: linear in combined field area and field count, plus the class's + /// checked-comparison costs across all fields; owned result storage. /// /// Example: `auto empty = value::record(value_type::record("sample", {}), {});`. static value record(value_type type, std::span fields); @@ -273,7 +276,7 @@ class value { /// Leaves this value unchanged, including on failure. /// /// Throws std::out_of_range for an invalid index, std::invalid_argument for non-composites. - /// Complexity: O(child W) time and owned result storage; O(1) runtime auxiliary + /// Complexity: linear in child area, with owned result storage and O(1) runtime auxiliary /// space excluding opaque operations. /// /// Example: `value::from(std::vector{2.0}).at(0).as() == 2.0`. @@ -284,8 +287,8 @@ class value { /// /// Throws std::out_of_range for invalid index, std::invalid_argument for shape mismatch /// or non-composites. Failure leaves the value unchanged; no rollback copy is needed. - /// Complexity: O(old/new child W + M) expected time and new child result storage, - /// where M is the compatibility comparison cost; comparison auxiliary space is additional. + /// Complexity: linear in replaced and replacement child area, plus the class's + /// checked-comparison costs; new child result storage. /// /// Example: `auto a = value::from(std::vector{1.0}); a.set(0, value::from(2.0));`. void set(std::size_t index, const value& replacement); @@ -293,7 +296,7 @@ class value { /// /// Leaves this value unchanged, including on failure. /// Throws std::invalid_argument for a non-record or missing name. - /// Complexity: linear field-name lookup, including compared name bytes, plus O(child W) + /// Complexity: linear field-name lookup, including compared name bytes, plus linear child-area /// copying time and child result storage; O(1) runtime auxiliary space excluding opaque /// operations. /// @@ -304,8 +307,8 @@ class value { /// Throws std::invalid_argument for non-record/missing name or shape mismatch. /// Follows set's ownership compatibility, copy semantics, and unchanged-on-failure guarantee. /// Complexity: linear field-name lookup, including compared name bytes, plus - /// O(old/new child W + M) expected replacement time and new child result storage, - /// where M is compatibility comparison cost; comparison auxiliary space is additional. + /// replacement work in old/new child area and the class's checked-comparison costs; + /// new child result storage. /// /// See the class example for a complete record and field replacement. void set_field(std::string_view name, const value& replacement); diff --git a/include/cel/runtime/value_type.hpp b/include/cel/runtime/value_type.hpp index af9b09b..ebd61cf 100644 --- a/include/cel/runtime/value_type.hpp +++ b/include/cel/runtime/value_type.hpp @@ -55,6 +55,9 @@ struct type_access; /// Access to one descriptor must not race its replacement or destruction. /// Factories retain component descriptors and copy supplied names; input spans and strings /// need not outlive construction. +/// Ownership sequences share descendant ranges instead of expanding a table at every node. +/// Across a descriptor graph, plan construction and metadata are linear in nodes and edges, +/// plus copied identity/name bytes; record-name validation has expected linear time. /// /// See value's shared example for record construction and descriptor copying. /// Example: `auto numbers = value_type::array(value_type::leaf()); auto copy = numbers;`. diff --git a/src/type_ops.hpp b/src/type_ops.hpp index 045a6fc..e394531 100644 --- a/src/type_ops.hpp +++ b/src/type_ops.hpp @@ -2,11 +2,17 @@ #ifndef CEL_RUNTIME_TYPE_OPS_HPP #define CEL_RUNTIME_TYPE_OPS_HPP +#include #include +#include +#include +#include +#include +#include namespace cel::detail { -/// A borrowed ownership-carrying slot in canonical fixed-aggregate bytes. +/// A borrowed carrier or reusable ownership subrange in canonical fixed-aggregate bytes. /// /// The containing descriptor retains type; its views must remain valid while the slot is used. struct ownership_slot { @@ -36,6 +42,39 @@ struct opaque_ownership { }; static_assert(std::is_trivially_copyable_v); +/// Hashes borrowed immutable descriptor identity pairs. +struct plan_pair_hash { + /// Combines the two metadata identities. + std::size_t operator()( + const std::pair& pair) const noexcept; +}; + +/// Memoizes successful shape and ownership checks for one checked operation. +/// +/// Retains compared descriptors, including consumed inputs, until the operation ends. +/// Shape and ownership successes are independent; failed comparisons are never cached. +/// For an operation ending at its first mismatch, complexity is expected O(P + E + S) +/// total comparison time and O(P + E) auxiliary space for distinct compared pairs P, +/// their edges E, and compared name bytes S. +class compatibility_context { + friend struct type_access; + using pair = std::pair; + std::unordered_set _semantic; + std::unordered_set _operations; + std::vector _retained; + std::size_t _compared = 0; + +public: + /// Starts an empty operation-local memo without allocating. + compatibility_context() = default; + /// Checks complete shapes and ownership operations and returns the newly compared pair count. + /// + /// Reuses successful pair checks; shape and operation comparisons count separately. + /// Throws std::invalid_argument on mismatch, leaving inputs unchanged. + /// Failed checks do not authorize a later comparison. + std::size_t require(const value_type& expected, const value_type& actual); +}; + /// Trusted access to immutable type identity and ownership capabilities. /// /// These operations do not implement callable execution or concrete closure bodies. @@ -82,6 +121,14 @@ struct type_access { /// visited plan pairs P, their edges E, and compared identity/name bytes S. /// S is zero for operation-only comparisons; identical plans compare in O(1). static bool compare_plans(const value_type& expected, const value_type& actual, bool semantic); + /// Compares plans using an operation's successful checks for the selected comparison. + /// + /// \pre For operation-only comparison, complete semantic shapes already match. + /// Follows compare_plans's contract and retains any newly compared descriptors. + static bool compare_plans(const value_type& expected, + const value_type& actual, + bool semantic, + compatibility_context& context); /// Returns the number of direct owning carriers in fixed canonical bytes. /// /// Arrays/callables count as one carrier; their separately owned children are not counted. @@ -90,13 +137,39 @@ struct type_access { /// /// Client leaves and callables are not admitted, including inside empty arrays/full ranges. static bool parameter_allowed(const value_type& type) noexcept; - /// Locates an ownership slot by ordinal without recursion or allocation. + /// Borrows the compiled ownership sequence's immediate reusable ranges. + /// + /// Scalars and carriers have no subranges. Single-range paths are collapsed; + /// branching sequences put a largest carrier-count range last. + /// The view remains valid while type's metadata is retained. + static std::span ownership_ranges(const value_type& type) noexcept; +}; + +/// Scans a compiled ownership sequence without allocation or nesting-dependent call space. +/// +/// Borrows the source descriptor for its lifetime. Each next() performs one constant-time +/// transition; the complete scan takes O(1 + carrier count) time and O(1) auxiliary space. +class ownership_cursor { + /// A borrowed sequence position and its byte offset from the traversal root. + struct position { + const value_type* type; + std::size_t offset; + std::size_t next = 0; + }; + // Every pending non-final descent halves the carrier count. Final descents replace + // their frame, so machine-word width bounds the stack even for skewed descriptors. + std::array::digits + 1> _pending; + std::size_t _size = 0; + +public: + /// Starts a traversal of type's direct ownership carriers. + explicit ownership_cursor(const value_type& type) noexcept; + /// Reports whether every carrier has been emitted. + bool empty() const noexcept { return _size == 0; } + /// Advances one traversal transition, returning a slot only when it reaches a carrier. /// - /// \pre ordinal < resources(type). - /// The result borrows metadata retained by type. - /// Complexity: O(sum of log(field count + 1) along the selected aggregate path) - /// time and O(1) auxiliary space. - static ownership_slot resource(const value_type& type, std::size_t ordinal) noexcept; + /// \pre The cursor is not empty. + std::optional next() noexcept; }; /// Validates complete type-level cloning and destruction capabilities. diff --git a/src/value.cpp b/src/value.cpp index 0cff834..2196e89 100644 --- a/src/value.cpp +++ b/src/value.cpp @@ -89,34 +89,37 @@ struct array_owner { /// Destroys initialized ownership without allocating or consuming nesting-dependent stack. /// /// Client operations retain their own costs and behavior. - /// Complexity: O(N + L + C + D) time and O(1) runtime auxiliary space, with costs as in value. + /// Complexity: linear in released value area; O(1) runtime auxiliary space. ~array_owner(); }; -/// Retires a source-order ownership-carrier prefix into enclosing retirement operations. +/// Retires a traversal-order ownership-carrier prefix into enclosing retirement operations. /// /// \pre Exactly the first count ownership carriers in data are valid and exclusively /// owned; count <= type_access::resources(type). pending and queue remain alive until /// their scheduled owners retire. /// Source carrier ownership is retired; array storage is released when pending is drained. -/// Complexity: O(L + C) time and O(1) runtime auxiliary space, with costs as in value. +/// Complexity: linear in carrier count, plus held destruction costs; O(1) runtime auxiliary space. void retire_resources(const value_type& type, std::byte* data, std::size_t count, array_owner*& pending, retirement_queue& queue) noexcept { - // Cached ownership ranks skip every non-owning scalar and zero-sized subtree. + ownership_cursor cursor(type); + // Scan the compiled sequence once, stopping at the initialized carrier prefix. while (count != 0) { - const auto slot = type_access::resource(type, --count); - auto* address = byte_at(data, slot.offset); - if (slot.type->kind() == type_kind::array) { + const auto slot = cursor.next(); + if (!slot) continue; + --count; + auto* address = byte_at(data, slot->offset); + if (slot->type->kind() == type_kind::array) { auto* node = read_array(address).owner; node->pending_next = pending; pending = node; - } else if (callable_access::installed(*slot.type)) { + } else if (callable_access::installed(*slot->type)) { callable_access::retire(address, queue); } else { - const auto operations = type_access::operations(*slot.type); + const auto operations = type_access::operations(*slot->type); assert(operations.destroy); if (!operations.destroy) std::terminate(); operations.destroy(address); @@ -129,8 +132,8 @@ void retire_resources(const value_type& type, /// \pre owner has exclusive valid prefix/partial ownership; pending and queue remain alive /// until their scheduled owners retire. /// Leaves no initialized element ownership in owner. -/// Complexity: O(L + C) time and O(1) runtime auxiliary space, with costs as in value; -/// scalar elements require no per-element retirement. +/// Complexity: linear in initialized carriers, plus held destruction costs; O(1) runtime auxiliary +/// space; scalar elements require no per-element retirement. void retire_elements(array_owner& owner, array_owner*& pending, retirement_queue& queue) noexcept { const auto resources = type_access::resources(owner.element); const auto stride = owner.element.byte_layout().size; @@ -153,7 +156,7 @@ void retire_elements(array_owner& owner, array_owner*& pending, retirement_queue /// \pre pending links uniquely owned valid array nodes with discardable initialized /// prefixes; queue remains alive until scheduled executable owners retire. /// No runtime traversal allocation or nesting-dependent call space is used. -/// Complexity: O(N + L + C + D) time and O(1) runtime auxiliary space, with costs as in value. +/// Complexity: linear in released value area; O(1) runtime auxiliary space. void drain_arrays(array_owner*& pending, retirement_queue& queue) noexcept { // Detach each node before retiring its descendants and releasing its aligned bytes. while (pending) { @@ -179,20 +182,23 @@ array_owner::~array_owner() { /// completed <= type_access::resources(type); pending retains uniquely owned partial clones. /// On success completed counts all direct carriers and pending retains descendants still /// needing cloning. Failure preserves a discardable prefix counted by completed. -/// Complexity: O(B + N + L + C) time and new owned result storage, with costs as in value; -/// O(1) runtime auxiliary space excluding opaque operations. +/// Complexity: linear in carriers and copied array bytes, plus held clone costs; new owned result +/// storage; O(1) runtime auxiliary space excluding opaque operations. void clone_resources(const value_type& type, const std::byte* source, std::byte* destination, std::size_t& completed, array_owner*& pending) { const auto resources = type_access::resources(type); + ownership_cursor cursor(type); + std::size_t ordinal = 0; // Construct one independent carrier at a time without recursively cloning child arrays. while (completed != resources) { - const auto slot = type_access::resource(type, completed); - const auto* input = byte_at(source, slot.offset); - auto* output = byte_at(destination, slot.offset); - if (slot.type->kind() == type_kind::array) { + const auto slot = cursor.next(); + if (!slot || ordinal++ < completed) continue; + const auto* input = byte_at(source, slot->offset); + auto* output = byte_at(destination, slot->offset); + if (slot->type->kind() == type_kind::array) { const auto* original = read_array(input).owner; assert(original->initialized == original->count && original->partial_resources == 0); auto copy = std::make_unique(original->element, original->count); @@ -204,7 +210,7 @@ void clone_resources(const value_type& type, write_carrier(output, owner); pending = owner; } else { - const auto operations = type_access::operations(*slot.type); + const auto operations = type_access::operations(*slot->type); if (!operations.clone) throw std::invalid_argument("callable ownership is not installed"); operations.clone(input, output); @@ -215,9 +221,11 @@ void clone_resources(const value_type& type, void clone_payload(const value_type& type, const std::byte* source, std::byte* destination) { // Reject deferred direct carriers before reading any source representation. - for (std::size_t i = 0; i != type_access::resources(type); ++i) { - const auto slot = type_access::resource(type, i); - if (slot.type->kind() == type_kind::callable && !type_access::operations(*slot.type).clone) + ownership_cursor cursor(type); + while (!cursor.empty()) { + const auto slot = cursor.next(); + if (slot && slot->type->kind() == type_kind::callable && + !type_access::operations(*slot->type).clone) throw std::invalid_argument("callable ownership is not installed"); } const auto extent = type.byte_layout().size; @@ -279,7 +287,7 @@ const value_type& child_type(const value_type& type, std::size_t index) { /// /// \pre type is a tuple, record, or range, count <= arity, and exactly that prefix is /// valid owned data, exclusively accessible for retirement. -/// Complexity: O(F + N + L + C + D) time and O(1) runtime auxiliary space, with costs as in value. +/// Complexity: linear in field count and released value area; O(1) runtime auxiliary space. void destroy_prefix(const value_type& type, std::byte* data, std::size_t count) noexcept { while (count != 0) { --count; @@ -306,8 +314,7 @@ struct owned_payload { /// Destroys initialized ownership and releases outer storage without recursion/allocation. /// /// Client operations retain their own costs and behavior. - /// Complexity: O(F + N + L + C + D) time and O(1) runtime auxiliary space, with costs as in - /// value. + /// Complexity: linear in field count and released value area; O(1) runtime auxiliary space. ~owned_payload() { if (type.kind() == type_kind::tuple || type.kind() == type_kind::record || type.kind() == type_kind::range) @@ -493,9 +500,10 @@ value value::array_owned(value_type element, std::span children) { auto result = std::make_unique(value_type::array(element)); auto owner = std::make_unique(element, children.size()); const auto stride = element.byte_layout().size; + detail::compatibility_context comparisons; // Transfer each canonical element and retire its public boundary owner. for (auto& child : children) { - detail::require_compatible(element, child.type()); + comparisons.require(element, child.type()); if (stride != 0) std::memcpy(detail::byte_at(owner->bytes.data(), owner->initialized * stride), raw_data(child), stride); @@ -511,9 +519,10 @@ value value::array(value_type element, std::span elements) { auto result = std::make_unique(value_type::array(element)); auto owner = std::make_unique(element, elements.size()); const auto stride = element.byte_layout().size; + detail::compatibility_context comparisons; // Clone directly into packed canonical element bytes, tracking only the initialized prefix. for (const auto& child : elements) { - detail::require_compatible(element, child.type()); + comparisons.require(element, child.type()); detail::clone_payload(element, raw_data(child), detail::byte_at(owner->bytes.data(), owner->initialized * stride)); ++owner->initialized; @@ -526,11 +535,12 @@ value value::aggregate(value_type type, std::span fields) { if (type.offsets().size() != fields.size()) throw std::invalid_argument("wrong aggregate arity"); auto result = std::make_unique(std::move(type)); + detail::compatibility_context comparisons; // Completed children are independently owned; later failures destroy precisely that prefix. for (const auto& child : fields) { const auto index = result->initialized; const auto& expected = detail::child_type(result->type, index); - detail::require_compatible(expected, child.type()); + comparisons.require(expected, child.type()); detail::clone_payload(expected, raw_data(child), detail::byte_at(result->bytes.data(), result->type.offsets()[index])); ++result->initialized; @@ -571,7 +581,8 @@ void value::set(std::size_t index, const value& replacement) { if (index >= size()) throw std::out_of_range("child index out of bounds"); const auto& expected = type().kind() == type_kind::array ? type().element() : detail::child_type(type(), index); - detail::require_compatible(expected, replacement.type()); + detail::compatibility_context comparisons; + comparisons.require(expected, replacement.type()); value copy(replacement); std::byte* destination = nullptr; if (type().kind() == type_kind::array) { diff --git a/src/value_ops.hpp b/src/value_ops.hpp index 1c3f121..7ac2147 100644 --- a/src/value_ops.hpp +++ b/src/value_ops.hpp @@ -27,8 +27,8 @@ class array_builder { /// Retires the initialized suffix with existing canonical ownership operations. /// /// Never allocates runtime traversal storage or recurses with ownership nesting. - /// Complexity: O(F + N + L + C + D) time, with costs as in value, including the - /// suffix's element count in F; O(1) runtime auxiliary space. + /// Complexity: linear in suffix element count and released value area; + /// O(1) runtime auxiliary space. ~array_builder(); /// Disallows duplicated array ownership. array_builder(const array_builder&) = delete; @@ -64,8 +64,8 @@ class array_builder { /// nested inside arrays; the broader rejection case needs resolution. /// Failure destroys every constructed child; destination remains uninitialized. /// -/// Complexity: O(B + N + L + C + D) time and new owned result storage, with costs -/// as in value; O(1) runtime auxiliary space excluding opaque operations. +/// Complexity: linear in source value area, plus held clone/destruction costs; +/// new owned result storage and O(1) runtime auxiliary space excluding opaque operations. /// Canonical traversal and cleanup use no nesting-dependent call space. void clone_payload(const value_type& type, const std::byte* source, std::byte* destination); @@ -75,8 +75,8 @@ void clone_payload(const value_type& type, const std::byte* source, std::byte* d /// accessible for retirement. /// Never allocates or throws. Bytewise transfer must retire the source without this call. /// Runtime retirement uses no nesting-dependent call space; client operations retain their costs. -/// Complexity: O(N + L + C + D) time and O(1) runtime auxiliary space, with costs as -/// in value. Scalar arrays require no per-element retirement. +/// Complexity: linear in retired value area, plus held destruction costs; +/// O(1) runtime auxiliary space. Scalar arrays require no per-element retirement. void destroy_payload(const value_type& type, std::byte* data) noexcept; /// Retires a complete payload into an enclosing runtime executable retirement operation. /// @@ -84,7 +84,7 @@ void destroy_payload(const value_type& type, std::byte* data) noexcept; /// accessible for retirement; queue remains alive until enqueued owners retire. /// Retires array storage now and schedules installed executable owners with queue. /// Never allocates runtime traversal storage or recurses with ownership nesting. -/// Complexity: O(N + L + C + D) time and O(1) runtime auxiliary space, with costs as in value. +/// Complexity: linear in retired value area; O(1) runtime auxiliary space. void destroy_payload(const value_type& type, std::byte* data, retirement_queue& queue) noexcept; /// Trusted access between public owners and canonical raw representations. @@ -96,14 +96,14 @@ struct value_access { /// \pre owner is exclusively accessible and queue remains alive until enqueued owners retire. /// Leaves owner as source unit and releases its outer bytes and metadata reference. /// Never allocates runtime traversal storage or recurses with ownership nesting. - /// Complexity: O(N + L + C + D) time and O(1) runtime auxiliary space, with costs as in value. + /// Complexity: linear in released value area; O(1) runtime auxiliary space. static void retire(value& owner, retirement_queue& queue) noexcept; /// Transfers canonical ownership into a caller-provided uninitialized extent. /// /// \pre destination is aligned, disjoint, and large enough for owner.type(); owner /// is exclusively accessible and the destination retains complete destruction metadata. /// Leaves owner unit and does not destroy the transferred payload. - /// Complexity: O(outer canonical bytes + released metadata D) time and O(1) auxiliary + /// Complexity: O(outer canonical bytes + released metadata area) time and O(1) auxiliary /// space; no allocation. static void release_to(value& owner, std::byte* destination) noexcept; /// Acquires outer storage and transfers a canonical owner without cloning its children. @@ -120,8 +120,8 @@ struct value_access { /// \pre data is a readable valid owned representation of type whose descendants /// remain valid and unchanged during copying. /// Callable code retains explicit reference semantics; failure releases acquired owners. - /// Complexity: O(B + N + L + C + D) time and new owned result storage, with costs - /// as in value; O(1) runtime auxiliary space excluding opaque operations. + /// Complexity: linear in source value area, plus held clone/destruction costs; + /// new owned result storage and O(1) runtime auxiliary space excluding opaque operations. static value copy(const value_type& type, const std::byte* data); /// Takes uniquely owned boundary elements into packed canonical storage. /// @@ -129,9 +129,9 @@ struct value_access { /// Throws std::invalid_argument for shape/operation mismatch, destroying completed transfers. /// Remaining sources retain ownership. /// Throws std::overflow_error for canonical extent overflow before consuming sources. - /// Complexity: O(B + F + M + D) expected time and packed result storage, with costs - /// as in value and M the sum of compatibility comparison costs; comparisons use - /// auxiliary space. Failure also retires consumed payloads. + /// Complexity: linear in transferred outer bytes, element count, and released metadata, + /// plus value's operation-wide checked-comparison costs; packed result storage. + /// Failure also retires consumed payloads. static value take_array(value_type element, std::span children); /// Returns a packed array's logical length without acquiring ownership. /// @@ -145,8 +145,8 @@ struct value_access { /// The destination retains complete destruction metadata. /// Source ownership is retired on return without cloning the selected child. /// Source outer bytes remain caller-owned; separately owned array storage is released. - /// Complexity: O(selected outer bytes + sibling F + N + L + C + D) time and - /// O(1) runtime auxiliary space, with costs as in value. + /// Complexity: linear in selected outer bytes, sibling count, and retired value area; + /// O(1) runtime auxiliary space. static void project(const value_type& type, std::byte* source, std::size_t index, diff --git a/src/value_type.cpp b/src/value_type.cpp index a88799f..5d6e04a 100644 --- a/src/value_type.cpp +++ b/src/value_type.cpp @@ -27,8 +27,9 @@ void require_ownership(const value_type& type) { /// Immutable complete semantic metadata after publication. struct type_plan { - // [knowledge] Fields and offsets are canonical and category-appropriate. resource_ends - // contains cumulative source-order carrier counts; predicate caches include nested types. + // [knowledge] Fields and offsets are canonical and category-appropriate. ownership + // borrows retained descendants, collapses unary paths, and puts a largest range last. + // Rebuild these borrowed ranges whenever copied fields are rebound. // Only dying, uniquely owned plans may use release_next or otherwise mutate published data. type_kind kind = type_kind::tuple; // Identifies the shape. layout bytes{0, 1}; // Describes its canonical representation. @@ -38,7 +39,7 @@ struct type_plan { std::type_index leaf{typeid(void)}; // Identifies a concrete leaf. std::vector fields; // Owns ordered fields or callable parameters. std::vector offsets; // Owns ordered aggregate offsets. - std::vector resource_ends; // Caches cumulative source-order carrier counts. + std::vector ownership; // Shares sublayouts without expanding descendants. std::vector names; // Owns record field names. std::string identity; // Owns nominal record identity. std::optional element; // Retains array/range element identity. @@ -48,16 +49,40 @@ struct type_plan { std::shared_ptr release_next; // Links only dying, uniquely owned plans. }; -/// A hash function for immutable metadata identity pairs. -struct plan_pair_hash { - /// Combines pointer identities for immutable plan-pair lookup. - std::size_t operator()( - const std::pair& pair) const noexcept { - const auto a = std::hash{}(pair.first); - const auto b = std::hash{}(pair.second); - return a ^ (b + std::size_t{0x9e3779b9} + (a << 6U) + (a >> 2U)); +/// Compiles reusable carrier ranges from complete canonical fields. +/// +/// \pre plan is unpublished and its fields and offsets agree. +/// Complexity: O(field count) time and added range metadata; descendants are not expanded. +void compile_ownership(type_plan& plan) { + plan.ownership.clear(); + std::size_t largest = 0; + std::size_t largest_count = 0; + // Borrow normalized child ranges instead of copying their transitive slot sequences. + for (std::size_t i = 0; i != plan.fields.size(); ++i) { + const auto& field = plan.fields[i]; + const auto count = type_access::resources(field); + if (count == 0) continue; + ownership_slot range{&field, plan.offsets[i]}; + const auto children = type_access::ownership_ranges(field); + if (children.size() == 1) { + range.type = children.front().type; + range.offset += children.front().offset; + } + if (count > largest_count) { + largest = plan.ownership.size(); + largest_count = count; + } + plan.ownership.push_back(range); } -}; + if (!plan.ownership.empty()) std::swap(plan.ownership[largest], plan.ownership.back()); +} + +std::size_t plan_pair_hash::operator()( + const std::pair& pair) const noexcept { + const auto a = std::hash{}(pair.first); + const auto b = std::hash{}(pair.second); + return a ^ (b + std::size_t{0x9e3779b9} + (a << 6U) + (a >> 2U)); +} value_type type_access::install_callable_ownership(const value_type& signature, opaque_ownership operations) { @@ -137,6 +162,7 @@ value_type type_access::bind_runtime_ownership(const value_type& type, opaque_ow plan->owns = std::all_of(plan->fields.begin(), plan->fields.end(), [](const value_type& field) { return field.owns_values(); }); + compile_ownership(*plan); } bound.emplace(source, value_type(std::move(plan))); } @@ -157,15 +183,29 @@ bool type_access::compatible_operations(const value_type& expected, const value_ bool type_access::compare_plans(const value_type& expected, const value_type& actual, bool semantic) { + compatibility_context context; + return compare_plans(expected, actual, semantic, context); +} + +bool type_access::compare_plans(const value_type& expected, + const value_type& actual, + bool semantic, + compatibility_context& context) { using pair = std::pair; if (expected._plan == actual._plan) return true; + auto& successful = semantic ? context._semantic : context._operations; + const pair roots{expected._plan.get(), actual._plan.get()}; + if (successful.contains(roots)) return true; + context._retained.push_back(expected); + context._retained.push_back(actual); std::vector pending{{expected._plan.get(), actual._plan.get()}}; std::unordered_set visited; // Visit each distinct immutable plan pair once, including shared DAG edges. while (!pending.empty()) { const auto [a, b] = pending.back(); pending.pop_back(); - if (a == b || !visited.insert({a, b}).second) continue; + if (a == b || successful.contains({a, b}) || !visited.insert({a, b}).second) continue; + ++context._compared; if (a->kind != b->kind) return false; if (semantic) { if (a->bytes.size != b->bytes.size || a->bytes.alignment != b->bytes.alignment || @@ -190,6 +230,7 @@ bool type_access::compare_plans(const value_type& expected, for (std::size_t i = 0; i != a->fields.size(); ++i) pending.emplace_back(a->fields[i]._plan.get(), b->fields[i]._plan.get()); } + successful.merge(visited); return true; } @@ -200,38 +241,54 @@ bool type_access::parameter_allowed(const value_type& type) noexcept { return type._plan->parameter; } -ownership_slot type_access::resource(const value_type& type, std::size_t ordinal) noexcept { - assert(ordinal < resources(type)); - const value_type* current = &type; - std::size_t offset = 0; - // Cumulative carrier counts select one source-order path without a traversal stack. - while (current->kind() == type_kind::tuple || current->kind() == type_kind::record) { - const auto& plan = *current->_plan; - const auto found = - std::upper_bound(plan.resource_ends.begin(), plan.resource_ends.end(), ordinal); - const auto i = static_cast(found - plan.resource_ends.begin()); - assert(i < plan.fields.size()); - if (i == plan.fields.size()) std::terminate(); - if (i != 0) ordinal -= plan.resource_ends[i - 1]; - offset += plan.offsets[i]; - current = &plan.fields[i]; +std::span type_access::ownership_ranges(const value_type& type) noexcept { + return type._plan->ownership; +} + +ownership_cursor::ownership_cursor(const value_type& type) noexcept { + if (type_access::resources(type) == 0) return; + const auto ranges = type_access::ownership_ranges(type); + const auto root = ranges.size() == 1 ? ranges.front() : ownership_slot{&type, 0}; + _pending[_size++] = {root.type, root.offset}; +} + +std::optional ownership_cursor::next() noexcept { + assert(!empty()); + auto& current = _pending[_size - 1]; + const auto ranges = type_access::ownership_ranges(*current.type); + if (ranges.empty()) { + const ownership_slot slot{current.type, current.offset}; + --_size; + return slot; } - assert(current->kind() == type_kind::array || current->kind() == type_kind::callable); - return {current, offset}; + const auto range = ranges[current.next++]; + const auto offset = current.offset + range.offset; + if (current.next == ranges.size()) --_size; + assert(_size < _pending.size()); + _pending[_size++] = {range.type, offset}; + return std::nullopt; } void require_compatible(const value_type& expected, const value_type& actual) { - if (!expected.compatible_with(actual)) + compatibility_context context; + context.require(expected, actual); +} + +std::size_t compatibility_context::require(const value_type& expected, const value_type& actual) { + const auto before = _compared; + if (!type_access::compare_plans(expected, actual, true, *this) || + !type_access::compare_plans(expected, actual, false, *this)) throw std::invalid_argument("incompatible value shape or opaque ownership operations"); + return _compared - before; } /// Extends a plan's canonical layout and complete aggregate capabilities with source-order fields. /// -/// \pre plan has a valid canonical prefix, including matching cumulative resource counts. +/// \pre plan has a valid canonical prefix. /// Throws std::overflow_error if byte extent arithmetic overflows. /// Also throws std::overflow_error if the ownership-carrier count overflows. /// Failure may leave a partially extended unpublished plan. -/// Complexity: O(field count) amortized time and added offset/count result storage. +/// Complexity: O(field count) amortized time and added offset result storage. void canonical_layout(type_plan& plan, std::span fields) { // Accumulate source-order layouts and retain canonical field offsets. for (const auto& field : fields) { @@ -248,7 +305,6 @@ void canonical_layout(type_plan& plan, std::span fields) { if (count > std::numeric_limits::max() - plan.resources) throw std::overflow_error("aggregate ownership count overflow"); plan.resources += count; - plan.resource_ends.push_back(plan.resources); } plan.bytes.size = align_offset(plan.bytes.size, plan.bytes.alignment); } @@ -324,6 +380,7 @@ value_type value_type::tuple(std::span fields) { auto plan = std::make_shared(); plan->fields.assign(fields.begin(), fields.end()); detail::canonical_layout(*plan, fields); + detail::compile_ownership(*plan); return value_type(std::move(plan)); } @@ -341,6 +398,7 @@ value_type value_type::record(std::string_view identity, std::spanfields.push_back(field.type); } detail::canonical_layout(*plan, plan->fields); + detail::compile_ownership(*plan); return value_type(std::move(plan)); } @@ -392,7 +450,9 @@ bool value_type::same_shape(const value_type& other) const { } bool value_type::compatible_with(const value_type& other) const { - return same_shape(other) && detail::type_access::compatible_operations(*this, other); + detail::compatibility_context context; + return detail::type_access::compare_plans(*this, other, true, context) && + detail::type_access::compare_plans(*this, other, false, context); } type_kind value_type::kind() const noexcept { return _plan->kind; } diff --git a/tests/resource_test.cpp b/tests/resource_test.cpp index e2c57d3..d8b8858 100644 --- a/tests/resource_test.cpp +++ b/tests/resource_test.cpp @@ -1,14 +1,111 @@ // SPDX-License-Identifier: BSL-1.0 +#include "type_ops.hpp" #include "value_ops.hpp" #include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include +#include #include #include #include #include + +/// Checks every carrier offset and a linear bound on constant-time traversal steps. +/// Complexity: O(count log count) time and O(count) temporary space. +void check_ownership_traversal(const cel::value_type& type, std::size_t count) { + cel::detail::ownership_cursor cursor(type); + std::vector offsets; + std::size_t steps = 0; + while (!cursor.empty()) { + if (const auto slot = cursor.next()) { + CHECK((slot->type->kind() == cel::type_kind::array)); + offsets.push_back(slot->offset); + } + ++steps; + } + REQUIRE((offsets.size() == count)); + CHECK((steps <= 3 * count)); + std::sort(offsets.begin(), offsets.end()); + for (std::size_t i = 0; i != count; ++i) + CHECK((offsets[i] == i * sizeof(void*))); +} + +/// Catches repeated root searches and expanded metadata at every skewed descriptor. +TEST_CASE("ownership ranges traverse wide and skewed aggregates in linear work") { + constexpr std::size_t count = 2048; + const auto element = cel::value::from(std::vector{3.0}); + const cel::value_type unit; + const std::vector fields(count, element); + const auto flat = cel::value::tuple(fields); + check_ownership_traversal(flat.type(), count); + + for (const bool heavy_first : {false, true}) { + auto type = element.type(); + std::size_t ranges = 0; + std::size_t range_bytes = 0; + for (std::size_t i = 1; i != count; ++i) { + const auto children = + heavy_first ? std::array{type, element.type()} : std::array{element.type(), type}; + type = cel::value_type::tuple(children); + const auto compiled = cel::detail::type_access::ownership_ranges(type); + ranges += compiled.size(); + range_bytes += compiled.size_bytes(); + } + CHECK(ranges <= 2 * count); + CHECK(range_bytes <= 2 * count * sizeof(cel::detail::ownership_slot)); + check_ownership_traversal(type, count); + auto original = + cel::detail::value_access::copy(type, cel::detail::value_access::data(flat)); + auto copy = original; + original = cel::value{}; + auto restored = + cel::detail::value_access::copy(flat.type(), cel::detail::value_access::data(copy)); + CHECK(restored.at(0).at(0).as() == 3.0); + CHECK(restored.at(count - 1).at(0).as() == 3.0); + copy = cel::value{}; + restored = cel::value{}; + type = unit; + } +} + +/// Supplies a nonowning client field with extended alignment. +struct alignas(256) ownership_aligned_leaf { + std::array bytes; ///< Stores a trivially copyable opaque payload. +}; + +/// Catches incorrect range offsets when zero-byte and over-aligned fields precede carriers. +TEST_CASE("record ownership ranges preserve canonical offsets around nonowning fields") { + const auto array = cel::value::from(std::vector{5.0}); + const auto wide = cel::value::from(ownership_aligned_leaf{}); + const auto type = + cel::value_type::record("mixed", std::array{cel::record_field{"unit", cel::value_type{}}, + cel::record_field{"bytes", wide.type()}, + cel::record_field{"items", array.type()}}); + auto original = cel::value::record(type, std::array{cel::value{}, wide, array}); + auto copy = original; + copy.set_field("items", cel::value::from(std::vector{9.0})); + CHECK(original.field("items").at(0).as() == 5.0); + CHECK(copy.field("items").at(0).as() == 9.0); + original = cel::value{}; + copy = cel::value{}; +} + +/// Catches expansion of shared ranges and traversal proportional to unary nesting. +TEST_CASE("ownership ranges reuse shared descendants and collapse unary paths") { + auto type = cel::value_type::array(cel::value_type::leaf()); + std::size_t ranges = 0; + for (std::size_t i = 0; i != 12; ++i) { + type = cel::value_type::tuple(std::array{type, type}); + ranges += cel::detail::type_access::ownership_ranges(type).size(); + } + CHECK(ranges <= 24); + check_ownership_traversal(type, 4096); + for (std::size_t i = 0; i != 50000; ++i) + type = cel::value_type::tuple(std::array{type}); + check_ownership_traversal(type, 4096); +} /// Catches recursive last-reference release, including during exception cleanup. TEST_CASE("deep descriptor release and exception unwinding are stack independent") { const cel::value_type unit; diff --git a/tests/value_test.cpp b/tests/value_test.cpp index c8e651f..4775800 100644 --- a/tests/value_test.cpp +++ b/tests/value_test.cpp @@ -31,6 +31,13 @@ struct other_leaf { bool fail_test_clone = false; /// Counts live resources created by the synthetic opaque clone callback. int live_test_owners = 0; +/// Requests a failure after a known initialized ownership prefix. +int test_clones_until_failure = -1; +/// Identifies a synthetic clone failure without allocating a diagnostic. +struct test_clone_error : std::exception { + /// Returns a fixed diagnostic without allocating. + const char* what() const noexcept override { return "synthetic clone failure"; } +}; /// Clones a synthetic opaque owner without implementing a callable object. void clone_test_owner(const std::byte* source, std::byte* destination) { @@ -38,6 +45,10 @@ void clone_test_owner(const std::byte* source, std::byte* destination) { std::memcpy(static_cast(&pointer), source, sizeof(pointer)); auto copy = std::make_unique(*pointer); if (fail_test_clone) throw std::runtime_error("synthetic clone failure"); + if (test_clones_until_failure == 0) { + throw test_clone_error{}; + } + if (test_clones_until_failure > 0) --test_clones_until_failure; ++live_test_owners; pointer = copy.release(); std::memcpy(destination, static_cast(&pointer), sizeof(pointer)); @@ -54,6 +65,103 @@ void destroy_test_owner(std::byte* data) noexcept { /// Supplies a distinct installed operation pair to test representation admission. void destroy_test_owner_alternative(std::byte* data) noexcept { destroy_test_owner(data); } +/// Catches repeating complete comparisons for every empty element with shared metadata. +TEST_CASE("checked arrays reuse equivalent descriptor comparisons across elements") { + constexpr std::size_t depth = 128; + constexpr std::size_t count = 128; + auto expected = cel::value_type::leaf(); + auto actual = cel::value_type::leaf(); + for (std::size_t i = 0; i != depth; ++i) { + expected = cel::value_type::array(expected); + actual = cel::value_type::array(actual); + } + const auto empty = cel::value::array(actual.element(), {}); + const std::vector children(count, empty); + cel::value result; + result = cel::value::array(expected, children); + CHECK(result.size() == count); + CHECK(result.at(count - 1).size() == 0); + + auto consumed = children; + result = cel::detail::value_access::take_array(expected, consumed); + for (const auto& child : consumed) + CHECK(child.type().same_shape(cel::value{}.type())); + + cel::detail::compatibility_context comparisons; + std::size_t work = 0; + for (const auto& child : children) + work += comparisons.require(expected, child.type()); + CHECK(work > 0); + CHECK(work <= 2 * (depth + 1)); + + for (std::size_t i = 0; i != count; ++i) { + const auto distinct = cel::value::array(actual.element(), {}); + work += comparisons.require(expected, distinct.type()); + } + CHECK(work <= 2 * (depth + count + 1)); +} + +/// Catches memo entries authorizing unequal shapes or foreign operations after a failed check. +TEST_CASE("operation comparison caches keep shape and ownership checks independent") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + const auto expected = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner}); + cel::detail::compatibility_context comparisons; + for (int i = 0; i != 128; ++i) { + const auto actual = cel::detail::type_access::install_callable_ownership( + signature, + {clone_test_owner, i % 2 == 0 ? destroy_test_owner : destroy_test_owner_alternative}); + if (i % 2 == 0) { + CHECK_NOTHROW(comparisons.require(expected, actual)); + } else { + CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); + CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); + } + } + const auto one = cel::value_type::tuple(std::array{expected}); + const auto two = cel::value_type::tuple(std::array{expected, expected}); + CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); + CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); + CHECK_NOTHROW(comparisons.require(one, cel::value_type::tuple(std::array{expected}))); + + const auto foreign = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner_alternative}); + const auto valid_empty = cel::value::array(expected, {}); + const auto foreign_empty = cel::value::array(foreign, {}); + CHECK_THROWS_AS(cel::value::array(valid_empty.type(), std::array{valid_empty, foreign_empty}), + std::invalid_argument); + auto destination = cel::value::array(valid_empty.type(), std::array{valid_empty}); + CHECK_THROWS_AS(destination.set(0, foreign_empty), std::invalid_argument); + CHECK(destination.at(0).type().compatible_with(valid_empty.type())); +} + +/// Catches leaking a partially cloned traversal-order prefix. +TEST_CASE("partial ownership traversal cleans its initialized prefix") { + const auto installed = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_test_owner, destroy_test_owner}); + int number = 42; + int* pointer = &number; + std::array bytes; + std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); + const auto callable = cel::detail::value_access::copy(installed, bytes.data()); + const auto array = cel::value::from(std::vector{2.0, 3.0}); + const auto source = + cel::value::tuple(std::array{callable, array, callable, array, callable, array}); + const auto live = live_test_owners; + test_clones_until_failure = 2; + bool caught = false; + try { + auto copy = source; + } catch (const test_clone_error&) { + caught = true; + } + test_clones_until_failure = -1; + CHECK(caught); + CHECK(live_test_owners == live); + CHECK(source.at(1).at(0).as() == 2.0); +} + /// Catches layout-only comparison and ownership traversal before unequal-shape rejection. TEST_CASE("public compatibility requires complete semantic shapes") { const auto scalar = cel::value_type::leaf();