lutaml-model 0.8.198 → 0.8.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -727,6 +727,46 @@ module Lutaml
727
727
  type == Lutaml::Model::Type::Hash
728
728
  end
729
729
 
730
+ # Whether the attribute's polymorphic list admits this value as a
731
+ # listed scalar member: a Type::Value member is a scalar shape (and
732
+ # admits arrays of scalars; the :array symbol admits arrays too).
733
+ # A list of model classes only does not admit scalars (#1292).
734
+ def polymorphic_scalar_member?(value)
735
+ list = @options[:polymorphic]
736
+ return false unless list.is_a?(::Array)
737
+
738
+ scalar_member = list.any? do |member|
739
+ member.is_a?(Class) && member < Type::Value
740
+ end
741
+ return false unless scalar_member
742
+ return false if value.is_a?(::Hash) || value.is_a?(Serialize)
743
+ return true unless value.is_a?(::Array)
744
+
745
+ list.include?(:array) ||
746
+ value.all? { |item| !item.is_a?(::Hash) && !item.is_a?(Serialize) }
747
+ end
748
+
749
+ # Whether the list admits this Array on a singular attribute: a list
750
+ # with a scalar member admits an Array of members — scalars and model
751
+ # instances alike — each item taking its own lane (#1292).
752
+ def polymorphic_member_array?(value)
753
+ value.is_a?(Array) && value.none?(Hash) &&
754
+ has_polymorphic_list? &&
755
+ options[:polymorphic].any? { |member| member.is_a?(Class) && member < Type::Value }
756
+ end
757
+
758
+ # The listed member type that owns this value: the first Value
759
+ # member whose cast preserves the value's class, falling back to
760
+ # the first Value member. The probe only runs on the rare
761
+ # polymorphic-scalar path.
762
+ def polymorphic_member_type_for(value)
763
+ members = @options[:polymorphic].select do |member|
764
+ member.is_a?(Class) && member < Type::Value
765
+ end
766
+ members.find { |member| member.cast(value).class == value.class } ||
767
+ members.first
768
+ end
769
+
730
770
  # The attribute a plain scalar coerces onto for a Serializable
731
771
  # type (#1228): the whole-value `map to: :content` form (a
732
772
  # content/root mapping whose sole target is a scalar attribute)
@@ -984,7 +1024,7 @@ instance_object = nil)
984
1024
  end
985
1025
  return true unless options[:polymorphic]
986
1026
 
987
- valid_polymorphic_type?(value, resolved_type)
1027
+ valid_polymorphic_type?(value)
988
1028
  end
989
1029
 
990
1030
  def validate_polymorphic!(value, resolved_type)
@@ -1037,7 +1077,8 @@ instance_object = nil)
1037
1077
 
1038
1078
  def valid_collection!(value, caller)
1039
1079
  if collection_instance?(value) && !collection? &&
1040
- !value_policy.whole_value?(unresolved_type)
1080
+ !value_policy.whole_value?(unresolved_type) &&
1081
+ !polymorphic_member_array?(value)
1041
1082
  raise Lutaml::Model::CollectionTrueMissingError.new(name,
1042
1083
  caller)
1043
1084
  end
@@ -1193,6 +1234,14 @@ instance_object = nil)
1193
1234
  "not build one (received #{casted.class})"
1194
1235
  end
1195
1236
 
1237
+ # A polymorphic list with a scalar member (Type::String, ...)
1238
+ # accepts a listed scalar verbatim: the member type owns the
1239
+ # value, so the content-coercion contract below does not apply
1240
+ # (#1292 - the declaration explicitly allows the scalar).
1241
+ if serializable_type?(register) && polymorphic_scalar_member?(value)
1242
+ return Type.lookup(polymorphic_member_type_for(value)).cast(value)
1243
+ end
1244
+
1196
1245
  # The 0.8.x scalar-coercion contract (#1228): a plain string for
1197
1246
  # a mapped-model attribute whose type does not own a scalar
1198
1247
  # .cast coerces onto the type's `content` mapping (title:
@@ -1279,6 +1328,7 @@ instance_object = nil)
1279
1328
 
1280
1329
  def process_options!
1281
1330
  validate_options!(@options)
1331
+ validate_polymorphic_entries!(@options[:polymorphic])
1282
1332
  if union?
1283
1333
  @options[:union_member_types] =
1284
1334
  Lutaml::Model::Type::Union.validate_members!(@options[:union_member_types])
@@ -1649,10 +1699,37 @@ instance_object = nil)
1649
1699
  "Invalid type: #{type}, must be a Symbol, String or a Class"
1650
1700
  end
1651
1701
 
1652
- def valid_polymorphic_type?(value, resolved_type)
1702
+ # Validation agrees with the serializer. A listed scalar member admits
1703
+ # scalars and arrays of them (polymorphic_scalar_member?) and, since
1704
+ # the nested lane takes any model instance under the declared base,
1705
+ # model instances too; a list of model classes only restricts them to
1706
+ # the listed classes. The old predicate compared entries to
1707
+ # value.class (Type::String is never a String) and then demanded the
1708
+ # declared base type, so every admitted value failed here.
1709
+ def valid_polymorphic_type?(value)
1653
1710
  return value.is_a?(type) unless has_polymorphic_list?
1654
1711
 
1655
- options[:polymorphic].include?(value.class) && value.is_a?(resolved_type)
1712
+ return true if polymorphic_scalar_member?(value)
1713
+ return false unless value.is_a?(Serialize)
1714
+
1715
+ list = options[:polymorphic]
1716
+ list.any? { |member| member.is_a?(Class) && member < Type::Value } ||
1717
+ list.any? { |entry| entry.is_a?(Class) && value.is_a?(entry) }
1718
+ end
1719
+
1720
+ # Definition-time contract for the polymorphic list: an entry that can
1721
+ # never match anything — a Symbol other than :array — fails the
1722
+ # declaration instead of surfacing at serialization (#1292).
1723
+ def validate_polymorphic_entries!(entries)
1724
+ return unless entries.is_a?(Array)
1725
+
1726
+ entries.each do |entry|
1727
+ next if entry.is_a?(Class) || entry == :array
1728
+
1729
+ raise ArgumentError,
1730
+ "polymorphic entry #{entry.inspect} is not a type: use a " \
1731
+ "class or :array"
1732
+ end
1656
1733
  end
1657
1734
 
1658
1735
  def has_polymorphic_list?
@@ -206,14 +206,13 @@ module Lutaml
206
206
  # yields each resolved element-order item with its owning schema.
207
207
  def each_schema_item(schemas, &dispatch)
208
208
  schemas.each do |schema|
209
- # Override-applied documents ride the override collection
210
- # alongside the Override declarations themselves (the mixed
211
- # shape the include/import collections already have); only
212
- # the applied Schema objects carry a walkable element order.
213
- if schema.respond_to?(:override) && schema.override&.any?
214
- schema.override.grep(Lutaml::Xml::Schema::Xsd::Schema).each do |applied|
215
- each_schema_item([applied], &dispatch)
216
- end
209
+ # An override's composed view is reachable from its entry
210
+ # (the override collection holds the declarations only);
211
+ # the view carries the referenced document's walkable
212
+ # element order with the replacements substituted.
213
+ Array(schema.override).each do |entry|
214
+ view = entry.composed
215
+ each_schema_item([view], &dispatch) if view
217
216
  end
218
217
  if schema.include&.any?
219
218
  each_schema_item(schema.include,
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Lutaml
4
4
  module Model
5
- VERSION = "0.8.198"
5
+ VERSION = "0.8.200"
6
6
  end
7
7
  end
@@ -56,31 +56,72 @@ module Lutaml
56
56
  Glob.include_schema(schema_path) if schema_path && Glob.location?
57
57
  end
58
58
 
59
- # XSD 1.1 §4.2.4: the referenced document's components are
60
- # replaced by this override's same-named children. Matching is
61
- # by component kind and name; a child with no counterpart adds
62
- # to the referenced document (lenient); children without a name
63
- # (ref-form, anonymous) carry no replacement. Applied on a copy
64
- # of the referenced schema so the override stays local to the
65
- # referencing document.
66
- def apply_to!(target_schema)
67
- COMPONENT_KINDS.each do |kind, name_attr|
68
- Array(public_send(kind)).each do |replacement|
69
- name = replacement.public_send(name_attr)
70
- next if name.nil?
59
+ # The composed view of the referenced document (XSD 1.1 §4.2.4):
60
+ # a new schema whose component collections carry each same-named
61
+ # component replaced by this override's child and the rest of
62
+ # the children appended. Matching is by component kind and
63
+ # name; a child with no counterpart adds to the view (lenient);
64
+ # children without a name (ref-form, anonymous) carry no
65
+ # replacement. The referenced document and its components are
66
+ # shared by reference and never mutated, so every document
67
+ # overriding the same target composes against the same
68
+ # originals.
69
+ def composed
70
+ @composed
71
+ end
72
+
73
+ # Composes (once) against the referenced document; the entry is
74
+ # shared by every viewer, so a chase coming back to it finds the
75
+ # view already composed (#1299).
76
+ def compose(referenced)
77
+ return @composed if @composed
78
+
79
+ view = Schema.new(**view_attributes(referenced))
80
+ view.element_order = referenced.element_order
81
+ @composed = view
82
+ end
83
+
84
+ # Root the composed view as its own schema root, as the parsed
85
+ # document it views is.
86
+ def assign_root!(root = self, seen = nil)
87
+ seen ||= {}.compare_by_identity
88
+ super
89
+ composed&.assign_root!(composed, seen)
90
+ self
91
+ end
71
92
 
72
- components = target_schema.public_send(kind)
73
- index = components.index do |component|
74
- component.public_send(name_attr) == name
75
- end
76
- if index
77
- components[index] = replacement
78
- else
79
- components << replacement
80
- end
93
+ private
94
+
95
+ def view_attributes(referenced)
96
+ Schema.attributes.each_with_object({}) do |(name, _attribute), values|
97
+ value = referenced.public_send(name)
98
+ values[name] = if COMPONENT_KINDS.key?(name)
99
+ substitute_components(name, value)
100
+ elsif value.is_a?(Array)
101
+ value.dup
102
+ else
103
+ value
104
+ end
105
+ end
106
+ end
107
+
108
+ def substitute_components(kind, components)
109
+ name_attr = COMPONENT_KINDS[kind]
110
+ substituted = Array(components).dup
111
+ Array(public_send(kind)).each do |replacement|
112
+ name = replacement.public_send(name_attr)
113
+ next if name.nil?
114
+
115
+ index = substituted.index do |component|
116
+ component.public_send(name_attr) == name
117
+ end
118
+ if index
119
+ substituted[index] = replacement
120
+ else
121
+ substituted << replacement
81
122
  end
82
123
  end
83
- target_schema
124
+ substituted
84
125
  end
85
126
 
86
127
  Lutaml::Xml::Schema::Xsd.register_model(self, :override)
@@ -294,24 +294,31 @@ module Lutaml
294
294
  alias attributes attribute
295
295
  alias groups group
296
296
 
297
+ # XSD 1.1 §4.2.4 assembly: every override entry composes the
298
+ # view of its referenced document once. The entry is shared by
299
+ # reference with every viewer, so the view is too, and a chase
300
+ # that comes back to a location on its own chain finds the
301
+ # entry still uncomposed and leaves it so (as for a cyclic
302
+ # include) instead of chasing its own assembly forever
303
+ # (#1299). Runs after the tree is parsed (the override's
304
+ # children are populated), before root assignment.
297
305
  def apply_overrides!(seen = nil)
298
306
  seen ||= {}.compare_by_identity
299
307
  return self if seen[self]
300
308
 
301
309
  seen[self] = true
302
310
  Array(override).each do |entry|
303
- next unless entry.is_a?(Override) && entry.schema_path
304
- next if self.class.in_progress?(entry.schema_path)
311
+ next unless entry.is_a?(Override)
305
312
 
306
- self.class.add_in_progress(entry.schema_path)
307
- referenced = insert_in_processed_schemas(entry)
308
- self.class.remove_in_progress(entry.schema_path)
309
- next unless referenced
313
+ path = entry.schema_path
314
+ next unless path
315
+ next if entry.composed || self.class.in_progress?(path)
310
316
 
311
- applied = Lutaml::Model::Utils.deep_dup(referenced)
312
- entry.apply_to!(applied)
313
- override(applied)
314
- applied.apply_overrides!(seen)
317
+ self.class.add_in_progress(path)
318
+ referenced = insert_in_processed_schemas(entry)
319
+ entry.compose(referenced) if referenced
320
+ ensure
321
+ self.class.remove_in_progress(path)
315
322
  end
316
323
  %i[include import].each do |kind|
317
324
  Array(public_send(kind)).each do |nested|
@@ -338,15 +345,10 @@ module Lutaml
338
345
  namespaces.uniq
339
346
  end
340
347
 
341
- # XSD 1.1 s4.2.4 override application (the assembly pass): each
342
- # override resolves its referenced document through the same
343
- # location machinery includes use, replaces the same-named
344
- # components on a COPY (the processed-schemas memo shares
345
- # originals across references; an override is local to this
346
- # reference), and appends the applied document to the override
347
- # collection so the schema walk reaches it in place of the raw
348
- # document. Runs after the tree is parsed (the override's
349
- # children are populated), before root assignment.
348
+ # An xs:include / xs:import declaration resolves its document
349
+ # through the location machinery; a location already on the
350
+ # chain is not chased again (cyclic references compose as
351
+ # multiple inclusions of the same document).
350
352
  def setup_import_and_include(klass, model, schema, args = {})
351
353
  instance = init_instance_of(klass, schema.attributes || {}, args)
352
354
  annotation_object(instance, schema)
@@ -424,6 +426,7 @@ module Lutaml
424
426
  class << self
425
427
  def reset_processed_schemas
426
428
  @processed_schemas = {}
429
+ @in_progress = []
427
430
  end
428
431
 
429
432
  def processed_schemas
@@ -7,15 +7,18 @@ require "lutaml/lml"
7
7
 
8
8
  RSpec.configure do |config|
9
9
  config.define_derived_metadata(file_path: %r{elk_layout_spec}) do |metadata|
10
-
11
- metadata[:skip] = "elkrb gem not available" unless (require "elkrb"
12
- true)
13
- rescue StandardError
14
- false
15
-
10
+ metadata[:skip] = "elkrb gem not available" unless elkrb_available?
16
11
  end
17
12
  end
18
13
 
14
+ # elkrb is an optional layout engine; its absence skips the layout specs.
15
+ def elkrb_available?
16
+ require "elkrb"
17
+ true
18
+ rescue LoadError
19
+ false
20
+ end
21
+
19
22
  def fixtures_path(path)
20
23
  File.join(File.expand_path("fixtures", __dir__), path)
21
24
  end
@@ -223,20 +223,22 @@ RSpec.describe "KV group-then-bulk hydration" do
223
223
  expect(ranged.from_hash("tags" => %w[a b]).tags).to eq(%w[a b])
224
224
  end
225
225
 
226
- it "rejects self-referential models (cycle)" do
226
+ it "compiles self-referential models as a plan referencing itself (#1297)" do
227
227
  node = Class.new(Lutaml::Model::Serializable) do
228
228
  attribute :name, :string
229
229
  json { map "name", to: :name }
230
230
  end
231
231
  node.attribute :child, node
232
- node.json do
232
+ node.json do
233
233
  map "name", to: :name
234
234
  map "child", to: :child
235
235
  end
236
236
  stub_const("KvGroup::Node", node)
237
237
 
238
- expect(Lutaml::KeyValue::Transform.kv_group_plan(node, :json,
239
- :default)).to be(false)
238
+ plan = Lutaml::KeyValue::Transform.kv_group_plan(node, :json, :default)
239
+ expect(plan).to be_an(Array)
240
+ child_row = plan.find { |row| row[0].to == :child }
241
+ expect(child_row[4]).to equal(plan)
240
242
  parsed = node.from_hash("name" => "n", "child" => { "name" => "c" })
241
243
  expect(parsed.child.name).to eq("c")
242
244
  end
@@ -284,7 +286,7 @@ RSpec.describe "KV group-then-bulk hydration" do
284
286
  expect(verdicts.uniq.length).to eq(1)
285
287
  end
286
288
 
287
- it "keeps the cycle verdict per-build across threads" do
289
+ it "builds self-referential plans per thread, each referencing itself" do
288
290
  node = Class.new(Lutaml::Model::Serializable) do
289
291
  attribute :name, :string
290
292
  json { map "name", to: :name }
@@ -303,7 +305,10 @@ RSpec.describe "KV group-then-bulk hydration" do
303
305
  end
304
306
  end.map(&:value)
305
307
 
306
- expect(verdicts).to all(be(false))
308
+ expect(verdicts).to all(be_an(Array))
309
+ verdicts.each do |plan|
310
+ expect(plan.find { |row| row[0].to == :child }[4]).to equal(plan)
311
+ end
307
312
  end
308
313
  end
309
314
 
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+
5
+ # lutaml-model#1297: a recursive model graph (a tree) compiles as a
6
+ # self-referential plan instead of being refused to the interpretive
7
+ # walk, and the compiled executor hydrates on an explicit frame stack —
8
+ # hydration depth is bound by the heap, not the VM stack.
9
+ class RecursivePlanNode < Lutaml::Model::Serializable
10
+ attribute :name, :string
11
+ attribute :child, RecursivePlanNode
12
+ attribute :children, RecursivePlanNode, collection: true,
13
+ initialize_empty: true
14
+
15
+ key_value do
16
+ map "name", to: :name
17
+ map "child", to: :child
18
+ map "children", to: :children
19
+ end
20
+ end
21
+
22
+ class RecursivePlanTwig < Lutaml::Model::Serializable
23
+ attribute :name, :string
24
+ attribute :branch, "RecursivePlanBranch"
25
+
26
+ key_value do
27
+ map "name", to: :name
28
+ map "branch", to: :branch
29
+ end
30
+ end
31
+
32
+ class RecursivePlanBranch < Lutaml::Model::Serializable
33
+ attribute :name, :string
34
+ attribute :twigs, RecursivePlanTwig, collection: true,
35
+ initialize_empty: true
36
+
37
+ key_value do
38
+ map "name", to: :name
39
+ map "twigs", to: :twigs
40
+ end
41
+ end
42
+
43
+ # The outer's second row is ineligible (a custom deserializer), so the
44
+ # outer build fails after the inner completed against its rows.
45
+ class RecursivePlanInner < Lutaml::Model::Serializable
46
+ attribute :outer, "RecursivePlanOuter"
47
+
48
+ key_value { map "outer", to: :outer }
49
+ end
50
+
51
+ class RecursivePlanOuter < Lutaml::Model::Serializable
52
+ attribute :inner, RecursivePlanInner
53
+ attribute :note, :string
54
+
55
+ key_value do
56
+ map "inner", to: :inner
57
+ map "note", to: :note, with: { from: :note_from }
58
+ end
59
+
60
+ def self.note_from(_model, value)
61
+ value.to_s
62
+ end
63
+ end
64
+
65
+ RSpec.describe "recursive model graphs on the compiled KV plan" do
66
+ def plan_for(klass)
67
+ Lutaml::KeyValue::Transform.kv_group_plan(klass, :hash, :default)
68
+ end
69
+
70
+ def row_for(plan, attribute)
71
+ plan.find { |row| row[0].to == attribute }
72
+ end
73
+
74
+ def chain(depth, key = "child")
75
+ h = { "name" => "leaf" }
76
+ (depth - 1).times do
77
+ h = { "name" => "n", key => (key == "child" ? h : [h]) }
78
+ end
79
+ h
80
+ end
81
+
82
+ def thicket(depth)
83
+ h = { "name" => "leaf" }
84
+ (depth - 1).times do
85
+ h = { "name" => "b", "twigs" => [{ "name" => "t", "branch" => h }] }
86
+ end
87
+ h
88
+ end
89
+
90
+ it "compiles a self-referencing model as a plan that references itself" do
91
+ plan = plan_for(RecursivePlanNode)
92
+ expect(plan).to be_an(Array)
93
+ expect(row_for(plan, :child)[4]).to equal(plan)
94
+ expect(row_for(plan, :children)[4]).to equal(plan)
95
+ end
96
+
97
+ it "compiles a mutually recursive pair into plans that reference each other" do
98
+ branch = plan_for(RecursivePlanBranch)
99
+ twig = plan_for(RecursivePlanTwig)
100
+ expect(branch).to be_an(Array)
101
+ expect(twig).to be_an(Array)
102
+ expect(row_for(branch, :twigs)[4]).to equal(twig)
103
+ expect(row_for(twig, :branch)[4]).to equal(branch)
104
+ end
105
+
106
+ it "caches the recursive plans once the outermost build succeeds" do
107
+ first = plan_for(RecursivePlanNode)
108
+ expect(plan_for(RecursivePlanNode)).to equal(first)
109
+ twig = plan_for(RecursivePlanTwig)
110
+ expect(row_for(plan_for(RecursivePlanBranch), :twigs)[4]).to equal(twig)
111
+ end
112
+
113
+ it "commits nothing when the outer build fails after an inner completed" do
114
+ expect(plan_for(RecursivePlanOuter)).to be(false)
115
+ # a cached inner plan would reference the failed outer's partial rows
116
+ expect(plan_for(RecursivePlanInner)).to be(false)
117
+ end
118
+
119
+ it "hydrates a self-referencing tree past the VM stack depth" do
120
+ node = RecursivePlanNode.from_hash(chain(10_000))
121
+ depth = 0
122
+ while node.child
123
+ depth += 1
124
+ node = node.child
125
+ end
126
+ # 10,000 levels, one child hop each below the root
127
+ expect(depth).to eq(9_999)
128
+ expect(node.name).to eq("leaf")
129
+ end
130
+
131
+ it "hydrates a mutually recursive graph past the VM stack depth" do
132
+ branch = RecursivePlanBranch.from_hash(thicket(5000))
133
+ depth = 0
134
+ while (twig = branch.twigs.first)&.branch
135
+ depth += 1
136
+ branch = twig.branch
137
+ end
138
+ expect(depth).to eq(4999)
139
+ end
140
+
141
+ it "keeps collection order and the parent wiring through the frame stack" do
142
+ doc = {
143
+ "name" => "root",
144
+ "children" => [
145
+ { "name" => "a", "children" => [{ "name" => "aa" }] },
146
+ { "name" => "b" },
147
+ ],
148
+ }
149
+ node = RecursivePlanNode.from_hash(doc)
150
+ expect(node.children.map(&:name)).to eq(%w[a b])
151
+ expect(node.children.first.children.first.name).to eq("aa")
152
+ expect(node.children.first.lutaml_parent).to equal(node)
153
+ expect(node.children.first.children.first.lutaml_parent)
154
+ .to equal(node.children.first)
155
+ expect(node.to_hash).to eq(doc)
156
+ end
157
+
158
+ it "falls back to the walk for a non-Hash item where a model was expected" do
159
+ doc = { "name" => "root", "child" => { "name" => "c" } }
160
+ expect(RecursivePlanNode.from_hash(doc).child.name).to eq("c")
161
+ expect(RecursivePlanNode.from_hash({ "name" => "root" }).child).to be_nil
162
+ end
163
+ end
@@ -208,13 +208,16 @@ RSpec.describe Lutaml::KeyValue::Transformation::ValueSerializer do
208
208
  end
209
209
  end
210
210
 
211
- # Helper method to build a mock rule
211
+ # A real compiled rule: the serializer's plan reads the rule's option
212
+ # hash (value map, when_attribute), which a bare double never carries.
212
213
  def build_rule(attribute_type:, attribute_name: :test,
213
- child_transformation: nil)
214
- double("CompiledRule",
215
- attribute_type: attribute_type,
216
- attribute_name: attribute_name,
217
- child_transformation: child_transformation,
218
- collection?: false)
214
+ child_transformation: nil)
215
+ Lutaml::Model::CompiledRule.new(
216
+ attribute_name: attribute_name,
217
+ serialized_name: attribute_name.to_s,
218
+ attribute_type: attribute_type,
219
+ child_transformation: child_transformation,
220
+ mapping_type: :key_value,
221
+ )
219
222
  end
220
223
  end