lutaml-model 0.8.203 → 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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/.gitattributes +5 -0
  3. data/.github/workflows/lml-conformance.yml +71 -0
  4. data/.gitignore +7 -0
  5. data/README.adoc +1 -0
  6. data/docs/_guides/lml-cross-language.adoc +128 -0
  7. data/docs/_references/lml-conformance.adoc +78 -0
  8. data/docs/_references/lml-contract.adoc +290 -0
  9. data/lib/lutaml/model/lml/artifact_verifier.rb +205 -0
  10. data/lib/lutaml/model/lml/bundle.rb +171 -0
  11. data/lib/lutaml/model/lml/document.rb +46 -10
  12. data/lib/lutaml/model/lml/document_validator.rb +840 -0
  13. data/lib/lutaml/model/lml/exporter/v1_projector.rb +102 -0
  14. data/lib/lutaml/model/lml/exporter/v2_projector.rb +401 -0
  15. data/lib/lutaml/model/lml/exporter.rb +223 -87
  16. data/lib/lutaml/model/lml/graph_exporter.rb +248 -0
  17. data/lib/lutaml/model/lml/importer.rb +180 -0
  18. data/lib/lutaml/model/lml/mapping_compiler.rb +401 -0
  19. data/lib/lutaml/model/lml/materialization.rb +257 -0
  20. data/lib/lutaml/model/lml/ordered_content.rb +577 -0
  21. data/lib/lutaml/model/lml/portable_json.rb +385 -0
  22. data/lib/lutaml/model/lml/rejected_error.rb +64 -15
  23. data/lib/lutaml/model/lml/round_trip.rb +86 -0
  24. data/lib/lutaml/model/lml/value_declarations.rb +84 -0
  25. data/lib/lutaml/model/lml.rb +61 -0
  26. data/lib/lutaml/model/schema/definitions/attribute.rb +4 -2
  27. data/lib/lutaml/model/schema/registry_generator.rb +1 -1
  28. data/lib/lutaml/model/schema/renderers/member_decls.rb +1 -0
  29. data/lib/lutaml/model/schema/xml_compiler/spec_builder/members.rb +10 -0
  30. data/lib/lutaml/model/sequence.rb +7 -0
  31. data/lib/lutaml/model/version.rb +1 -1
  32. data/lib/lutaml/xml/leptris/native_emission.rb +4 -0
  33. data/lib/lutaml/xml/leptris/plan_serializer.rb +14 -9
  34. data/schema/lml/document.schema.json +179 -0
  35. data/scripts/lml/export_choices.rb +57 -0
  36. data/scripts/lml/export_conformance.rb +23 -0
  37. data/scripts/lml/export_mml.rb +253 -0
  38. data/scripts/lml/export_preservation.rb +421 -0
  39. data/scripts/lml/verify_artifacts.rb +31 -0
  40. data/spec/fixtures/lml_artifacts/model.json +1 -0
  41. data/spec/fixtures/lml_artifacts/valid.json +1 -0
  42. data/spec/fixtures/lml_artifacts/valid.sha256 +1 -0
  43. data/spec/fixtures/lml_conformance/core/index.json +1 -0
  44. data/spec/fixtures/lml_conformance/core/manifest.json +1 -0
  45. data/spec/fixtures/lml_conformance/core/schema.json +1 -0
  46. data/spec/fixtures/lml_conformance/core/schema.yaml +79 -0
  47. data/spec/fixtures/lml_conformance/float_vectors.generator.rb +60 -0
  48. data/spec/fixtures/lml_conformance/float_vectors.json +21550 -0
  49. data/spec/fixtures/lml_conformance/preservation/index.json +1 -0
  50. data/spec/fixtures/lml_conformance/preservation/manifest.json +1 -0
  51. data/spec/fixtures/lml_conformance/preservation/schema.json +1 -0
  52. data/spec/fixtures/lml_conformance/preservation/schema.yaml +319 -0
  53. data/spec/fixtures/lml_conformance/r2_refusals.generator.rb +153 -0
  54. data/spec/fixtures/lml_conformance/r2_refusals.json +1662 -0
  55. data/spec/fixtures/lml_conformance/ruby_portable_interop.generator.rb +40 -0
  56. data/spec/fixtures/lml_conformance/ruby_portable_interop.json +1 -0
  57. data/spec/fixtures/lml_contract/bundle.json +81 -0
  58. data/spec/fixtures/lml_contract/manifest.json +30 -0
  59. data/spec/fixtures/lml_contract/v1_unit.canonical.json +1 -0
  60. data/spec/fixtures/lml_contract/v1_unit.json +1 -0
  61. data/spec/fixtures/lml_contract/v2_node.canonical.json +1 -0
  62. data/spec/fixtures/lml_contract/v2_node.json +32 -0
  63. data/spec/fixtures/lml_mml/inventory.json +1 -0
  64. data/spec/fixtures/lml_mml/manifest.json +1 -0
  65. data/spec/fixtures/lml_mml/oracle.json +1 -0
  66. data/spec/fixtures/lml_mml/v3-mi-mixed.json +1 -0
  67. data/spec/fixtures/lml_mml/v3-mi-mixed.yaml +970 -0
  68. data/spec/fixtures/lml_mml/v4-mi-mixed.json +1 -0
  69. data/spec/fixtures/lml_mml/v4-mi-mixed.yaml +1516 -0
  70. data/spec/fixtures/lml_mml_materialization/replay.rb +37 -0
  71. data/spec/lutaml/model/lml_any_attribute_spec.rb +91 -0
  72. data/spec/lutaml/model/lml_artifact_verifier_spec.rb +86 -0
  73. data/spec/lutaml/model/lml_builtin_types_spec.rb +49 -0
  74. data/spec/lutaml/model/lml_conformance_spec.rb +178 -0
  75. data/spec/lutaml/model/lml_document_spec.rb +279 -0
  76. data/spec/lutaml/model/lml_export_validation_spec.rb +96 -0
  77. data/spec/lutaml/model/lml_exporter_spec.rb +127 -5
  78. data/spec/lutaml/model/lml_graph_exporter_spec.rb +205 -0
  79. data/spec/lutaml/model/lml_importer_spec.rb +290 -0
  80. data/spec/lutaml/model/lml_input_hardening_spec.rb +156 -0
  81. data/spec/lutaml/model/lml_mapping_compiler_spec.rb +256 -0
  82. data/spec/lutaml/model/lml_materialization_spec.rb +138 -0
  83. data/spec/lutaml/model/lml_mml_materialization_spec.rb +54 -0
  84. data/spec/lutaml/model/lml_mml_pilot_spec.rb +150 -0
  85. data/spec/lutaml/model/lml_model_choices_spec.rb +88 -0
  86. data/spec/lutaml/model/lml_ordered_content_spec.rb +243 -0
  87. data/spec/lutaml/model/lml_portable_json_spec.rb +310 -0
  88. data/spec/lutaml/model/lml_preservation_spec.rb +211 -0
  89. data/spec/lutaml/model/lml_review_export_spec.rb +247 -0
  90. data/spec/lutaml/model/lml_review_import_spec.rb +390 -0
  91. data/spec/lutaml/model/lml_review_misc_spec.rb +152 -0
  92. data/spec/lutaml/model/lml_review_round4_spec.rb +200 -0
  93. data/spec/lutaml/model/lml_review_round5_spec.rb +194 -0
  94. data/spec/lutaml/model/lml_ruby_interop_fixture_spec.rb +37 -0
  95. data/spec/lutaml/model/lml_shared_corpus_spec.rb +132 -0
  96. data/spec/lutaml/model/lml_value_declarations_spec.rb +128 -0
  97. data/spec/lutaml/model/schema/class_loader_spec.rb +51 -0
  98. data/spec/lutaml/model/schema/xml_compiler_runtime_spec.rb +20 -0
  99. data/spec/lutaml/model/sequence_spec.rb +48 -0
  100. data/spec/lutaml/xml/cdata_emission_spec.rb +68 -0
  101. data/spec/support/lml_any_attribute_fixtures.rb +26 -0
  102. data/spec/support/lml_conformance.rb +292 -0
  103. data/spec/support/lml_corpus.rb +75 -0
  104. data/spec/support/lml_export_fixtures.rb +190 -0
  105. data/spec/support/lml_graph_fixtures.rb +108 -0
  106. data/spec/support/lml_import_fixtures.rb +52 -0
  107. data/spec/support/lml_mapping_fixtures.rb +170 -0
  108. data/spec/support/lml_materialization_fixtures.rb +53 -0
  109. data/spec/support/lml_model_choices_fixtures.rb +150 -0
  110. data/spec/support/lml_order_fixtures.rb +151 -0
  111. metadata +92 -2
  112. data/lib/lutaml/model/schema/schema_builder/nokogiri.rb +0 -41
@@ -0,0 +1,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "export_preservation"
4
+
5
+ # Real source-model oracles; the original MML classes are loaded only on request.
6
+ module LmlMml
7
+ SOURCE_REVISION = "d826d80f6b1477569c8320ccd945268a6ce1062f"
8
+ SOURCE_VERSION = "2.4.7"
9
+ SOURCE_SPECS = {
10
+ "ordered_content_spec.rb" => "sha256:b776a2a40a2ad8fcfdeb0363571b8638437868cdcb169492d9a61d3e036235ab",
11
+ "v3_spec.rb" => "sha256:0221940af4e7aae3226885bd789ae66a632b500ae77fef77c289ecfff4ab9ac9",
12
+ "v4_spec.rb" => "sha256:4fa8b613b26c7d1d435309df5d1b76fae727aad232f859d38a974e69bdfbe201",
13
+ }.freeze
14
+ SOURCE_DIGEST = "sha256:271bd0ed0256a02784b35aaa99e7f0aaf0ba11abc64ed974d24025375b4f9829"
15
+ FRAMEWORK_REVISION = "4e75c92b7d9ab3e3aa5f4f90af4a9ce860c76f72"
16
+ PRESERVATION_REVISION = "9716740b6b7feb755b8557a2bfab89d066e855bd"
17
+ NAMESPACE = "http://www.w3.org/1998/Math/MathML"
18
+ PACKAGE = File.expand_path("../../spec/fixtures/lml_mml", __dir__)
19
+
20
+ module_function
21
+
22
+ def source_root
23
+ ENV["LML_MML_ROOT"] || Gem.path.map { |path| File.join(path, "gems", "mml-#{SOURCE_VERSION}") }
24
+ .find { |path| File.directory?(path) } || raise(ArgumentError, "set LML_MML_ROOT to the pinned mml source")
25
+ end
26
+
27
+ def source_digest(root)
28
+ digest = Digest::SHA256.new
29
+ Dir.glob(File.join(root, "lib/**/*.rb"), sort: false).sort.each do |path|
30
+ digest.update("#{path.delete_prefix("#{root}/")}\0#{File.binread(path)}\0")
31
+ end
32
+ "sha256:#{digest.hexdigest}"
33
+ end
34
+
35
+ def load_source(root = source_root)
36
+ root = File.expand_path(root)
37
+ unless source_digest(root) == SOURCE_DIGEST
38
+ raise ArgumentError, "mml source digest differs from #{SOURCE_REVISION} (#{SOURCE_VERSION})"
39
+ end
40
+
41
+ $LOAD_PATH.unshift(File.join(root, "lib"))
42
+ require "mml"
43
+ require "mml/version"
44
+ raise ArgumentError, "expected mml #{SOURCE_VERSION}" unless Mml::VERSION == SOURCE_VERSION
45
+
46
+ [Mml::V2, Mml::V3, Mml::V4].each do |version|
47
+ configuration = version::Configuration
48
+ configuration.populate_context! unless configuration.context
49
+ end
50
+ loaded = $LOADED_FEATURES.find { |path| path.end_with?("/mml.rb") }
51
+ unless loaded == File.join(root, "lib/mml.rb")
52
+ raise ArgumentError, "mml was already loaded from a different source"
53
+ end
54
+
55
+ root
56
+ end
57
+
58
+ def cases
59
+ mixed = %(<mi xmlns="#{NAMESPACE}" mathvariant="bold">x<malignmark/>y<mglyph src="g.png" alt="g"/>z</mi>)
60
+ nested = %(<math xmlns="#{NAMESPACE}" display="block"><mrow><mi>a</mi><mo>+</mo><mfrac><mi>x<malignmark/>y</mi><mrow><mn>1</mn><mo>+</mo><mn>2</mn></mrow></mfrac><mi>b</mi></mrow><mi>c</mi></math>)
61
+ [3, 4].flat_map do |version|
62
+ [["v#{version}-mi-mixed", "Mi", mixed], ["v#{version}-math-nested", "Math", nested]].map do |id, name, input|
63
+ { "id" => id, "model_id" => "Mml::V#{version}::#{name}@mml_v#{version}",
64
+ "register" => "mml_v#{version}", "input" => input }
65
+ end
66
+ end
67
+ end
68
+
69
+ def normalize(value, register, identities = {})
70
+ case value
71
+ when Lutaml::Model::UninitializedClass then { "state" => "absent" }
72
+ when Array then value.map { |item| normalize(item, register, identities) }
73
+ when Lutaml::Model::Serialize
74
+ klass = value.class
75
+ model_id = identities.fetch(klass) { "#{klass.name}@#{register}" }
76
+ attributes = klass.attributes(register).to_h do |name, _attribute|
77
+ [name.to_s, normalize(value.public_send(name), register, identities)]
78
+ end
79
+ descriptor = Lutaml::Model::Lml::OrderedContent.descriptor_for(
80
+ klass, mapping: klass.mappings_for(:xml, register), register: register
81
+ )
82
+ attributes["__lml_content"] = Lutaml::Model::Lml::OrderedContent.capture(descriptor, value) if descriptor
83
+ attributes.merge("__lml_model" => model_id)
84
+ when Integer then value.to_s
85
+ else value
86
+ end
87
+ end
88
+
89
+ def replay(entry, klass, identities = {})
90
+ register = entry.fetch("register").to_sym
91
+ Lutaml::Model::Config.with_adapter(xml: :nokogiri) do
92
+ record = klass.from_xml(entry.fetch("input"), register: register)
93
+ output = record.to_xml(register: register)
94
+ { "data" => normalize(record, register, identities), "output" => output,
95
+ "tree" => LmlPreservation.xml_tree(output) }
96
+ end
97
+ end
98
+
99
+ def refusal(error)
100
+ { "reason" => error.reason.to_s, "model" => error.klass.to_s,
101
+ "detail" => error.detail, "location" => error.location }.compact
102
+ end
103
+
104
+ def inventory
105
+ [Mml::V2, Mml::V3, Mml::V4].map do |version|
106
+ register = version::Configuration.context_id
107
+ registry = version::Configuration.context.registry
108
+ classes = registry.names.map { |name| registry.lookup(name) }.uniq.sort_by(&:name)
109
+ declarations = classes.map do |klass|
110
+ mapping = klass.mappings_for(:xml, register)
111
+ source = { "model" => klass.name, "source_ordered" => mapping.ordered?,
112
+ "source_mixed_content" => mapping.mixed_content?,
113
+ "source_ordered_content" => !!(mapping.ordered? || mapping.mixed_content?),
114
+ "float_attributes" => klass.attributes(register).values.select { |attribute| attribute.unresolved_type == :float }.map { |attribute| attribute.name.to_s } }
115
+ begin
116
+ document = Lutaml::Model::Lml::Exporter.project(klass, register: register)
117
+ source.merge("ordered_content" => !!document["ordered_content"])
118
+ rescue Lutaml::Model::Lml::RejectedError => e
119
+ source.merge(refusal(e))
120
+ end
121
+ end
122
+ { "version" => version.name, "register" => register.to_s,
123
+ "registered_count" => classes.size, "exported_count" => declarations.count { |entry| !entry.key?("reason") },
124
+ "source_ordered_count" => declarations.count { |entry| entry["source_ordered_content"] },
125
+ "exported_ordered_count" => declarations.count { |entry| entry["ordered_content"] },
126
+ "float_ordered_count" => declarations.count do |entry|
127
+ entry["ordered_content"] && entry["float_attributes"].any?
128
+ end,
129
+ "declarations" => declarations }
130
+ end
131
+ end
132
+
133
+ def source_oracles
134
+ cases.map do |entry|
135
+ klass = Object.const_get(entry.fetch("model_id").split("@").first)
136
+ entry.merge("expected" => replay(entry, klass))
137
+ end
138
+ end
139
+
140
+ def source_graph(root, register)
141
+ seen = {}
142
+ queue = [root]
143
+ until queue.empty?
144
+ klass = queue.shift
145
+ next if seen.key?(klass)
146
+
147
+ children = klass.attributes(register).values.filter_map do |attribute|
148
+ type = attribute.type(register)
149
+ type if type.is_a?(Class) && type.include?(Lutaml::Model::Serialize)
150
+ end.uniq
151
+ seen[klass] = children
152
+ queue.concat(children)
153
+ end
154
+ seen.to_h do |klass, children|
155
+ ["#{klass.name}@#{register}", children.map { |child| "#{child.name}@#{register}" }.sort]
156
+ end.sort.to_h
157
+ end
158
+
159
+ def graph_exports
160
+ cases.to_h do |entry|
161
+ klass = Object.const_get(entry.fetch("model_id").split("@").first)
162
+ register = entry.fetch("register").to_sym
163
+ references = source_graph(klass, register)
164
+ bundle = Lutaml::Model::Lml.export_bundle([klass], register: register)
165
+ [entry.fetch("id"), { "bundle" => bundle.to_h, "checksum" => bundle.checksum,
166
+ "model_count" => bundle.models.size, "source_references" => references }]
167
+ rescue Lutaml::Model::Lml::RejectedError => e
168
+ [entry.fetch("id"), { "refusal" => refusal(e), "source_references" => references }]
169
+ end
170
+ end
171
+
172
+ def existing_exclusions(root, versions)
173
+ { "reported_historical_ordered_refusals" => 191, "historical_ordered_model_count_matched" => versions.sum { |version| version.fetch("source_ordered_count") } == 191,
174
+ "source_specs" => SOURCE_SPECS.map do |name, digest|
175
+ path = File.join(root, "spec/mml", name)
176
+ if File.file?(path) && LmlPreservation.digest(File.binread(path)) != digest
177
+ raise ArgumentError, "mml source expectation differs: #{name}"
178
+ end
179
+
180
+ { "path" => "spec/mml/#{name}", "sha256" => digest }
181
+ end,
182
+ "v3" => { "existing_filters" => ["share requires XInclude", "HTML span", "mathml entity", "foreign background/color attributes", "XML comments", "ErrorHandling"],
183
+ "negative_tests_pending" => "Parser does not validate MathML schema compliance",
184
+ "available_fixture_count" => Dir.glob(File.join(root, "spec/fixtures/mml3-testsuite/Math/testsuite/build/main/**/*.mml")).size },
185
+ "v4" => { "existing_filters" => ["HTML elements", "unknown namespace elements", "nonempty none/mprescripts/mspace", "mtd outside table", "br inside mtext"],
186
+ "available_fixture_count" => Dir.glob(File.join(root, "spec/fixtures/mmlcore-testsuite/mathml/**/*.mml")).size } }
187
+ end
188
+
189
+ def files(root = source_root)
190
+ root = load_source(root)
191
+ exports = graph_exports
192
+ versions = inventory
193
+ payloads = {
194
+ "oracle.json" => LmlPreservation.json("cases" => source_oracles),
195
+ "inventory.json" => LmlPreservation.json("versions" => versions, "existing_exclusions" => existing_exclusions(root, versions)),
196
+ }
197
+ exports.each do |id, result|
198
+ next unless result.key?("bundle")
199
+
200
+ payloads["#{id}.json"] = LmlPreservation.json(result.fetch("bundle"))
201
+ payloads["#{id}.yaml"] = YAML.safe_dump(LmlPreservation.canonical(result.fetch("bundle")))
202
+ end
203
+ manifest = {
204
+ "generation" => "mml-pilot-v1", "source_revision" => SOURCE_REVISION, "source_version" => SOURCE_VERSION,
205
+ "source_digest" => SOURCE_DIGEST, "framework_revision" => FRAMEWORK_REVISION,
206
+ "preservation_revision" => PRESERVATION_REVISION, "case_count" => cases.size,
207
+ "graphs" => exports.transform_values { |result| result.except("bundle") },
208
+ "files" => payloads.sort.map { |path, bytes| { "path" => path, "sha256" => LmlPreservation.digest(bytes) } }
209
+ }
210
+ payloads.merge("manifest.json" => LmlPreservation.json(manifest))
211
+ end
212
+
213
+ # Package drift is always an error. A refused closed graph is reported as
214
+ # "refused" and becomes an error only with require_complete.
215
+ def check(directory, payloads, require_complete: false)
216
+ errors = payloads.filter_map do |path, bytes|
217
+ full_path = File.join(directory, path)
218
+ { "id" => path, "error" => "missing or changed file" } unless File.file?(full_path) && File.binread(full_path) == bytes.b
219
+ end
220
+ (Dir.children(directory) - payloads.keys).each { |path| errors << { "id" => path, "error" => "unknown file" } }
221
+ manifest = JSON.parse(payloads.fetch("manifest.json"))
222
+ refused = manifest.fetch("graphs").select { |_id, graph| graph.key?("refusal") }
223
+ refused.each do |id, graph|
224
+ errors << { "id" => id, "error" => "closed graph refused", "refusal" => graph.fetch("refusal") } if require_complete
225
+ end
226
+ { "expected_count" => cases.size, "exported_count" => manifest.fetch("graphs").count { |_id, graph| graph.key?("checksum") },
227
+ "refused" => refused.transform_values { |graph| graph.fetch("refusal") }, "errors" => errors }
228
+ end
229
+
230
+ def main(arguments = ARGV)
231
+ options = { check: false, complete: false, package: PACKAGE, root: nil }
232
+ OptionParser.new do |parser|
233
+ parser.on("--check") { options[:check] = true }
234
+ parser.on("--require-complete") { options[:complete] = true }
235
+ parser.on("--package DIRECTORY") { |path| options[:package] = path }
236
+ parser.on("--mml-root DIRECTORY") { |path| options[:root] = path }
237
+ end.parse!(arguments)
238
+ payloads = files(options[:root] || source_root)
239
+ unless options[:check]
240
+ FileUtils.mkdir_p(options[:package])
241
+ payloads.each { |path, bytes| File.binwrite(File.join(options[:package], path), bytes) }
242
+ end
243
+ # The large payloads are not carried in the working tree; a check
244
+ # reads them from the corpus first (see spec/support/lml_corpus.rb).
245
+ require_relative "../../spec/support/lml_corpus"
246
+ LmlCorpus.materialize!(options[:package]) if options[:check]
247
+ report = check(options[:package], payloads, require_complete: options[:complete])
248
+ puts LmlPreservation.json(report)
249
+ report.fetch("errors").empty? ? 0 : 1
250
+ end
251
+ end
252
+
253
+ exit LmlMml.main if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,421 @@
1
+ # frozen_string_literal: true
2
+
3
+ $LOAD_PATH.unshift(File.expand_path("../../lib", __dir__))
4
+ require "lutaml/model"
5
+ require "json"
6
+ require "yaml"
7
+ require "digest"
8
+ require "rexml/document"
9
+ require "optparse"
10
+ require "fileutils"
11
+
12
+ # Ruby-authored preservation package; no dependency on another corpus index.
13
+ module LmlPreservation
14
+ GENERATION = "preservation-v1"
15
+ SOURCE_REVISION = "8a8ef040963b7965388b01b58af33af2b0995f91"
16
+ XML_PROFILE = "expanded-names-text-v1"
17
+
18
+ class Namespace < Lutaml::Xml::W3c::XmlNamespace
19
+ uri "urn:lml:preservation"
20
+ prefix_default "p"
21
+ element_form_default :qualified
22
+ end
23
+
24
+ class Namespaces < Lutaml::Model::Serializable
25
+ attribute :qualified, :string
26
+ attribute :plain, :string
27
+ xml do
28
+ root "record"
29
+ namespace Namespace
30
+ map_element "qualified", to: :qualified
31
+ map_element "plain", to: :plain, form: :unqualified
32
+ end
33
+ end
34
+
35
+ class Mixed < Lutaml::Model::Serializable
36
+ attribute :text, :string, collection: true
37
+ attribute :em, :string, collection: true
38
+ xml do
39
+ root "mixed"
40
+ mixed_content
41
+ map_content to: :text
42
+ map_element "em", to: :em
43
+ end
44
+ end
45
+
46
+ class Ordered < Lutaml::Model::Serializable
47
+ attribute :a, :string, collection: true
48
+ attribute :b, :string, collection: true
49
+ xml do
50
+ root "ordered", ordered: true
51
+ map_element "a", to: :a
52
+ map_element "b", to: :b
53
+ end
54
+ end
55
+
56
+ class Cdata < Lutaml::Model::Serializable
57
+ attribute :text, :string
58
+ xml do
59
+ root "cdata"
60
+ map_content to: :text, cdata: true
61
+ end
62
+ end
63
+
64
+ class States < Lutaml::Model::Serializable
65
+ attribute :value, :string
66
+ attribute :fallback, :string, default: "default"
67
+ attribute :items, :string, collection: true, initialize_empty: true
68
+ json do
69
+ map "value", to: :value, render_nil: true, render_empty: true
70
+ map "fallback", to: :fallback, render_default: true
71
+ map "items", to: :items, render_empty: true
72
+ end
73
+ end
74
+
75
+ class Bounded < Lutaml::Model::Serializable
76
+ attribute :items, :string, collection: 1..2
77
+ json { map "items", to: :items }
78
+ end
79
+
80
+ class TypedEnum < Lutaml::Model::Serializable
81
+ attribute :number, :integer, values: [1, 2]
82
+ attribute :flag, :boolean, values: [true, false]
83
+ json do
84
+ map "number", to: :number
85
+ map "flag", to: :flag
86
+ end
87
+ end
88
+
89
+ class Source < Lutaml::Model::Serializable
90
+ attribute :name, :string
91
+ json { map "name", to: :name }
92
+ end
93
+
94
+ Lutaml::Model::GlobalRegister.register(Lutaml::Model::Register.new(:oracle))
95
+
96
+ class Imported < Lutaml::Model::Serializable
97
+ import_model Source, :oracle
98
+ end
99
+
100
+ module_function
101
+
102
+ def canonical(value)
103
+ case value
104
+ when Hash then value.keys.sort.to_h { |key| [key, canonical(value.fetch(key))] }
105
+ when Array then value.map { |item| canonical(item) }
106
+ else value
107
+ end
108
+ end
109
+
110
+ def json(value)
111
+ JSON.generate(canonical(value))
112
+ end
113
+
114
+ def digest(bytes)
115
+ "sha256:#{Digest::SHA256.hexdigest(bytes)}"
116
+ end
117
+
118
+ def inputs
119
+ namespace_input = '<p:record xmlns:p="urn:lml:preservation"><p:qualified>Q</p:qualified><plain>P</plain></p:record>'
120
+ mixed_input = "<mixed>before<em>one</em>between<em>two</em>after</mixed>"
121
+ [
122
+ ["namespace-tree", Namespaces, "xml", "xml_tree", namespace_input],
123
+ ["namespace-bytes", Namespaces, "xml", "bytes", namespace_input],
124
+ ["mixed-order-tree", Mixed, "xml", "xml_tree", mixed_input],
125
+ ["mixed-order-bytes", Mixed, "xml", "bytes", mixed_input],
126
+ ["ordered-tree", Ordered, "xml", "xml_tree", "<ordered><b>one</b><a>two</a><b>three</b></ordered>"],
127
+ ["ordered-bytes", Ordered, "xml", "bytes", "<ordered><b>one</b><a>two</a><b>three</b></ordered>"],
128
+ ["cdata-bytes", Cdata, "xml", "bytes", "<cdata><![CDATA[a < b & c]]></cdata>"],
129
+ ["state-absent", States, "json", "data", "{}"],
130
+ ["state-null", States, "json", "data", '{"value":null,"fallback":null}'],
131
+ ["state-empty", States, "json", "data", '{"value":"","items":[]}'],
132
+ ["state-explicit-default", States, "json", "data", '{"fallback":"default"}'],
133
+ ["cardinality-valid", Bounded, "json", "data", '{"items":["one","two"]}'],
134
+ ["cardinality-invalid", Bounded, "json", "data", '{"items":["one","two","three"]}'],
135
+ ["cardinality-missing", Bounded, "json", "data", '{"items":[]}'],
136
+ ["typed-enum-valid", TypedEnum, "json", "data", '{"number":2,"flag":false}'],
137
+ ["typed-enum-invalid", TypedEnum, "json", "data", '{"number":3,"flag":true}'],
138
+ ["imported-context", Imported, "json", "data", '{"name":"contextual"}'],
139
+ ]
140
+ end
141
+
142
+ def model_id(klass)
143
+ "#{klass.name}@#{klass == Imported ? 'oracle' : 'default'}"
144
+ end
145
+
146
+ def neutral(value)
147
+ case value
148
+ when Lutaml::Model::UninitializedClass then { "state" => "absent" }
149
+ when Integer then value.to_s
150
+ when Array then value.map { |item| neutral(item) }
151
+ else value
152
+ end
153
+ end
154
+
155
+ def register_for(klass)
156
+ return :default unless klass == Imported
157
+
158
+ # GlobalContext.reset! removes contexts while GlobalRegister keeps registers.
159
+ if !Lutaml::Model::GlobalContext.context(:oracle) || !Lutaml::Model::GlobalRegister.lookup(:oracle)
160
+ Lutaml::Model::GlobalRegister.register(Lutaml::Model::Register.new(:oracle))
161
+ end
162
+ :oracle
163
+ end
164
+
165
+ def attributes_for(klass)
166
+ klass.attributes(register_for(klass))
167
+ end
168
+
169
+ def normalized(record, klass, input, format)
170
+ data = attributes_for(klass).keys.to_h { |name| [name.to_s, neutral(record.public_send(name))] }
171
+ if klass == States
172
+ authored = JSON.parse(input)
173
+ data = data.to_h do |name, value|
174
+ state = if authored.key?(name)
175
+ "present"
176
+ elsif name == "fallback"
177
+ "default"
178
+ elsif name == "items"
179
+ "initialized_empty"
180
+ else
181
+ "absent"
182
+ end
183
+ [name, { "state" => state, "value" => value }]
184
+ end
185
+ elsif [Mixed, Ordered].include?(klass) && format == "xml"
186
+ # Preserve real per-instance order through the Ruby serialized tree, and
187
+ # expose portable member/index tokens alongside the parsed member values.
188
+ counters = Hash.new(0)
189
+ data["__lml_content"] = record.element_order.map do |node|
190
+ member = node.element? ? node.name : "text"
191
+ kind = node.element? ? "element" : node.node_type.to_s
192
+ token = { "kind" => kind, "attribute" => member, "index" => counters[member] }
193
+ counters[member] += 1
194
+ token
195
+ end
196
+ end
197
+ data
198
+ end
199
+
200
+ def execute(entry, klass)
201
+ format = entry.fetch("format")
202
+ register = register_for(klass)
203
+ Lutaml::Model::Config.with_adapter(xml: :nokogiri, json: :standard) do
204
+ record = klass.public_send("from_#{format}", entry.fetch("input"), register: register)
205
+ errors = record.validate(register: register)
206
+ if errors.any?
207
+ return invalid_result(klass, format, errors)
208
+ end
209
+
210
+ { "data" => normalized(record, klass, entry.fetch("input"), format),
211
+ "output" => record.public_send("to_#{format}", register: register) }
212
+ end
213
+ rescue Lutaml::Model::CollectionCountOutOfRangeError, Lutaml::Model::InvalidValueError => e
214
+ invalid_result(klass, format, [e])
215
+ end
216
+
217
+ def invalid_result(klass, format, errors)
218
+ { "error" => { "reason" => "invalid_document", "model_id" => model_id(klass),
219
+ "format" => format, "location" => "/input",
220
+ "ruby_errors" => errors.map { |error| error.class.name } } }
221
+ end
222
+
223
+ def cases
224
+ inputs.map do |id, klass, format, comparison, input|
225
+ entry = { "id" => id, "model_id" => model_id(klass), "lml_checksum" => checksum,
226
+ "format" => format, "input" => input, "comparison" => comparison }
227
+ result = execute(entry, klass)
228
+ entry.merge("expected_data" => result["data"], "expected_output" => result["output"],
229
+ "expected_error" => result["error"])
230
+ end
231
+ end
232
+
233
+ def schema
234
+ models = inputs.map { |entry| entry[1] }.uniq.to_h do |klass|
235
+ fields = attributes_for(klass).map do |name, attribute|
236
+ builtin = if klass == TypedEnum && name == :number
237
+ "integer"
238
+ elsif klass == TypedEnum && name == :flag
239
+ "boolean"
240
+ else
241
+ "string"
242
+ end
243
+ collection = if [Mixed, Ordered, Bounded].include?(klass) || name == :items
244
+ { "min" => klass == Bounded ? 1 : 0, "max" => klass == Bounded ? 2 : nil }
245
+ else
246
+ false
247
+ end
248
+ field = { "name" => name.to_s, "type" => { "kind" => "builtin", "name" => builtin },
249
+ "required" => false, "collection" => collection,
250
+ "default" => name == :fallback ? { "present" => true, "value" => "default" } : { "present" => false },
251
+ "initialize_empty" => klass == States && name == :items }
252
+ field["values"] = attribute.options[:values] if klass == TypedEnum
253
+ field
254
+ end
255
+ document = { "lml" => 2, "model" => klass.name, "register" => klass == Imported ? "oracle" : "default",
256
+ "attributes" => fields, "mappings" => schema_mappings(klass, fields) }
257
+ document["ordered_content"] = { "member" => "__lml_content", "version" => 1 } if [Mixed, Ordered].include?(klass)
258
+ [model_id(klass), document]
259
+ end
260
+ { "lml_bundle" => 1, "roots" => models.keys.sort, "models" => models,
261
+ "value_types" => {}, "capabilities" => %w[json xml],
262
+ "provenance" => { "source_revision" => SOURCE_REVISION } }
263
+ end
264
+
265
+ def schema_mappings(klass, fields)
266
+ if [States, Bounded, TypedEnum, Imported].include?(klass)
267
+ return { "json" => { "rules" => fields.map do |field|
268
+ rule = { "key" => [field.fetch("name")], "to" => field.fetch("name") }
269
+ if klass == States
270
+ rule["render"] = case field.fetch("name")
271
+ when "value" then { "nil" => true, "empty" => true, "default" => false }
272
+ when "fallback" then { "default" => true }
273
+ else { "empty" => true }
274
+ end
275
+ end
276
+ rule
277
+ end } }
278
+ end
279
+ root = { Namespaces => "record", Mixed => "mixed", Ordered => "ordered", Cdata => "cdata" }.fetch(klass)
280
+ rules = fields.map do |field|
281
+ name = field.fetch("name")
282
+ content = name == "text"
283
+ namespace = if klass == Namespaces
284
+ name == "plain" ? { "mode" => "unqualified" } : { "mode" => "inherit" }
285
+ else
286
+ { "mode" => "inherit" }
287
+ end
288
+ rule = { "kind" => content ? "content" : "element", "to" => name, "namespace" => namespace }
289
+ rule["name"] = [name] unless content
290
+ rule["cdata"] = true if klass == Cdata
291
+ rule
292
+ end
293
+ namespace = klass == Namespaces ? { "mode" => "uri", "uri" => "urn:lml:preservation", "prefix" => "p" } : { "mode" => "inherit" }
294
+ { "xml" => { "root" => { "element" => root }, "namespace" => namespace, "rules" => rules } }
295
+ end
296
+
297
+ def checksum
298
+ digest(json(schema.except("provenance")))
299
+ end
300
+
301
+ def source_expectations
302
+ %w[mixed_content_spec.rb cdata_spec.rb collection_spec.rb register_spec.rb].map do |name|
303
+ path = "spec/lutaml/model/#{name}"
304
+ # Pin repository source text independent of Windows CRLF checkout conversion.
305
+ { "path" => path, "sha256" => digest(File.binread(File.expand_path("../../#{path}", __dir__)).gsub("\r\n", "\n")) }
306
+ end
307
+ end
308
+
309
+ def files
310
+ index = { "corpus" => 1, "generation" => GENERATION, "source_revision" => SOURCE_REVISION,
311
+ "xml_canon_profile" => XML_PROFILE, "wire_profile" => "ruby-native",
312
+ "data_profile" => "exact-values-decimal-v1",
313
+ "source_expectations" => source_expectations, "cases" => cases }
314
+ payload = { "index.json" => json(index), "schema.json" => json(schema), "schema.yaml" => YAML.safe_dump(canonical(schema)) }
315
+ manifest = { "manifest" => 1, "lml_checksum" => checksum, "schema_version" => 2,
316
+ "generator_version" => "ruby-preservation-oracle-v1", "target" => "ruby", "capabilities" => %w[json xml],
317
+ "corpora" => [{ "generation" => GENERATION, "sha256" => digest(payload.fetch("index.json")) }],
318
+ "files" => payload.sort.map { |path, bytes| { "path" => path, "sha256" => digest(bytes) } },
319
+ "dependencies" => [{ "name" => "lutaml-model", "revision" => SOURCE_REVISION,
320
+ "sha256" => digest(File.binread(File.expand_path("../../lutaml-model.gemspec", __dir__)).gsub("\r\n", "\n")) }] }
321
+ payload.merge("manifest.json" => json(manifest))
322
+ end
323
+
324
+ def xml_tree(bytes)
325
+ raise ArgumentError, "forbidden XML declaration" if bytes.match?(/<!DOCTYPE|<!ENTITY|<\?(?!xml\s)/i)
326
+
327
+ element = REXML::Document.new(bytes).root
328
+ xml_element(element)
329
+ end
330
+
331
+ def xml_element(element)
332
+ attrs = element.attributes.each_attribute.filter_map do |attribute|
333
+ next if attribute.expanded_name == "xmlns" || attribute.prefix == "xmlns"
334
+
335
+ [[attribute.namespace, attribute.name], attribute.value]
336
+ end.sort
337
+ children = element.children.each_with_object([]) do |child, result|
338
+ if child.is_a?(REXML::Element)
339
+ result << xml_element(child)
340
+ elsif child.is_a?(REXML::Text)
341
+ result.last.is_a?(String) ? result[-1] += child.value : result << child.value
342
+ else
343
+ raise ArgumentError, "unsupported XML node"
344
+ end
345
+ end
346
+ [[element.namespace, element.name], attrs, children]
347
+ end
348
+
349
+ def compare(entry, result)
350
+ return entry["expected_error"] == result["error"] ? nil : "error mismatch" if entry["expected_error"]
351
+ return "typed data mismatch" unless entry.fetch("expected_data") == result["data"]
352
+
353
+ expected = entry.fetch("expected_output")
354
+ actual = result.fetch("output")
355
+ equal = case entry.fetch("comparison")
356
+ when "bytes" then expected.b == actual.b
357
+ when "xml_tree" then xml_tree(expected) == xml_tree(actual)
358
+ when "data" then JSON.parse(expected) == JSON.parse(actual)
359
+ else false
360
+ end
361
+ equal ? nil : "output mismatch"
362
+ end
363
+
364
+ def check(directory)
365
+ index = JSON.parse(File.read(File.join(directory, "index.json")))
366
+ raise ArgumentError, "invalid index" unless index.is_a?(Hash) && index["cases"].is_a?(Array)
367
+
368
+ expected = cases.to_h { |entry| [entry.fetch("id"), entry] }
369
+ classes = inputs.to_h { |entry| [entry.first, entry[1]] }
370
+ executed = []
371
+ errors = []
372
+ index.fetch("cases").each do |entry|
373
+ unless entry.is_a?(Hash) && entry["id"].is_a?(String)
374
+ errors << { "id" => "package/cases", "error" => "invalid case" }
375
+ next
376
+ end
377
+ id = entry.fetch("id")
378
+ error = if !expected.key?(id)
379
+ "unknown case"
380
+ elsif executed.include?(id)
381
+ "duplicate case"
382
+ else
383
+ executed << id
384
+ entry == expected.fetch(id) ? compare(entry, execute(entry, classes.fetch(id))) : "changed case"
385
+ end
386
+ errors << { "id" => id, "error" => error } if error
387
+ end
388
+ (expected.keys - executed).each { |id| errors << { "id" => id, "error" => "missing case" } }
389
+ files.each do |path, bytes|
390
+ full_path = File.join(directory, path)
391
+ errors << { "id" => "package/#{path}", "error" => "missing or changed file" } unless File.file?(full_path) && File.binread(full_path) == bytes.b
392
+ end
393
+ (Dir.children(directory) - files.keys).each { |path| errors << { "id" => "package/#{path}", "error" => "unknown file" } }
394
+ unless YAML.safe_load_file(File.join(directory, "schema.yaml"), aliases: false) == JSON.parse(File.read(File.join(directory, "schema.json")))
395
+ errors << { "id" => "package/schema.yaml", "error" => "schema equivalence mismatch" }
396
+ end
397
+ { "expected_ids" => expected.keys, "executed_ids" => executed, "expected_count" => expected.size,
398
+ "executed_count" => executed.size, "errors" => errors }
399
+ rescue Errno::ENOENT, JSON::ParserError, Psych::Exception, KeyError, TypeError, ArgumentError => e
400
+ { "expected_ids" => inputs.map(&:first), "executed_ids" => [], "expected_count" => inputs.size,
401
+ "executed_count" => 0, "errors" => [{ "id" => "package", "error" => e.class.name }] +
402
+ inputs.map { |entry| { "id" => entry.first, "error" => "missing case" } } }
403
+ end
404
+
405
+ def main
406
+ options = { check: false, package: File.expand_path("../../spec/fixtures/lml_conformance/preservation", __dir__) }
407
+ OptionParser.new do |parser|
408
+ parser.on("--check") { options[:check] = true }
409
+ parser.on("--package DIRECTORY") { |path| options[:package] = path }
410
+ end.parse!
411
+ unless options[:check]
412
+ FileUtils.mkdir_p(options[:package])
413
+ files.each { |path, bytes| File.binwrite(File.join(options[:package], path), bytes) }
414
+ end
415
+ report = check(options[:package])
416
+ puts json(report)
417
+ report.fetch("errors").empty? ? 0 : 1
418
+ end
419
+ end
420
+
421
+ exit LmlPreservation.main if $PROGRAM_NAME == __FILE__