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,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model/lml"
4
+
5
+ module LmlValueDeclarationFixtures
6
+ class Code < Lutaml::Model::Type::String
7
+ VALUES = %w[a b].freeze
8
+
9
+ def self.cast(value, options = {})
10
+ return if value.nil?
11
+
12
+ super(value, options.dup.tap { |copy| copy[:values] ||= VALUES })
13
+ end
14
+ end
15
+
16
+ class QualifiedNamespace < Lutaml::Xml::Namespace
17
+ uri "urn:declared-values"
18
+ prefix_default "d"
19
+ attribute_form_default :qualified
20
+ end
21
+
22
+ class QualifiedModel < Lutaml::Model::Serializable
23
+ attribute :code, Code
24
+ xml do
25
+ root "qualified"
26
+ namespace QualifiedNamespace
27
+ map_attribute "code", to: :code
28
+ end
29
+ end
30
+
31
+ class Model < Lutaml::Model::Serializable
32
+ choice(min: 1, max: 1) do
33
+ attribute :code, Code, default: "a"
34
+ attribute :other, :string
35
+ end
36
+ json do
37
+ map "code", to: :code
38
+ map "other", to: :other
39
+ end
40
+ xml do
41
+ root "declared"
42
+ map_element "code", to: :code
43
+ map_element "other", to: :other
44
+ end
45
+ end
46
+ end
47
+
48
+ RSpec.describe Lutaml::Model::Lml::ValueDeclarations do
49
+ let(:source) { LmlValueDeclarationFixtures::Model }
50
+ let(:scalar) { LmlValueDeclarationFixtures::Code }
51
+ let(:definition) { { "base" => "string", "facets" => { "enumeration" => %w[a b] } } }
52
+ let(:registry) { described_class.new({ scalar => definition }) }
53
+ let(:lml) { Lutaml::Model::Lml }
54
+
55
+ it "keeps arbitrary named casters refused without explicit declarations" do
56
+ expect { lml.export_bundle(source) }.to raise_error(lml::RejectedError) { |error| expect(error.reason).to eq(:unsupported_type) }
57
+ end
58
+
59
+ it "exports named identity, declared facets, defaults and choices without flattening" do
60
+ tree = lml.export_bundle(source, value_declarations: registry).to_h
61
+ id = "#{scalar.name}@default"
62
+ expect(tree.fetch("value_types")).to eq(id => definition)
63
+ model = tree.fetch("models").values.first
64
+ expect(model.fetch("attributes").first.fetch("type")).to eq("kind" => "value", "id" => id)
65
+ expect(model.fetch("attributes").first.fetch("default")).to eq("present" => true, "value" => "a")
66
+ expect(model.fetch("choices").fetch("validation")).to eq("explicit")
67
+ expect(lml::Importer.bundle(tree).to_h).to eq(tree)
68
+ end
69
+
70
+ it "requires native bindings and preserves their source reader and validation behavior" do
71
+ bundle = lml.export_bundle(source, value_declarations: registry)
72
+ expect { lml.import_bundle(bundle) }.to raise_error(lml::RejectedError) { |error| expect(error.reason).to eq(:missing_type_binding) }
73
+ imported = lml.import_bundle(bundle, type_bindings: { "#{scalar.name}@default" => scalar }).fetch("#{source.name}@default")
74
+ [{ code: "a" }, { code: "b" }, { code: "a", other: "x" }].each do |input|
75
+ original = source.new(input)
76
+ actual = imported.new(input)
77
+ expect(actual.to_json).to eq(original.to_json)
78
+ expect(actual.to_xml).to eq(original.to_xml)
79
+ expect(actual.validate.map(&:class)).to eq(original.validate.map(&:class))
80
+ end
81
+ expect { imported.from_json('{"code":"unknown"}') }.to raise_error(Lutaml::Model::Type::InvalidValueError)
82
+ end
83
+
84
+ it "preserves qualified attribute namespaces while importing declared scalar models" do
85
+ original_class = LmlValueDeclarationFixtures::QualifiedModel
86
+ bundle = lml.export_bundle(original_class, value_declarations: registry)
87
+ rule = bundle.models.values.first.fetch("mappings").fetch("xml").fetch("rules").first
88
+ expect(rule.fetch("namespace")).to eq("mode" => "uri", "uri" => "urn:declared-values", "prefix" => "d")
89
+ imported = lml.import_bundle(bundle, type_bindings: { "#{scalar.name}@default" => scalar }).fetch("#{original_class.name}@default")
90
+ original = original_class.new(code: "a").to_xml(prefix: true)
91
+ expect(imported.from_xml(original).to_xml(prefix: true)).to eq(original)
92
+ end
93
+
94
+ it "treats facet payloads as data rather than model references" do
95
+ definition.fetch("facets")["opaque_payload"] = { "kind" => "model", "id" => "Missing@default" }
96
+ tree = lml.export_bundle(source, value_declarations: registry).to_h
97
+ expect(tree.fetch("models").keys).to eq(["#{source.name}@default"])
98
+ expect(tree.fetch("value_types").values.first.fetch("facets").fetch("opaque_payload")).to eq("kind" => "model", "id" => "Missing@default")
99
+ end
100
+
101
+ it "uses exact source class identity rather than names or inherited behavior" do
102
+ expect(registry.fetch(scalar.name)).to be_nil
103
+ subclass = Class.new(scalar)
104
+ stub_const("LmlUnregisteredCode", subclass)
105
+ expect(registry.fetch(subclass)).to be_nil
106
+ expect { described_class.new({ scalar.name => definition }) }.to raise_error(lml::RejectedError)
107
+ end
108
+
109
+ it "freezes a private data copy without freezing the caller's declarations" do
110
+ item = described_class.new({ scalar => definition })
111
+ definition.fetch("facets").fetch("enumeration") << "c"
112
+ expect(item.fetch(scalar).fetch("facets").fetch("enumeration")).to eq(%w[a b])
113
+ expect(item.fetch(scalar)).to be_frozen
114
+ expect(item.to_h.fetch("version")).to eq(1)
115
+ end
116
+
117
+ it "refuses unsupported registry versions and executable metadata" do
118
+ expect { described_class.new({ scalar => definition }, version: 2) }.to raise_error(lml::RejectedError) { |error| expect(error.reason).to eq(:unsupported_version) }
119
+ invoked = false
120
+ definition["facets"]["callback"] = -> { invoked = true }
121
+ expect { described_class.new({ scalar => definition }) }.to raise_error(lml::RejectedError) { |error| expect(error.reason).to eq(:invalid_document) }
122
+ expect(invoked).to be(false)
123
+ end
124
+
125
+ it "refuses unvalidated raw registries at the public exporter boundary" do
126
+ expect { lml.export_bundle(source, value_declarations: { scalar => definition }) }.to raise_error(ArgumentError, /ValueDeclarations/)
127
+ end
128
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "lutaml/model/schema"
5
+
6
+ RSpec.describe Lutaml::Model::Schema::ClassLoader do
7
+ let(:definition) do
8
+ Lutaml::Model::Schema::Definitions::Model.new(
9
+ class_name: "Entry",
10
+ xml_root: Lutaml::Model::Schema::Definitions::XmlRoot.new(
11
+ kind: :element, name: "entry",
12
+ ),
13
+ )
14
+ end
15
+
16
+ let(:entry) do
17
+ Lutaml::Model::Schema::CompiledOutput::Entry.new(
18
+ "Entry", definition, :model
19
+ )
20
+ end
21
+
22
+ it "loads generated classes from a nested namespace directory" do
23
+ stub_const("ClassLoaderRegression", Module.new)
24
+
25
+ output = Lutaml::Model::Schema::CompiledOutput.new(
26
+ entries: [entry],
27
+ module_namespace: "ClassLoaderRegression::Nested",
28
+ )
29
+
30
+ expect { described_class.load(output) }.not_to raise_error
31
+
32
+ expect(ClassLoaderRegression::Nested::Entry.ancestors)
33
+ .to include(Lutaml::Model::Serialize::ClassMethods)
34
+ end
35
+
36
+ it "keeps single-level namespace autoloads working" do
37
+ registry = Lutaml::Model::Schema::RegistryGenerator.generate(
38
+ [entry], module_namespace: "SingleLevel"
39
+ )
40
+
41
+ expect(registry).to include('File.join(__dir__, "singlelevel", "entry")')
42
+ end
43
+
44
+ it "keeps flat class output free of a registry namespace" do
45
+ registry = Lutaml::Model::Schema::RegistryGenerator.generate(
46
+ [entry], module_namespace: nil
47
+ )
48
+
49
+ expect(registry).to be_nil
50
+ end
51
+ end
@@ -52,6 +52,26 @@ RSpec.describe "runtime XSD class loading" do
52
52
  end
53
53
  end
54
54
 
55
+ # `use="required"` on an xs:attribute compiles to a required model
56
+ # attribute, so an instance the schema forbids fails validation.
57
+ it "carries use=\"required\" through to the generated attribute" do
58
+ Dir.mktmpdir do |dir|
59
+ Lutaml::Model::Schema.from_xml(
60
+ xsd, output_dir: File.join(dir, "required_attribute_models"),
61
+ load_classes: true
62
+ )
63
+
64
+ expect(RequiredAttributeModels::EntryType.attributes[:id].options[:required])
65
+ .to be true
66
+
67
+ missing = RequiredAttributeModels::EntryType.from_xml(
68
+ "<entry><name>Alpha</name><year>2024</year></entry>",
69
+ )
70
+ expect { missing.validate! }
71
+ .to raise_error(Lutaml::Model::ValidationError, /id/)
72
+ end
73
+ end
74
+
55
75
  # Anonymous (inline) complexTypes get CT_-prefixed internal names;
56
76
  # the generated classes must still (a) map skippable XSD built-ins
57
77
  # like xs:int to Lutaml primitives and (b) serialize the owning
@@ -396,6 +396,54 @@ RSpec.describe "Sequence" do
396
396
  end
397
397
  let(:klass) { SequenceSpec::CeramicRestricted }
398
398
 
399
+ # An optional scalar member (XSD minOccurs="0", maxOccurs="1") may be
400
+ # absent: the sequence validator skips it and continues with the next
401
+ # member instead of reporting the element that follows as out of order.
402
+ context "with an optional scalar member between required ones" do
403
+ let(:model) do
404
+ Class.new(Lutaml::Model::Serializable) do
405
+ attribute :title, :string, required: true
406
+ attribute :note, :string
407
+ attribute :meta, :string
408
+ attribute :items, :string, collection: 0..Float::INFINITY
409
+
410
+ xml do
411
+ element "Doc"
412
+ sequence do
413
+ map_element :title, to: :title
414
+ map_element :note, to: :note
415
+ map_element :meta, to: :meta
416
+ map_element :items, to: :items
417
+ end
418
+ end
419
+ end
420
+ end
421
+
422
+ it "accepts an instance that omits the optional member" do
423
+ instance = model.from_xml("<Doc><title>t</title><meta>m</meta></Doc>")
424
+ expect { instance.validate! }.not_to raise_error
425
+ end
426
+
427
+ it "accepts an instance that omits the optional member before a collection" do
428
+ instance = model.from_xml(
429
+ "<Doc><title>t</title><items>a</items><items>b</items></Doc>",
430
+ )
431
+ expect { instance.validate! }.not_to raise_error
432
+ end
433
+
434
+ it "still rejects a member that is out of order" do
435
+ instance = model.from_xml("<Doc><meta>m</meta><title>t</title></Doc>")
436
+ expect { instance.validate! }
437
+ .to raise_error(Lutaml::Model::ValidationError, /title/)
438
+ end
439
+
440
+ it "still rejects a missing required member" do
441
+ instance = model.from_xml("<Doc><note>n</note></Doc>")
442
+ expect { instance.validate! }
443
+ .to raise_error(Lutaml::Model::ValidationError, /title/)
444
+ end
445
+ end
446
+
399
447
  it "does not raise for correct order" do
400
448
  expect do
401
449
  sequence.validate_content!(
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+
5
+ # cdata: true must serialize as a CDATA section, not escaped text, on
6
+ # every engine lane. The equivalence-based cdata specs compare XML
7
+ # semantically (CDATA and escaped text are equivalent under that
8
+ # comparison), which is how the leptris plan lanes came to emit plain
9
+ # text nodes for cdata rules.
10
+ module CdataEmissionSpec
11
+ class Content < Lutaml::Model::Serializable
12
+ attribute :id, :string
13
+ attribute :label, :string
14
+
15
+ xml do
16
+ element "item"
17
+ map_attribute "id", to: :id
18
+ map_content to: :label, cdata: true
19
+ end
20
+ end
21
+
22
+ class Element < Lutaml::Model::Serializable
23
+ attribute :label, :string
24
+
25
+ xml do
26
+ element "labeled"
27
+ map_element "label", to: :label, cdata: true
28
+ end
29
+ end
30
+
31
+ class Plain < Lutaml::Model::Serializable
32
+ attribute :label, :string
33
+
34
+ xml do
35
+ element "plain"
36
+ map_element "label", to: :label
37
+ end
38
+ end
39
+ end
40
+
41
+ RSpec.describe "CDATA emission" do
42
+ %i[leptris nokogiri].each do |engine|
43
+ context "on the #{engine} lane" do
44
+ around do |example|
45
+ previous = Lutaml::Model::Config.xml_adapter_type
46
+ Lutaml::Model::Config.xml_adapter_type = engine
47
+ example.run
48
+ ensure
49
+ Lutaml::Model::Config.xml_adapter_type = previous
50
+ end
51
+
52
+ it "emits a CDATA section for a content rule with cdata: true" do
53
+ expect(CdataEmissionSpec::Content.new(id: "i", label: "<x>").to_xml)
54
+ .to include("<item id=\"i\"><![CDATA[<x>]]></item>")
55
+ end
56
+
57
+ it "emits a CDATA section for an element rule with cdata: true" do
58
+ expect(CdataEmissionSpec::Element.new(label: "<x>").to_xml)
59
+ .to include("<label><![CDATA[<x>]]></label>")
60
+ end
61
+
62
+ it "keeps escaped text for a rule without cdata" do
63
+ expect(CdataEmissionSpec::Plain.new(label: "<x>").to_xml)
64
+ .to include("<label>&lt;x&gt;</label>")
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+
5
+ # Named fixtures for LML any_attribute (map_all_attributes) specs.
6
+ module LmlAnyAttributeFixtures
7
+ class Tag < Lutaml::Model::Serializable
8
+ attribute :id, :string
9
+ attribute :other_attributes, :hash
10
+
11
+ xml do
12
+ element "tag"
13
+ map_attribute "id", to: :id
14
+ map_all_attributes to: :other_attributes
15
+ end
16
+ end
17
+
18
+ class Filtered < Lutaml::Model::Serializable
19
+ attribute :other_attributes, :hash
20
+
21
+ xml do
22
+ element "filtered"
23
+ map_all_attributes to: :other_attributes, matching: /\Adata-/
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,292 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+ require "json"
5
+ require "yaml"
6
+ require "digest"
7
+ require "rexml/document"
8
+
9
+ # Independent Ruby oracle and versioned replay protocol for the core package.
10
+ module LmlConformance
11
+ GENERATION = "core-v2"
12
+ SOURCE_REVISION = "8a8ef040963b7965388b01b58af33af2b0995f91"
13
+ XML_PROFILE = "expanded-names-text-v1"
14
+ NATIVE_PROFILE = "ruby-native-v1"
15
+ PORTABLE_PROFILE = "portable-exact-json-v1"
16
+ MODEL_ID = "LmlConformance::Record@default"
17
+
18
+ class Record < Lutaml::Model::Serializable
19
+ attribute :label, :string
20
+ attribute :count, :integer
21
+ attribute :enabled, :boolean
22
+
23
+ xml do
24
+ root "record"
25
+ map_attribute "enabled", to: :enabled
26
+ map_element "label", to: :label
27
+ map_element "count", to: :count
28
+ end
29
+
30
+ json do
31
+ map "label", to: :label
32
+ map "count", to: :count
33
+ map "enabled", to: :enabled
34
+ end
35
+ end
36
+
37
+ module_function
38
+
39
+ def canonical(value)
40
+ case value
41
+ when Hash then value.keys.sort.to_h { |key| [key, canonical(value.fetch(key))] }
42
+ when Array then value.map { |item| canonical(item) }
43
+ else value
44
+ end
45
+ end
46
+
47
+ def json(value)
48
+ JSON.generate(canonical(value))
49
+ end
50
+
51
+ def digest(bytes)
52
+ "sha256:#{Digest::SHA256.hexdigest(bytes)}"
53
+ end
54
+
55
+ # Contract-authored v2 schema; does not depend on the parallel exporter work.
56
+ def schema
57
+ fields = { "label" => "string", "count" => "integer", "enabled" => "boolean" }
58
+ {
59
+ "lml_bundle" => 1, "roots" => [MODEL_ID], "value_types" => {},
60
+ "capabilities" => %w[json xml],
61
+ "provenance" => { "source_revision" => SOURCE_REVISION },
62
+ "models" => { MODEL_ID => {
63
+ "lml" => 2, "model" => "LmlConformance::Record", "register" => "default",
64
+ "attributes" => fields.map do |name, type|
65
+ { "name" => name, "type" => { "kind" => "builtin", "name" => type },
66
+ "required" => false, "collection" => false,
67
+ "default" => { "present" => false }, "initialize_empty" => false }
68
+ end,
69
+ "mappings" => {
70
+ "json" => { "rules" => fields.keys.map { |name| { "key" => [name], "to" => name } } },
71
+ "xml" => { "root" => { "element" => "record" },
72
+ "namespace" => { "mode" => "inherit" },
73
+ "rules" => %w[enabled label count].map do |name|
74
+ { "kind" => name == "enabled" ? "attribute" : "element",
75
+ "name" => [name], "to" => name,
76
+ "namespace" => { "mode" => "inherit" } }
77
+ end },
78
+ }
79
+ } }
80
+ }
81
+ end
82
+
83
+ def schema_checksum
84
+ digest(json(schema.except("provenance")))
85
+ end
86
+
87
+ def normalized(record)
88
+ { "label" => record.label, "count" => record.count.to_s, "enabled" => record.enabled }
89
+ end
90
+
91
+ def case_inputs
92
+ [
93
+ ["core-json", "json", "data", '{"label":"café & tea","count":42,"enabled":false}'],
94
+ ["core-xml-tree", "xml", "xml_tree", '<record enabled="false"><label>café &amp; tea</label><count>42</count></record>'],
95
+ ["core-xml-bytes", "xml", "bytes", '<record enabled="true"><label>plain</label><count>7</count></record>'],
96
+ ["core-json-invalid", "json", "data", "{"],
97
+ ["core-json-portable-exact", "json", "data", '{"label":"beyond binary64","count":"9007199254740993","enabled":false}', PORTABLE_PROFILE],
98
+ ]
99
+ end
100
+
101
+ def execute(entry)
102
+ format = entry.fetch("format")
103
+ raise ArgumentError, "unsupported_format" unless %w[json xml].include?(format)
104
+
105
+ profile = entry.fetch("wire_profile")
106
+ raise ArgumentError, "unknown wire profile" unless [NATIVE_PROFILE, PORTABLE_PROFILE].include?(profile)
107
+ raise ArgumentError, "portable profile requires JSON" if profile == PORTABLE_PROFILE && format != "json"
108
+
109
+ input = entry.fetch("input")
110
+ if profile == PORTABLE_PROFILE
111
+ # This opt-in boundary is for the three-field Record oracle only. Native
112
+ # Ruby mappings stay unchanged; exact JSON integers never pass via Float.
113
+ parsed = JSON.parse(input)
114
+ count = parsed.fetch("count")
115
+ unless count.is_a?(String) && count.match?(/\A-?(?:0|[1-9][0-9]*)\z/)
116
+ raise ArgumentError, "portable integer requires decimal string"
117
+ end
118
+
119
+ # The native String cast accepts floating/exponential forms via Float.
120
+ # Supply an already exact Ruby Integer at this opt-in wire boundary.
121
+ parsed["count"] = Integer(count, 10)
122
+ input = JSON.generate(parsed)
123
+ end
124
+
125
+ Lutaml::Model::Config.with_adapter(xml: :nokogiri) do
126
+ record = Record.public_send("from_#{format}", input)
127
+ data = normalized(record)
128
+ output = profile == PORTABLE_PROFILE ? JSON.generate(data) : record.public_send("to_#{format}")
129
+ { "data" => data, "output" => output }
130
+ end
131
+ rescue JSON::ParserError, Lutaml::Model::InvalidFormatError
132
+ { "error" => { "reason" => "invalid_document", "model_id" => MODEL_ID,
133
+ "format" => format, "location" => "/input" } }
134
+ end
135
+
136
+ def oracle_cases
137
+ case_inputs.map do |id, format, comparison, input, profile|
138
+ entry = { "id" => id, "model_id" => MODEL_ID, "lml_checksum" => schema_checksum,
139
+ "format" => format, "input" => input, "comparison" => comparison,
140
+ "wire_profile" => profile || NATIVE_PROFILE, "data_profile" => "exact-values-decimal-v1" }
141
+ result = execute(entry)
142
+ entry.merge("expected_data" => result["data"], "expected_output" => result["output"],
143
+ "expected_error" => result["error"])
144
+ end
145
+ end
146
+
147
+ def profiles
148
+ [NATIVE_PROFILE, PORTABLE_PROFILE].to_h do |profile|
149
+ ids = case_inputs.filter_map { |entry| entry.first if (entry[4] || NATIVE_PROFILE) == profile }
150
+ [profile, { "required_case_ids" => ids }]
151
+ end
152
+ end
153
+
154
+ def target_profiles
155
+ { "ruby" => [NATIVE_PROFILE, PORTABLE_PROFILE], "ts" => [PORTABLE_PROFILE], "rust" => [PORTABLE_PROFILE] }
156
+ end
157
+
158
+ # Consumers report all required profile/case coverage, including omissions.
159
+ # Selecting another profile never silently certifies a target's required set.
160
+ def coverage(index, target:, executed_ids:)
161
+ required_profiles = index.fetch("target_profiles").fetch(target)
162
+ required_ids = required_profiles.flat_map { |profile| index.fetch("profiles").fetch(profile).fetch("required_case_ids") }
163
+ errors = (required_ids - executed_ids).map { |id| { "id" => id, "error" => "required case not executed" } }
164
+ { "required_profiles" => required_profiles, "required_ids" => required_ids, "errors" => errors }
165
+ end
166
+
167
+ def files
168
+ index = { "corpus" => 1, "generation" => GENERATION, "source_revision" => SOURCE_REVISION,
169
+ "xml_canon_profile" => XML_PROFILE, "profiles" => profiles,
170
+ "target_profiles" => target_profiles, "cases" => oracle_cases }
171
+ payload = { "index.json" => json(index), "schema.json" => json(schema),
172
+ "schema.yaml" => YAML.safe_dump(canonical(schema)) }
173
+ manifest = {
174
+ "manifest" => 1, "lml_checksum" => schema_checksum, "schema_version" => 2,
175
+ "generator_version" => "ruby-core-oracle-v2", "target" => "ruby",
176
+ "capabilities" => %w[json xml],
177
+ "corpora" => [{ "generation" => GENERATION, "sha256" => digest(payload.fetch("index.json")) }],
178
+ "files" => payload.sort.map { |path, bytes| { "path" => path, "sha256" => digest(bytes) } },
179
+ "dependencies" => [{ "name" => "lutaml-model", "revision" => SOURCE_REVISION,
180
+ # Pin repository source text independent of Windows CRLF checkout conversion.
181
+ "sha256" => digest(File.binread(File.expand_path("../../lutaml-model.gemspec", __dir__)).gsub("\r\n", "\n")) }]
182
+ }
183
+ payload.merge("manifest.json" => json(manifest))
184
+ end
185
+
186
+ # Expanded element/attribute names, sorted attributes, significant text and
187
+ # child order; namespace declarations and prefix spelling are not tree data.
188
+ # CDATA and text have the same tree meaning; bytes preserve lexical differences.
189
+ def xml_tree(bytes)
190
+ raise ArgumentError, "DTD and processing instructions are forbidden" if bytes.match?(/<!DOCTYPE|<!ENTITY|<\?(?!xml\s)/i)
191
+
192
+ root = REXML::Document.new(bytes).root
193
+ raise ArgumentError, "missing XML root" unless root
194
+
195
+ xml_element(root)
196
+ end
197
+
198
+ def xml_element(element)
199
+ attributes = element.attributes.each_attribute.filter_map do |attribute|
200
+ next if attribute.expanded_name == "xmlns" || attribute.prefix == "xmlns"
201
+
202
+ [[attribute.namespace, attribute.name], attribute.value]
203
+ end.sort
204
+ children = element.children.each_with_object([]) do |child, result|
205
+ if child.is_a?(REXML::Element)
206
+ result << xml_element(child)
207
+ elsif child.is_a?(REXML::Text)
208
+ if result.last.is_a?(String)
209
+ result[-1] += child.value
210
+ else
211
+ result << child.value
212
+ end
213
+ else
214
+ raise ArgumentError, "unsupported XML node"
215
+ end
216
+ end
217
+ [[element.namespace, element.name], attributes, children]
218
+ end
219
+
220
+ def compare(entry, actual)
221
+ return actual["error"] == entry["expected_error"] ? nil : "error mismatch" if entry["expected_error"]
222
+ return "unexpected error" if actual["error"]
223
+ return "typed data mismatch" unless actual["data"] == entry.fetch("expected_data")
224
+
225
+ expected = entry.fetch("expected_output")
226
+ output = actual.fetch("output")
227
+ equal = case entry.fetch("comparison")
228
+ when "data" then JSON.parse(output) == JSON.parse(expected)
229
+ when "xml_tree" then xml_tree(output) == xml_tree(expected)
230
+ when "bytes" then output.b == expected.b
231
+ else return "unknown comparison"
232
+ end
233
+ equal ? nil : "output mismatch"
234
+ end
235
+
236
+ def replay(index)
237
+ raise ArgumentError, "invalid index" unless index.is_a?(Hash)
238
+
239
+ expected = oracle_cases.to_h { |entry| [entry.fetch("id"), entry] }
240
+ entries = index.fetch("cases")
241
+ raise ArgumentError, "invalid cases" unless entries.is_a?(Array)
242
+
243
+ executed = []
244
+ errors = []
245
+ entries.each do |entry|
246
+ unless entry.is_a?(Hash) && entry["id"].is_a?(String)
247
+ errors << { "id" => "package/cases", "error" => "invalid case" }
248
+ next
249
+ end
250
+ id = entry.fetch("id")
251
+ if !expected.key?(id)
252
+ errors << { "id" => id, "error" => "unknown case" }
253
+ elsif executed.include?(id)
254
+ errors << { "id" => id, "error" => "duplicate case" }
255
+ else
256
+ executed << id
257
+ error = entry == expected.fetch(id) ? compare(entry, execute(entry)) : "changed case"
258
+ errors << { "id" => id, "error" => error } if error
259
+ end
260
+ end
261
+ (expected.keys - executed).each { |id| errors << { "id" => id, "error" => "missing case" } }
262
+ profile_coverage = coverage(index, target: "ruby", executed_ids: executed)
263
+ { "expected_ids" => expected.keys, "executed_ids" => executed,
264
+ "expected_count" => expected.size, "executed_count" => executed.size,
265
+ "required_profiles" => profile_coverage.fetch("required_profiles"),
266
+ "errors" => errors + profile_coverage.fetch("errors") }
267
+ end
268
+
269
+ def check(directory)
270
+ report = replay(JSON.parse(File.read(File.join(directory, "index.json"))))
271
+ files.each do |path, bytes|
272
+ full_path = File.join(directory, path)
273
+ next if File.file?(full_path) && File.binread(full_path) == bytes.b
274
+
275
+ report["errors"] << { "id" => "package/#{path}", "error" => "missing or changed file" }
276
+ end
277
+ (Dir.children(directory) - files.keys).sort.each do |path|
278
+ report["errors"] << { "id" => "package/#{path}", "error" => "unknown file" }
279
+ end
280
+ json_schema = JSON.parse(File.read(File.join(directory, "schema.json")))
281
+ yaml_schema = YAML.safe_load_file(File.join(directory, "schema.yaml"), aliases: false)
282
+ unless json_schema == yaml_schema
283
+ report["errors"] << { "id" => "package/schema.yaml", "error" => "schema equivalence mismatch" }
284
+ end
285
+ report
286
+ rescue Errno::ENOENT, JSON::ParserError, Psych::Exception, KeyError, TypeError, ArgumentError => e
287
+ { "expected_ids" => case_inputs.map(&:first), "executed_ids" => [],
288
+ "expected_count" => case_inputs.size, "executed_count" => 0,
289
+ "errors" => [{ "id" => "package", "error" => e.class.name }] +
290
+ case_inputs.map { |entry| { "id" => entry.first, "error" => "missing case" } } }
291
+ end
292
+ end