lutaml-model 0.8.202 → 0.8.204

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.
Files changed (123) hide show
  1. checksums.yaml +4 -4
  2. data/.gitattributes +5 -0
  3. data/.github/workflows/dependent-tests.yml +59 -2
  4. data/.github/workflows/lml-conformance.yml +71 -0
  5. data/.gitignore +7 -0
  6. data/README.adoc +1 -0
  7. data/docs/_guides/lml-cross-language.adoc +128 -0
  8. data/docs/_references/lml-conformance.adoc +78 -0
  9. data/docs/_references/lml-contract.adoc +290 -0
  10. data/docs/_references/plan-schema-spec.adoc +45 -18
  11. data/lib/lutaml/key_value/transform.rb +140 -21
  12. data/lib/lutaml/model/attribute.rb +11 -6
  13. data/lib/lutaml/model/lml/artifact_verifier.rb +205 -0
  14. data/lib/lutaml/model/lml/bundle.rb +171 -0
  15. data/lib/lutaml/model/lml/document.rb +46 -10
  16. data/lib/lutaml/model/lml/document_validator.rb +840 -0
  17. data/lib/lutaml/model/lml/exporter/v1_projector.rb +102 -0
  18. data/lib/lutaml/model/lml/exporter/v2_projector.rb +401 -0
  19. data/lib/lutaml/model/lml/exporter.rb +223 -87
  20. data/lib/lutaml/model/lml/graph_exporter.rb +248 -0
  21. data/lib/lutaml/model/lml/importer.rb +180 -0
  22. data/lib/lutaml/model/lml/mapping_compiler.rb +401 -0
  23. data/lib/lutaml/model/lml/materialization.rb +257 -0
  24. data/lib/lutaml/model/lml/ordered_content.rb +577 -0
  25. data/lib/lutaml/model/lml/portable_json.rb +385 -0
  26. data/lib/lutaml/model/lml/rejected_error.rb +64 -15
  27. data/lib/lutaml/model/lml/round_trip.rb +86 -0
  28. data/lib/lutaml/model/lml/value_declarations.rb +84 -0
  29. data/lib/lutaml/model/lml.rb +61 -0
  30. data/lib/lutaml/model/schema/definitions/attribute.rb +4 -2
  31. data/lib/lutaml/model/schema/registry_generator.rb +1 -1
  32. data/lib/lutaml/model/schema/renderers/member_decls.rb +1 -0
  33. data/lib/lutaml/model/schema/xml_compiler/spec_builder/members.rb +10 -0
  34. data/lib/lutaml/model/sequence.rb +7 -0
  35. data/lib/lutaml/model/serialize/deserialization_context.rb +21 -0
  36. data/lib/lutaml/model/serialize/initialization.rb +19 -9
  37. data/lib/lutaml/model/version.rb +1 -1
  38. data/lib/lutaml/xml/leptris/native_emission.rb +4 -0
  39. data/lib/lutaml/xml/leptris/plan_serializer.rb +14 -9
  40. data/schema/lml/document.schema.json +179 -0
  41. data/scripts/lml/export_choices.rb +57 -0
  42. data/scripts/lml/export_conformance.rb +23 -0
  43. data/scripts/lml/export_mml.rb +253 -0
  44. data/scripts/lml/export_preservation.rb +421 -0
  45. data/scripts/lml/verify_artifacts.rb +31 -0
  46. data/spec/address_person_spec.rb +8 -0
  47. data/spec/address_spec.rb +4 -0
  48. data/spec/fixtures/lml_artifacts/model.json +1 -0
  49. data/spec/fixtures/lml_artifacts/valid.json +1 -0
  50. data/spec/fixtures/lml_artifacts/valid.sha256 +1 -0
  51. data/spec/fixtures/lml_conformance/core/index.json +1 -0
  52. data/spec/fixtures/lml_conformance/core/manifest.json +1 -0
  53. data/spec/fixtures/lml_conformance/core/schema.json +1 -0
  54. data/spec/fixtures/lml_conformance/core/schema.yaml +79 -0
  55. data/spec/fixtures/lml_conformance/float_vectors.generator.rb +60 -0
  56. data/spec/fixtures/lml_conformance/float_vectors.json +21550 -0
  57. data/spec/fixtures/lml_conformance/preservation/index.json +1 -0
  58. data/spec/fixtures/lml_conformance/preservation/manifest.json +1 -0
  59. data/spec/fixtures/lml_conformance/preservation/schema.json +1 -0
  60. data/spec/fixtures/lml_conformance/preservation/schema.yaml +319 -0
  61. data/spec/fixtures/lml_conformance/r2_refusals.generator.rb +153 -0
  62. data/spec/fixtures/lml_conformance/r2_refusals.json +1662 -0
  63. data/spec/fixtures/lml_conformance/ruby_portable_interop.generator.rb +40 -0
  64. data/spec/fixtures/lml_conformance/ruby_portable_interop.json +1 -0
  65. data/spec/fixtures/lml_contract/bundle.json +81 -0
  66. data/spec/fixtures/lml_contract/manifest.json +30 -0
  67. data/spec/fixtures/lml_contract/v1_unit.canonical.json +1 -0
  68. data/spec/fixtures/lml_contract/v1_unit.json +1 -0
  69. data/spec/fixtures/lml_contract/v2_node.canonical.json +1 -0
  70. data/spec/fixtures/lml_contract/v2_node.json +32 -0
  71. data/spec/fixtures/lml_mml/inventory.json +1 -0
  72. data/spec/fixtures/lml_mml/manifest.json +1 -0
  73. data/spec/fixtures/lml_mml/oracle.json +1 -0
  74. data/spec/fixtures/lml_mml/v3-mi-mixed.json +1 -0
  75. data/spec/fixtures/lml_mml/v3-mi-mixed.yaml +970 -0
  76. data/spec/fixtures/lml_mml/v4-mi-mixed.json +1 -0
  77. data/spec/fixtures/lml_mml/v4-mi-mixed.yaml +1516 -0
  78. data/spec/fixtures/lml_mml_materialization/replay.rb +37 -0
  79. data/spec/lutaml/key_value/group_instantiate_spec.rb +204 -1
  80. data/spec/lutaml/model/lml_any_attribute_spec.rb +91 -0
  81. data/spec/lutaml/model/lml_artifact_verifier_spec.rb +86 -0
  82. data/spec/lutaml/model/lml_builtin_types_spec.rb +49 -0
  83. data/spec/lutaml/model/lml_conformance_spec.rb +178 -0
  84. data/spec/lutaml/model/lml_document_spec.rb +279 -0
  85. data/spec/lutaml/model/lml_export_validation_spec.rb +96 -0
  86. data/spec/lutaml/model/lml_exporter_spec.rb +127 -5
  87. data/spec/lutaml/model/lml_graph_exporter_spec.rb +205 -0
  88. data/spec/lutaml/model/lml_importer_spec.rb +290 -0
  89. data/spec/lutaml/model/lml_input_hardening_spec.rb +156 -0
  90. data/spec/lutaml/model/lml_mapping_compiler_spec.rb +256 -0
  91. data/spec/lutaml/model/lml_materialization_spec.rb +138 -0
  92. data/spec/lutaml/model/lml_mml_materialization_spec.rb +54 -0
  93. data/spec/lutaml/model/lml_mml_pilot_spec.rb +150 -0
  94. data/spec/lutaml/model/lml_model_choices_spec.rb +88 -0
  95. data/spec/lutaml/model/lml_ordered_content_spec.rb +243 -0
  96. data/spec/lutaml/model/lml_portable_json_spec.rb +310 -0
  97. data/spec/lutaml/model/lml_preservation_spec.rb +211 -0
  98. data/spec/lutaml/model/lml_review_export_spec.rb +247 -0
  99. data/spec/lutaml/model/lml_review_import_spec.rb +390 -0
  100. data/spec/lutaml/model/lml_review_misc_spec.rb +152 -0
  101. data/spec/lutaml/model/lml_review_round4_spec.rb +200 -0
  102. data/spec/lutaml/model/lml_review_round5_spec.rb +194 -0
  103. data/spec/lutaml/model/lml_ruby_interop_fixture_spec.rb +37 -0
  104. data/spec/lutaml/model/lml_shared_corpus_spec.rb +132 -0
  105. data/spec/lutaml/model/lml_value_declarations_spec.rb +128 -0
  106. data/spec/lutaml/model/schema/class_loader_spec.rb +51 -0
  107. data/spec/lutaml/model/schema/xml_compiler_runtime_spec.rb +20 -0
  108. data/spec/lutaml/model/sequence_spec.rb +48 -0
  109. data/spec/lutaml/model/serialize/deserialization_context_spec.rb +68 -0
  110. data/spec/lutaml/xml/cdata_emission_spec.rb +68 -0
  111. data/spec/spec_helper.rb +4 -5
  112. data/spec/support/lml_any_attribute_fixtures.rb +26 -0
  113. data/spec/support/lml_conformance.rb +292 -0
  114. data/spec/support/lml_corpus.rb +75 -0
  115. data/spec/support/lml_export_fixtures.rb +190 -0
  116. data/spec/support/lml_graph_fixtures.rb +108 -0
  117. data/spec/support/lml_import_fixtures.rb +52 -0
  118. data/spec/support/lml_mapping_fixtures.rb +170 -0
  119. data/spec/support/lml_materialization_fixtures.rb +53 -0
  120. data/spec/support/lml_model_choices_fixtures.rb +150 -0
  121. data/spec/support/lml_order_fixtures.rb +151 -0
  122. metadata +93 -2
  123. data/lib/lutaml/model/schema/schema_builder/nokogiri.rb +0 -41
@@ -0,0 +1,290 @@
1
+ = LutaML Model Language (LML) contract
2
+
3
+ LML is a versioned, language-neutral description of model declarations. It carries
4
+ model data and mappings; it does not carry executable defaults, serializers,
5
+ constructors, or application behavior. This reference records the effective v2
6
+ contract from issue #1033. A contract being effective does not mean every
7
+ producer, consumer, or command has shipped; see the capability status below.
8
+
9
+ == Versions and identities
10
+
11
+ Existing valid v1 documents and their `.export` checksums retain their current
12
+ meaning. A v1 document is a single Ruby model projection. `Document.from_hash`
13
+ validates the supplied version; it does not silently rewrite it.
14
+
15
+ Portable graphs use document version 2 inside a version-1 bundle. The bundle
16
+ contains `roots`, `models`, `value_types`, `capabilities`, and `provenance`.
17
+ Every model is keyed by a stable ID formed as
18
+ `<qualified-model-name>@<effective-register>`. In v2, a missing or default
19
+ register is normalized to `default`; v1 identity is unchanged. Names that cannot
20
+ be represented portably are rejected. A consumer may materialize a Ruby class
21
+ under a different constant name while preserving the schema ID.
22
+
23
+ [source,json]
24
+ ----
25
+ {
26
+ "lml_bundle": 1,
27
+ "roots": ["Example::Node@default"],
28
+ "models": {
29
+ "Example::Node@default": {
30
+ "lml": 2,
31
+ "model": "Example::Node",
32
+ "register": "default",
33
+ "attributes": [],
34
+ "mappings": {},
35
+ "ordered_content": {"member": "__lml_content", "version": 1}
36
+ }
37
+ },
38
+ "value_types": {},
39
+ "capabilities": ["json", "xml"],
40
+ "provenance": {"source_revision": "SOURCE_SHA"}
41
+ }
42
+ ----
43
+
44
+ The example abbreviates attributes and mappings. Graph closure includes model,
45
+ import, reference, and discriminator targets in the effective register context.
46
+ Duplicate IDs with different definitions, dangling references, unknown versions,
47
+ and implicit global-context changes are errors. Models and value types are
48
+ key-sorted; roots and capabilities are sorted unique arrays. Attribute, rule,
49
+ enum, and sequence arrays keep declaration order.
50
+
51
+ == Attributes, values, and mappings
52
+
53
+ An attribute has a name, a tagged type, and only the optional declarations that
54
+ apply to it. Types are explicit: `{kind:"builtin",name:"string"}`;
55
+ `{kind:"model",id:"Example::Child@default"}`; or
56
+ `{kind:"value",id:"Example::Code@default"}`. A value type records a builtin
57
+ base and its facets. Trusted target bindings are supplied separately by stable
58
+ ID; a document never supplies code to evaluate.
59
+
60
+ A scalar omits `collection`. A collection has inclusive `min` and `max` bounds;
61
+ `max:null` means unbounded. Defaults distinguish absent from present-null:
62
+ `{"present":false}` versus `{"present":true,"value":null}`. False and empty
63
+ values are also preserved. Enum values keep their types. Polymorphism uses an
64
+ explicit discriminator attribute and a map from wire values to model IDs.
65
+ References identify their target model ID.
66
+
67
+ XML mappings may declare a root, namespace policy, ordered or mixed content,
68
+ sequence/choice bounds, and element, attribute, or content rules. Namespace
69
+ policy is exactly one of `{"mode":"inherit"}`,
70
+ `{"mode":"unqualified"}`, or
71
+ `{"mode":"uri","uri":"…","prefix":"…"}`. An absent namespace
72
+ policy means the documented Ruby default; it is not inferred from truthiness.
73
+ Aliases and sequence members preserve their declared order. JSON and YAML
74
+ mappings use key rules plus typed neutral `root_mappings` and `child_mappings`.
75
+
76
+ Ordinary declarative ordered and mixed content are supported by the contract.
77
+ Per-instance order uses the reserved `__lml_content` member, version 1. Its
78
+ tokens refer to a member and collection index, or carry literal text/CDATA.
79
+ Tokens control serialization order; grouped member traversal does not. Missing
80
+ indices, duplicate or inconsistent references, a source member with the reserved
81
+ name, or imperative order callbacks are rejected. This representation does not
82
+ change MML or replace instance order with a fixed sequence.
83
+
84
+ == Portable types and exact values
85
+
86
+ |===
87
+ | LML type | Portable representation | Notes
88
+
89
+ | String-like values, including token, URI, email, hostname, and IP
90
+ | UTF-8 string
91
+ | Declared lexical facets are retained.
92
+
93
+ | Boolean
94
+ | JSON boolean
95
+ | XML uses its declared lexical form.
96
+
97
+ | Integer and exact integer
98
+ | Decimal digits as a string at exact-value boundaries
99
+ | Structural bounds remain JSON integers; no IEEE-754 intermediate is allowed.
100
+
101
+ | Decimal and exact rational
102
+ | Decimal string
103
+ | Preserve authored lexical zeros where relevant. A reduced rational with a denominator containing primes other than 2 or 5 raises `nonterminating_rational` for decimal output.
104
+
105
+ | Date/time/duration
106
+ | Original declared lexical form
107
+ | Preserve timezone and lexical distinctions.
108
+
109
+ | QName
110
+ | Namespace URI and local-name pair
111
+ | The XML mapping resolves prefixes.
112
+
113
+ | Binary
114
+ | Declared base64 or hex string
115
+ | Runtime targets use byte containers.
116
+
117
+ | Symbol, hash, model, reference, union, enum, named XML ID/custom type
118
+ | Typed value, neutral tree, or stable ID as appropriate
119
+ | A custom type needs a trusted target binding and declared base/facets.
120
+
121
+ | Float, double, or unsupported platform type
122
+ | No lossy portable fallback
123
+ | Reject as `unsupported_type` unless an explicit lossless lexical contract exists.
124
+ |===
125
+
126
+ Portable exact codecs are opt-in and do not change existing Ruby serializers.
127
+ Missing and null remain distinct in every target. Source lexical values are kept
128
+ separately when precision or trailing zeros matter.
129
+
130
+ == Canonical bytes and checksums
131
+
132
+ Canonical JSON is compact UTF-8, has no BOM or trailing newline, sorts object
133
+ keys recursively, and preserves array order. It uses only JSON-required escapes:
134
+ `/` and non-ASCII characters are not escaped, and strings are not Unicode
135
+ normalized. Strings must contain valid Unicode; structural numbers are bounded
136
+ integers and exact values are strings. YAML input must safely parse to the same
137
+ tree without classes or aliases.
138
+
139
+ A v1 checksum follows its existing rules. A v2 model checksum covers the full
140
+ model document. A bundle semantic checksum covers the bundle except `provenance`.
141
+ Both use `sha256:<lowercase-hex>`. Documents and bundles are immutable snapshots,
142
+ so caller mutation cannot silently change a pinned identity.
143
+
144
+ == Errors and manifests
145
+
146
+ Validation and projection errors expose `reason`, `model_id`, optional attribute,
147
+ format, or rule, and a JSON pointer `location`; legacy `reason`, `klass`, and
148
+ `detail` remain available. Contract error codes include `unsupported_version`,
149
+ `invalid_document`, `duplicate_id`, `dangling_reference`, `unknown_type`,
150
+ `unsupported_type`, `missing_type_binding`, `unsupported_format`,
151
+ `unsupported_mapping`, `non_serializable_default`, `lambda_default`,
152
+ `custom_initialize`, `imperative_element_order`, `invalid_ordered_content`,
153
+ `reserved_member`, `nonterminating_rational`, `unknown_discriminator`,
154
+ `round_trip_mismatch`, `checksum_mismatch`, `capability_missing`, and
155
+ `not_serializable`. A producer or consumer must fail with a named error rather
156
+ than silently dropping a declaration.
157
+
158
+ Artifact manifest version 1 records the LML bundle checksum, schema version 2,
159
+ pinned generator version, target (`ruby`, `ts`, `rust`, or `wasm`), capabilities,
160
+ corpus generation and digest, file paths and actual-byte digests, and dependency
161
+ revisions and digests. File and dependency entries are sorted. The manifest
162
+ digest is external and covers the complete canonical manifest, avoiding
163
+ self-reference. A consumer supplies the expected digest and version and verifies
164
+ files, corpus, and dependencies before loading. Paths stay inside the artifact
165
+ root; traversal and symlink escapes fail. Generated bytes may differ by target,
166
+ while semantic source and corpus identity agree. Provenance does not change
167
+ schema identity.
168
+
169
+ Replay indexes pin generation, source revision, model ID, LML checksum, format,
170
+ input, expected data/output, comparison mode, and expected error. Comparison is
171
+ `data`, `xml_tree` under a pinned canonicalization profile, or `bytes`. Byte
172
+ sensitive cases assert bytes separately. A runner reports expected and executed
173
+ case IDs and counts and exits nonzero for missing, unimplemented, or corrupt
174
+ cases. Each standalone package owns its index and manifest; no shared mutable
175
+ master index is required.
176
+
177
+ == Capability status and opt-in entry points
178
+
179
+ The contract is effective; command availability follows the implementation in
180
+ your installed release. The status below is anchored to issue #1033 base
181
+ `8a8ef040` and must be updated as implementation cards merge.
182
+
183
+ |===
184
+ | Surface | Status at the documented base
185
+
186
+ | Ruby v1 model export and source-drift verification
187
+ | Available through `Lutaml::Model::Lml.export` and `.verify`; v1 checksums remain stable.
188
+
189
+ | Validated v2 documents, graph bundles, manifests, and reconstruction
190
+ | Contract defined; implementation pending.
191
+
192
+ | TypeScript and Rust bundle consumers and generators
193
+ | Contract defined; implementation and package commands pending.
194
+
195
+ | WASM consumers and artifact verification
196
+ | Contract defined; implementation and package commands pending.
197
+
198
+ | CLI import/export/compile commands
199
+ | Pending; no stable command syntax is published yet.
200
+ |===
201
+
202
+ Use the current Ruby API to export a supported v1 projection and check that it
203
+ still matches its source class:
204
+
205
+ [source,ruby]
206
+ ----
207
+ document = Lutaml::Model::Lml.export(Example::Node)
208
+ puts document.to_json
209
+ puts document.checksum
210
+ Lutaml::Model::Lml.verify(document)
211
+ ----
212
+
213
+ This verification resolves the recorded Ruby model and re-exports its current
214
+ declarations. It detects source drift; it does not reconstruct a new class from
215
+ the document. The portable v2 graph exporter, validator, artifact verifier,
216
+ materializer, mapping compiler, and CLI are separate opt-in capabilities. Their
217
+ commands are pending implementation and will be documented with exact syntax
218
+ when they land. Import must validate first, then materialize models and apply
219
+ mappings; it must not evaluate document-provided code.
220
+
221
+ == Target-local behavior and package boundaries
222
+
223
+ LML stores declarations and mappings, not executable application behavior.
224
+ Custom initializers, Proc/delegated defaults, imperative ordered-element
225
+ callbacks, and custom serialization methods have no declarative equivalent and
226
+ remain named rejections. Keep writers, constructors, and application methods
227
+ handwritten in the target package and outside generated artifacts.
228
+
229
+ A compiler may bind a PARG rule to a stable LML class ID at compile time. For
230
+ coradoc M2, this hook lets grammar rules name model identities without embedding
231
+ Ruby constants or runtime code in an LML document. Ruby consumers may prepend an
232
+ external handwritten behavior module to a `Schema::ClassLoader`-generated class;
233
+ the behavior module belongs to the consumer and remains outside the pinned
234
+ artifact. Binding and prepend command/API details are pending until their
235
+ implementation lands.
236
+
237
+ Cross-language packages stay standalone: each owns its dependencies, manifest,
238
+ corpus pins, and CI. This keeps the contract usable if packages later move out of
239
+ `lutaml-model`.
240
+
241
+
242
+ == Explicit model choices (version 1)
243
+
244
+ A v2 model document may contain `choices` with `version: 1`,
245
+ `validation: "explicit"`, and an ordered `groups` array. Bundles containing
246
+ this field require the `model.choices.v1` capability. Documents without
247
+ choices retain their previous canonical form.
248
+
249
+ Each group contains nonnegative integer `min`, integer or null `max`
250
+ (null means unbounded), `format` (null or `"xml"`), and ordered `members`.
251
+ A member contains exactly one of `attribute` (a declared attribute name)
252
+ or `choice` (another complete group). XML sequence choices remain mapping
253
+ compositors and are independent of these model validation groups.
254
+
255
+ Import restores native Choice objects. Model choices run during explicit
256
+ `validate`/`validate!`, rather than adding group validation to construction
257
+ or codec I/O. Existing field/type validation remains independent. Nested
258
+ lower-bound failures mean that alternative is absent; nested upper-bound
259
+ failures propagate. A valid nested group counts as one alternative,
260
+ including a valid empty group. False and whitespace are present values.
261
+ Finite collection batches, optional collection emptiness, and XML render
262
+ policies retain the native Choice algorithm; vector lengths must not be
263
+ summed as alternative counts. Unsupported versions, formats, or missing
264
+ members are refused rather than discarded.
265
+
266
+
267
+ == Trusted named-value export declarations
268
+
269
+ `ValueDeclarations.new({ ScalarClass => { "base" => "string",
270
+ "facets" => { "enumeration" => ["a", "b"] } } }, version: 1)` is an
271
+ opt-in, caller-owned registry. Pass it as `value_declarations:` to
272
+ `Lml.export_bundle`. Registry keys are exact named source Class objects;
273
+ strings, aliases, and subclasses do not acquire a declaration by inference.
274
+ Declarations contain neutral data only. They never serialize or evaluate
275
+ cast callbacks. The caller must prove each declared base/facet projection
276
+ matches the source class in the exported attribute context.
277
+
278
+ The emitted graph retains the existing v2 named-value reference and
279
+ `value_types` base/facets representation. Registry versioning is separate
280
+ from the IR version. `registry.to_h` records version and source class names
281
+ for producer manifests. Canonical bundle identity includes the emitted
282
+ value-type definitions. A missing declaration keeps the existing refusal.
283
+
284
+ Ruby import still requires explicit native `type_bindings` by value-type
285
+ ID. Target bindings stay separate from declaration bytes. Unsupported or
286
+ non-equivalent scalar behavior needs an honest trusted target binding;
287
+ it must not be replaced by an inferred XSD normalization. Qualified
288
+ attribute QNames are exported using the native namespace resolver and
289
+ restored with explicit qualified form when the attribute belongs to its
290
+ model namespace. Unrelated URI mappings remain refused by the Ruby DSL.
@@ -146,9 +146,12 @@ Each row is the compiled form of one mapping rule:
146
146
  |===
147
147
 
148
148
  The in-memory precedent for this tuple is the shipped row shape
149
- `[rule, attr, kind, type, child_rows, child_register]`; the wire form
150
- replaces the Ruby object references (rule, attr, type, class) with
151
- portable identifiers.
149
+ `[rule, attr, kind, type, child_rows, child_register, discriminator,
150
+ absent_action]`. The seventh slot is the child's class-level
151
+ discriminator rule (`polymorphic_map:`) for `model` rows, resolved per
152
+ document; the eighth is the compiled absent-key action (<<absent>>).
153
+ The wire form replaces the Ruby object references (rule, attr, type,
154
+ class) with portable identifiers.
152
155
 
153
156
  The plan graph is a graph, not a tree. A recursive model graph — a tree
154
157
  whose nodes reference their own type, directly or through other model
@@ -187,14 +190,32 @@ shapes that are not ops-expressible — are **refusal gates**
187
190
  `type.cast(v)` is equivalent to `cast_value` — this equivalence is
188
191
  what made the plan gates the correct cast-precondition set.
189
192
 
193
+ [[absent]]
190
194
  === Absent keys and defaults
191
195
 
192
196
  Present-key detection uses the absent-vs-nil distinction the compiled
193
197
  walk makes (`fetch` with a sentinel; present-nil values read as nil).
194
- Absent rows carry the rule forward for default application.
195
- Resolution (<<open>>): the absent set returns to Ruby for the
196
- interpretive default path first; engine-side default application
197
- lands as a coverage card carrying defaults in the plan.
198
+ Each row carries a compiled **absent action**, decided at plan compile
199
+ from the attribute definition (#1311):
200
+
201
+ - `set`: assign the attribute's default through its writer — nil when
202
+ it has none — exactly as the walk's absent path does. Scalar rows and
203
+ model rows without a default take this action; the implicit
204
+ empty-collection default (`lazy_collection_default?`) does too,
205
+ because its value is provably the collection itself, so the writer
206
+ receives the same argument either way.
207
+ - `skip`: do nothing. A child-map rule with no default owns this
208
+ action: the walk returns before assigning, leaving the constructor
209
+ seed in place.
210
+ - `walk`: route the row through the interpretive absent path. Explicit
211
+ defaults on model-valued and child-map rules take it, because whether
212
+ a proc default materializes a document the rule must translate is not
213
+ a per-class constant. Runtime value-map overrides (`nil:`, `empty:`,
214
+ `omitted:`) also force it for every absent row of the node.
215
+
216
+ The plan therefore carries the absent outcome for the proven shapes
217
+ natively; the interpretive path remains the correctness reference for
218
+ `walk` rows.
198
219
 
199
220
  === Emission (Ruby → engine)
200
221
 
@@ -226,9 +247,14 @@ construction, so hydration depth is bound by the heap and never by the
226
247
  VM stack (#1297). Children complete before the parent instance is
227
248
  constructed; siblings hydrate in row order and collection items in
228
249
  document order; each child is linked to its parent, and to its root
229
- when it has none, once the parent instance exists. A child shape the
230
- plan does not cover unwinds the whole build to the fallback, which owns
231
- that shape's semantics and errors.
250
+ when it has none, once the parent instance exists. The frame's instance
251
+ is allocated through the compiled walk seed (`init_walk_state`); a
252
+ class with its own `initialize` runs that constructor body against the
253
+ seed with the generic attribute walk stood down (the #1059 contract),
254
+ so constructor-internal state and the generated defaults are identical
255
+ to the fallback's. A child shape the plan does not cover unwinds the
256
+ whole build to the fallback, which owns that shape's semantics and
257
+ errors.
232
258
 
233
259
  Parse errors: the engine raises the strict-parse contract (the
234
260
  `strict:` kwarg lineage — malformed input is a format error, never a
@@ -300,14 +326,15 @@ the gates table as the ledger.
300
326
  [[open]]
301
327
  == Resolutions (decided, with rationale)
302
328
 
303
- 1. *Defaults placement*: Ruby-side absent-row handling first
304
- (defaults apply through the interpretive absent path exactly as
305
- `kv_group_build` does today); engine-side default application
306
- lands as a coverage card carrying defaults in the plan.
307
- Rationale: the fallback is the correctness reference — shipping
308
- hydration before default relocation keeps the engine the strict
309
- subset; the measured win (the 61%) is in present-key casting,
310
- which this sequencing captures in full.
329
+ 1. *Defaults placement*: the absent action ships compiled per row
330
+ (#1311) — `set` rows assign the default through the writer, `skip`
331
+ rows leave the constructor seed, `walk` rows keep the interpretive
332
+ absent path. Rationale: the fallback remains the correctness
333
+ reference for the shapes whose outcome is not a per-class constant,
334
+ while the common shapes no longer pay a full rule-pipeline walk per
335
+ absent key — on the 3MB expressir wire those walks were ~three
336
+ quarters of the lane's samples. Engine-side default application
337
+ consumes the same per-row action rather than re-deriving it.
311
338
  2. *Custom type bindings*: accepted. Custom `Type::Value` subclasses
312
339
  ride the `Materialization` `type_bindings` pattern at plan level;
313
340
  unbound subclasses refuse to the fallback. Rationale: refusing
@@ -42,8 +42,15 @@ module Lutaml
42
42
  # lutaml-model#88: nil unless the mapping partitions a wire key
43
43
  # with when_attribute rules — the common case pays one scan.
44
44
  partition = kv_partition(rules)
45
+ # #1311 lever 3: parent/root are the same for every rule of one
46
+ # node, so one cast-options hash serves the whole rule walk and
47
+ # carries the memoized propagated child options across its
48
+ # child-valued attributes.
49
+ cast_options = { lutaml_parent: instance,
50
+ lutaml_root: instance.lutaml_root || instance }
45
51
  rules.each do |rule|
46
- process_mapping_rule(data, instance, format, rule, options, partition)
52
+ process_mapping_rule(data, instance, format, rule, options,
53
+ partition, cast_options)
47
54
  end
48
55
  collect_unmapped_keys(data, instance, mappings, rules)
49
56
 
@@ -264,10 +271,18 @@ module Lutaml
264
271
  # dispatch and registered type substitutions own their cast
265
272
  # (the per-rule walk threads them through cast options).
266
273
  return false if attr.collection? && attr.collection.is_a?(Range)
267
- return false if attr.polymorphic? || attr.union? ||
268
- attr.custom_collection?
274
+ return false if attr.union? || attr.custom_collection?
269
275
 
270
276
  type = attr.type(register)
277
+ # A polymorphic VALUE attribute (a model-typed attribute whose
278
+ # concrete class the walk resolves) owns its cast on the walk.
279
+ # A polymorphic_class flag on a SCALAR attribute marks the
280
+ # class's discriminator (`_class`): it is a plain scalar here —
281
+ # with or without the map on this rule, exactly as the walk
282
+ # reads it — and the concrete child class comes from each
283
+ # document at build time (kv_group_child_class).
284
+ return false if attr.polymorphic? &&
285
+ !(type.is_a?(Class) && type < Lutaml::Model::Type::Value)
271
286
  return false if Lutaml::Model::GlobalContext.context(register)
272
287
  .substitution_for(type).any?
273
288
 
@@ -284,7 +299,8 @@ module Lutaml
284
299
  rule.hash_mappings)
285
300
  return false unless child_plan
286
301
 
287
- rows << [rule, attr, :child_map, child_plan, nil, nil]
302
+ rows << [rule, attr, :child_map, child_plan, nil, nil, nil,
303
+ kv_absent_action(attr, :child_map)]
288
304
  next
289
305
  end
290
306
 
@@ -296,12 +312,18 @@ module Lutaml
296
312
 
297
313
  # child_register rides the row: the plan was BUILT under it,
298
314
  # and rebuilding the resolution per model row per document
299
- # cost a Concurrent::Map hop each time (TODO.perf 14).
300
- rows << [rule, attr, :model, type, child_rows, child_register]
315
+ # cost a Concurrent::Map hop each time (TODO.perf 14). The
316
+ # seventh slot is the child's class-level discriminator rule
317
+ # (polymorphic_map:), if any: the concrete class comes from
318
+ # each document, so these rows serve the fallthrough case.
319
+ poly = type.mappings_for(format, child_register)&.polymorphic_mapping
320
+ rows << [rule, attr, :model, type, child_rows, child_register, poly,
321
+ kv_absent_action(attr, :model)]
301
322
  elsif type.is_a?(Class) && type < Lutaml::Model::Type::Value &&
302
323
  !attr.value_policy.whole_value?(type) &&
303
324
  !Lutaml::Model::Attribute.custom_from_probe?(type)
304
- rows << [rule, attr, :scalar, nil, nil, nil]
325
+ rows << [rule, attr, :scalar, nil, nil, nil, nil,
326
+ kv_absent_action(attr, :scalar)]
305
327
  else
306
328
  return false
307
329
  end
@@ -312,12 +334,59 @@ module Lutaml
312
334
  Array(rule.name).each { |name| claimed[name.to_s] = true } if rule.name
313
335
  end
314
336
  claimed.freeze
315
- rows << [nil, nil, :unmapped, unmapped_target, claimed, nil]
337
+ rows << [nil, nil, :unmapped, unmapped_target, claimed, nil, nil, nil]
316
338
  end
317
339
  # No eligible rows at all (empty mapping) — nothing to gain.
318
340
  rows.empty? ? nil : rows
319
341
  end
320
342
 
343
+ # The absent-key outcome of a plan row, compiled once (#1311):
344
+ # the walk assigns the attribute's default through its writer —
345
+ # nil when the attribute has none — except for a child-map rule
346
+ # with no default, where it returns before assigning. The implicit
347
+ # empty-collection default is the one proc default whose value is
348
+ # provably the collection itself, so the writer sees the same
349
+ # argument either way. Explicit defaults on model-valued and
350
+ # child-map rules keep the walk: whether a proc default materializes
351
+ # a document the rule must translate is not a per-class constant.
352
+ def self.kv_absent_action(attr, kind)
353
+ case kind
354
+ when :scalar
355
+ :set
356
+ when :model, :child_map
357
+ return :set if attr.default_kind == :none
358
+ return :set if attr.lazy_collection_default?
359
+
360
+ :walk
361
+ else
362
+ :walk
363
+ end
364
+ end
365
+
366
+ # The concrete class behind a :model row whose declared type carries
367
+ # a class-level discriminator (polymorphic_map:), read from one
368
+ # document the way resolve_polymorphic reads it — the discriminator
369
+ # key, the map entry, Object.const_get — with an entry that resolves
370
+ # to the declared type itself falling through to the row's own rows.
371
+ # Returns [class, rows, register]: the concrete class hydrates through
372
+ # its own cached plan; nil when that plan is ineligible, so the node
373
+ # takes the walk (which owns the error for a missing discriminator).
374
+ def self.kv_group_child_class(type, rows, poly, doc, format, register)
375
+ key = doc[poly.name]
376
+ klass_name = key && poly.polymorphic_map[key]
377
+ return nil unless klass_name
378
+
379
+ klass = Object.const_get(klass_name)
380
+ return [type, rows, register] if klass == type
381
+
382
+ klass_register = Lutaml::Model::Register.resolve_for_child(klass,
383
+ register)
384
+ klass_rows = kv_group_plan(klass, format, klass_register)
385
+ return nil unless klass_rows
386
+
387
+ [klass, klass_rows, klass_register]
388
+ end
389
+
321
390
  # Class-level twin of the walk's child-map compile: the registry
322
391
  # lookups (child rules, per-attribute wire names, path casts)
323
392
  # resolve once per plan instead of once per node per child. nil
@@ -497,7 +566,7 @@ child_mappings)
497
566
  # the separate string_or_symbol_key? probe goes away.
498
567
  v = Lutaml::Model::Utils.fetch_str_or_sym(frame.doc, rule.name, MISSING)
499
568
  if v.equal?(MISSING)
500
- (frame.absent ||= []) << rule
569
+ (frame.absent ||= []) << row
501
570
  i += 1
502
571
  next
503
572
  end
@@ -547,11 +616,26 @@ child_mappings)
547
616
  private
548
617
 
549
618
  # :child when the frame's pending row has a document the plan
550
- # covers, :fallback otherwise.
619
+ # covers, :fallback otherwise. A :model row whose declared type
620
+ # carries a class-level discriminator (polymorphic_map:, the seventh
621
+ # slot) resolves the concrete class from EACH document, so the
622
+ # frame's request follows the document, not the row.
551
623
  def request_child(frame)
552
624
  document = frame.next_child_document
553
625
  return :fallback unless document
554
626
 
627
+ row = frame.rows[frame.pending_index]
628
+ if (poly = row[6])
629
+ resolved = self.class.kv_group_child_class(row[3], row[4], poly,
630
+ document, frame.format,
631
+ row[5])
632
+ return :fallback unless resolved
633
+
634
+ frame.request_transform = self.class.cached_transform(resolved[0],
635
+ resolved[2])
636
+ frame.request_rows = resolved[1]
637
+ frame.request_register = resolved[2]
638
+ end
555
639
  frame.request_doc = document
556
640
  :child
557
641
  end
@@ -587,9 +671,7 @@ child_mappings)
587
671
 
588
672
  instance.public_send(row[0].kv_setter, v)
589
673
  end
590
- frame.absent&.each do |rule|
591
- process_mapping_rule(frame.doc, instance, frame.format, rule, frame.options, nil)
592
- end
674
+ kv_apply_absent(frame, instance)
593
675
  frame.children&.each do |child|
594
676
  child.lutaml_parent = instance
595
677
  child.lutaml_root ||= instance.lutaml_root || instance
@@ -611,6 +693,35 @@ child_mappings)
611
693
  instance
612
694
  end
613
695
 
696
+ # Absent keys through the compiled per-row action (#1311) instead
697
+ # of the per-rule walk: on the expressir corpus the absent walks
698
+ # were ~three quarters of the lane's samples. A :set row assigns
699
+ # the attribute's default exactly as the walk would — the
700
+ # DEFAULT_VALUE_MAP sends the omitted sentinel to nil, and the
701
+ # writer casts and marks the value set; :skip leaves the constructor
702
+ # seed (child-map rules with no default). Runtime value-map
703
+ # overrides keep the walk: their outcome is not a per-class
704
+ # constant.
705
+ def kv_apply_absent(frame, instance)
706
+ return unless frame.absent
707
+
708
+ overrides = frame.options[:nil] || frame.options[:empty] ||
709
+ frame.options[:omitted]
710
+ frame.absent.each do |row|
711
+ rule = row[0]
712
+ action = overrides ? :walk : row[7]
713
+ case action
714
+ when :set
715
+ value = row[1].default_value(frame.register, instance)
716
+ value = nil if Lutaml::Model::Utils.uninitialized?(value)
717
+ instance.public_send(rule.kv_setter, value)
718
+ when :walk
719
+ process_mapping_rule(frame.doc, instance, frame.format, rule,
720
+ frame.options, nil)
721
+ end
722
+ end
723
+ end
724
+
614
725
  def process_rule!(instance, rule, hash, format, _mappings, options)
615
726
  return handle_delegate(instance, rule, hash, format) if rule.delegate
616
727
 
@@ -978,7 +1089,7 @@ child_mappings)
978
1089
  end
979
1090
 
980
1091
  def process_mapping_rule(doc, instance, format, rule, options = {},
981
- partition = nil)
1092
+ partition = nil, cast_options = nil)
982
1093
  plans = walk_plans_for(format)
983
1094
  plan = plans[rule] ||= build_walk_plan(format, rule)
984
1095
  kind = plan.kind
@@ -1035,7 +1146,7 @@ partition = nil)
1035
1146
  end
1036
1147
  unless kind == :hash_map
1037
1148
  value = cast_value(value, attr, format, rule,
1038
- instance)
1149
+ instance, cast_options)
1039
1150
  end
1040
1151
 
1041
1152
  # Range errors stay eager here. The over-count error only fires when the
@@ -1272,12 +1383,20 @@ partition = nil)
1272
1383
  end
1273
1384
  end
1274
1385
 
1275
- def cast_value(value, attr, format, rule, instance)
1276
- cast_options = rule.polymorphic ? { polymorphic: rule.polymorphic } : {}
1277
- cast_options[:lutaml_parent] = instance if instance
1278
- if instance
1279
- cast_options[:lutaml_root] =
1280
- (instance.lutaml_root || instance)
1386
+ def cast_value(value, attr, format, rule, instance, cast_options = nil)
1387
+ # #1311 lever 3: the node's shared cast-options hash replaces the
1388
+ # per-rule allocation; the rule's polymorphic list must not leak
1389
+ # into siblings, so it rides a copy.
1390
+ unless cast_options
1391
+ cast_options = {}
1392
+ cast_options[:lutaml_parent] = instance if instance
1393
+ if instance
1394
+ cast_options[:lutaml_root] =
1395
+ (instance.lutaml_root || instance)
1396
+ end
1397
+ end
1398
+ if rule.polymorphic
1399
+ cast_options = cast_options.merge(polymorphic: rule.polymorphic)
1281
1400
  end
1282
1401
  attr.cast(value, format, lutaml_register, cast_options)
1283
1402
  end
@@ -1261,17 +1261,22 @@ instance_object = nil)
1261
1261
  )
1262
1262
  end
1263
1263
 
1264
- propagated = Serialize::DeserializationContext.propagate(options)
1264
+ # #1311 lever 3: the child options are a per-node constant,
1265
+ # memoized on this node's cast-options hash instead of being
1266
+ # rebuilt (slice + merge) per attribute with a child value.
1267
+ child_options = Serialize::DeserializationContext.child_options(
1268
+ options, register
1269
+ )
1265
1270
  return klass.apply_mappings(
1266
- { content_attr => value }, format,
1267
- propagated.merge(register: register)
1271
+ { content_attr => value }, format, child_options
1268
1272
  )
1269
1273
  end
1270
1274
 
1271
1275
  if can_serialize?(klass, value, format, options)
1272
- propagated = Serialize::DeserializationContext.propagate(options)
1273
- klass.apply_mappings(value, format,
1274
- propagated.merge(register: register))
1276
+ child_options = Serialize::DeserializationContext.child_options(
1277
+ options, register
1278
+ )
1279
+ klass.apply_mappings(value, format, child_options)
1275
1280
  elsif needs_conversion?(klass, value)
1276
1281
  klass.public_send(:"from_#{format}", value)
1277
1282
  else