From a894209373069a8269c87f2d65c2e5cfdb2933bc Mon Sep 17 00:00:00 2001 From: Will McLemore Date: Thu, 26 Nov 2026 11:46:53 -0600 Subject: [PATCH] fix(spec): align privileged-event schema, fix fixtures/RFC drift, and tighten validators --- conformance/fixtures/usd-reserve.yaml | 1 + conformance/fixtures/usd-standard.yaml | 1 + conformance/fixtures/usd-tiered.yaml | 1 + conformance/scenarios/README.md | 10 +- rfcs/0001-timed-online-proxy-bidding.md | 9 + rfcs/0004-flexible-live-scheduling.md | 7 +- .../flexible-live-scheduling-scenarios.md | 7 +- .../minute-batch-examples.json | 2 +- ruby/engine/test/schema_assertions_test.rb | 113 +++++++- ruby/engine/test/specification_guard_test.rb | 66 ++++- .../engine/test/support/conformance_runner.rb | 32 ++- ruby/engine/test/support/schema_assertions.rb | 192 +++++++++---- scripts/validate_documents.rb | 241 ++++++++++++++-- specification/asyncapi.yaml | 5 +- specification/common/integer.schema.json | 2 +- specification/common/money.schema.json | 2 +- specification/common/timestamp.schema.json | 2 +- specification/concepts.md | 12 +- specification/contract.md | 18 +- .../events/privileged-event.schema.json | 268 ++++++++++++------ specification/events/public-event.schema.json | 2 +- specification/openapi.yaml | 46 ++- 22 files changed, 843 insertions(+), 196 deletions(-) diff --git a/conformance/fixtures/usd-reserve.yaml b/conformance/fixtures/usd-reserve.yaml index f5e5851..a62ff08 100644 --- a/conformance/fixtures/usd-reserve.yaml +++ b/conformance/fixtures/usd-reserve.yaml @@ -8,3 +8,4 @@ increments: amount_minor_units: 2500 opens_at: "2026-09-01T12:00:00Z" closes_at: "2026-09-01T13:00:00Z" +extension: null diff --git a/conformance/fixtures/usd-standard.yaml b/conformance/fixtures/usd-standard.yaml index d4a27d6..d8416f4 100644 --- a/conformance/fixtures/usd-standard.yaml +++ b/conformance/fixtures/usd-standard.yaml @@ -6,3 +6,4 @@ increments: amount_minor_units: 1000 opens_at: "2026-09-01T12:00:00Z" closes_at: "2026-09-01T13:00:00Z" +extension: null diff --git a/conformance/fixtures/usd-tiered.yaml b/conformance/fixtures/usd-tiered.yaml index 6690d98..336521f 100644 --- a/conformance/fixtures/usd-tiered.yaml +++ b/conformance/fixtures/usd-tiered.yaml @@ -8,3 +8,4 @@ increments: amount_minor_units: 2500 opens_at: "2026-09-01T12:00:00Z" closes_at: "2026-09-01T13:00:00Z" +extension: null diff --git a/conformance/scenarios/README.md b/conformance/scenarios/README.md index dff0149..cd1f79b 100644 --- a/conformance/scenarios/README.md +++ b/conformance/scenarios/README.md @@ -1,3 +1,11 @@ # Scenarios -The `timed-proxy/` directory contains the RFC 0001 conformance suite. +The `timed-proxy/` directory contains the executable RFC 0001 / RFC 0005 timed +online proxy bidding conformance suite. + +Sibling suites live alongside `scenarios/`: + +- [`../initial-scheduling/`](../initial-scheduling/) — RFC 0002 initial closing + schedule planning vectors; +- [`../shared-closing-clock/`](../shared-closing-clock/) — RFC 0003 / RFC 0004 + shared closing clock vectors. diff --git a/rfcs/0001-timed-online-proxy-bidding.md b/rfcs/0001-timed-online-proxy-bidding.md index c4fa026..d5ae679 100644 --- a/rfcs/0001-timed-online-proxy-bidding.md +++ b/rfcs/0001-timed-online-proxy-bidding.md @@ -305,6 +305,15 @@ rejected. ## Amendments +- 2026-11-24 (PR #59): added opt-in `extension.extend_on_void` (default `false`) + to timed proxy extension configuration. When `true`, an operator `void_bid` + that changes the leader or standing amount inside the trigger window extends + closing time by the same rule as a qualifying bid, records the extended + `closes_at` on `bid_voided`, and emits public `closing_time_changed`. Default + behavior (`false`) is unchanged, and RFC 0004 linked closing sets keep + `extend_on_void` disabled. Covered by conformance scenario `044` and fixture + `usd-soft-close-extend-on-void`. + - 2026-11-10 (second ruling): maintainer decision on the result of a void (Will McLemore). He was shown that in rare histories, voiding a bidder's last bid gives a different winner or price under rule A than under the previous diff --git a/rfcs/0004-flexible-live-scheduling.md b/rfcs/0004-flexible-live-scheduling.md index 99ca543..cf92ccd 100644 --- a/rfcs/0004-flexible-live-scheduling.md +++ b/rfcs/0004-flexible-live-scheduling.md @@ -258,8 +258,11 @@ or reductions of their maximum, do not reset an individual or group closing clock, even when the public projection changes (for example, a raise that crosses the reserve and moves the price to it). This departs from RFC 0001, where any change to the public standing amount qualifies, and applies only -under this capability. A reduction cannot go below the executed floor, so in -practice it never changes the public result. +under this capability. A reduction cannot go below the executed floor (so it +never lowers the standing amount), though under RFC 0001 a leader reducing onto +a tied executable rung takes later priority and can change the leader and +standing public state; when a reduction changes no public result, it does not +extend closing under either RFC 0001 or this capability. Every other accepted bidding command follows RFC 0001's qualifying rule. In particular, any accepted command that changes the leader is a qualifying bid, diff --git a/rfcs/proposals/flexible-live-scheduling-scenarios.md b/rfcs/proposals/flexible-live-scheduling-scenarios.md index 6435347..e393f1d 100644 --- a/rfcs/proposals/flexible-live-scheduling-scenarios.md +++ b/rfcs/proposals/flexible-live-scheduling-scenarios.md @@ -254,8 +254,11 @@ remain unchanged. Another qualifying group bid at 15:03 moves the group to **Then:** all closing times remain unchanged, including when a raise crosses the reserve and moves the public price to it. Normal bidding validity checks still -apply; a reduction cannot go below the executed floor, so it never changes the -public result. This exemption covers only the current leader's own adjustments +apply; a reduction cannot go below the executed floor (so it cannot lower the +standing amount), though under RFC 0001 a leader reducing onto a tied +executable rung with later priority can change the leader and standing public +state (in this non-tied example, leader and public state remain unchanged). This +exemption covers only the current leader's own adjustments (see FLS-21). Current engine behavior and the existing private-only example alone do not certify it. diff --git a/rfcs/proposals/flexible-live-scheduling/minute-batch-examples.json b/rfcs/proposals/flexible-live-scheduling/minute-batch-examples.json index dc9f3bb..b0cadc0 100644 --- a/rfcs/proposals/flexible-live-scheduling/minute-batch-examples.json +++ b/rfcs/proposals/flexible-live-scheduling/minute-batch-examples.json @@ -95,7 +95,7 @@ "bidder_role": "current_leader", "leader_changed": false, "public_projection_changed": false, - "note": "A reduction cannot go below the executed floor, so it cannot change the public result.", + "note": "A reduction cannot go below the executed floor, though under RFC 0001 a leader reducing onto a tied executable rung with later priority can change the leader and standing public state; in this non-tied case both remain unchanged.", "expected_group_close": "15:02" } ] diff --git a/ruby/engine/test/schema_assertions_test.rb b/ruby/engine/test/schema_assertions_test.rb index c6637c8..8df3096 100644 --- a/ruby/engine/test/schema_assertions_test.rb +++ b/ruby/engine/test/schema_assertions_test.rb @@ -4,7 +4,8 @@ require_relative "support/schema_assertions" # Guards the dependency-free schema checker itself: a conforming public event -# envelope passes, privileged leaks and missing envelope fields fail, and a +# envelope passes, privileged leaks and missing envelope fields fail, +# unevaluatedProperties/if-then-else/not/anyOf enforce 2020-12 semantics, and a # file-relative `$ref` that cannot be resolved fails with a clear message. class SchemaAssertionsTest < Minitest::Test include SchemaAssertions @@ -34,6 +35,116 @@ def test_missing_envelope_field_fails assert_raises(Minitest::Assertion) { assert_matches_schema(@schema, ENVELOPE.except("event_id")) } end + def test_unevaluated_properties_catches_extra_top_level_key_on_events_and_commands + error = assert_raises(Minitest::Assertion) do + assert_matches_schema(@schema, ENVELOPE.merge("unexpected_top_level" => true)) + end + assert_match(/unevaluated key unexpected_top_level/, error.message) + + place_bid_schema = load_schema("specification/commands/place-bid.schema.json") + valid_command = { + "command_id" => "command-1", "type" => "place_bid", + "auction_id" => "auction-1", "bidding_unit_id" => "unit-1", + "expected_version" => 0, "effective_at" => "2026-09-01T12:10:00Z", + "bid_id" => "bid-1", "bidder_id" => "bidder-a", "maximum_minor_units" => 10_000 + } + assert_matches_schema(place_bid_schema, valid_command) + assert_raises(Minitest::Assertion) do + assert_matches_schema(place_bid_schema, valid_command.merge("operator_id" => "op-1")) + end + + privileged_schema = load_schema("specification/events/privileged-event.schema.json") + valid_privileged = { + "event_id" => "command-1-0", "type" => "executed_amount_changed", "visibility" => "privileged", + "auction_id" => "auction-1", "bidding_unit_id" => "unit-1", "aggregate_version" => 2, + "event_index" => 1, "command_id" => "command-2", + "effective_at" => "2026-09-01T12:12:00Z", "recorded_at" => "2026-09-01T12:12:00Z", + "data" => {"bidder_id" => "bidder-a", "old_minor_units" => 30_000, "new_minor_units" => 10_000} + } + assert_matches_schema(privileged_schema, valid_privileged) + assert_raises(Minitest::Assertion) do + assert_matches_schema(privileged_schema, valid_privileged.merge("stray" => 1)) + end + end + + def test_unevaluated_properties_tracks_all_of_one_of_any_of_if_then_else_and_ref + schema = { + "allOf" => [ + {"$ref" => "#/$defs/base"}, + { + "if" => {"required" => ["kind"], "properties" => {"kind" => {"const" => "a"}}}, + "then" => {"properties" => {"a_only" => {"type" => "integer"}}}, + "else" => {"properties" => {"b_only" => {"type" => "string"}}} + } + ], + "anyOf" => [ + {"properties" => {"tag" => {"const" => "x"}}}, + {"properties" => {"extra_tag" => {"type" => "boolean"}}} + ], + "unevaluatedProperties" => false, + "$defs" => { + "base" => {"type" => "object", "required" => ["kind"], "properties" => {"kind" => {"type" => "string"}}} + } + } + + assert_matches_schema(schema, {"kind" => "a", "a_only" => 1, "tag" => "x"}) + assert_matches_schema(schema, {"kind" => "b", "b_only" => "ok", "extra_tag" => true}) + assert_raises(Minitest::Assertion) do + assert_matches_schema(schema, {"kind" => "a", "b_only" => "wrong-branch", "tag" => "x"}) + end + assert_raises(Minitest::Assertion) do + assert_matches_schema(schema, {"kind" => "a", "a_only" => 1, "tag" => "x", "stray" => 99}) + end + end + + def test_if_then_else_and_not_enforce_rejection_schema + rejection_schema = load_schema("specification/rejections/rejection.schema.json") + + assert_matches_schema( + rejection_schema, + {"command_id" => "cmd-1", "status" => "rejected", "reason" => "bidding_closed"} + ) + assert_matches_schema( + rejection_schema, + { + "command_id" => "cmd-2", + "status" => "rejected", + "reason" => "maximum_below_executed_amount", + "executed_floor_minor_units" => 10_000 + } + ) + + assert_raises(Minitest::Assertion) do + assert_matches_schema( + rejection_schema, + {"command_id" => "cmd-3", "status" => "rejected", "reason" => "maximum_below_executed_amount"} + ) + end + assert_raises(Minitest::Assertion) do + assert_matches_schema( + rejection_schema, + { + "command_id" => "cmd-4", + "status" => "rejected", + "reason" => "bidding_closed", + "executed_floor_minor_units" => 10_000 + } + ) + end + end + + def test_not_rejects_matching_documents_and_does_not_mark_properties_evaluated + schema = { + "type" => "object", + "properties" => {"allowed" => {"type" => "string"}}, + "not" => {"required" => ["forbidden"], "properties" => {"forbidden" => {"type" => "string"}}}, + "unevaluatedProperties" => false + } + assert_matches_schema(schema, {"allowed" => "yes"}) + assert_raises(Minitest::Assertion) { assert_matches_schema(schema, {"allowed" => "yes", "forbidden" => "no"}) } + assert_raises(Minitest::Assertion) { assert_matches_schema(schema, {"allowed" => "yes", "forbidden" => 123}) } + end + def test_file_ref_with_pointer_fragment_resolves assert_matches_schema({"$ref" => "./base.schema.json#/properties/visibility"}, "public", root: @schema) assert_raises(Minitest::Assertion) do diff --git a/ruby/engine/test/specification_guard_test.rb b/ruby/engine/test/specification_guard_test.rb index fdc53b5..addd4df 100644 --- a/ruby/engine/test/specification_guard_test.rb +++ b/ruby/engine/test/specification_guard_test.rb @@ -5,10 +5,12 @@ require "json" require "open3" require "tmpdir" +require "yaml" # scripts/validate_documents.rb is the contract's guard against unbounded -# integers. These tests run it against a scratch copy of the repository so a -# regression in the guard itself fails the engine suite, not only CI. +# integers, version drift, malformed fixtures/scenarios, and privileged leaks. +# These tests run it against a scratch copy of the repository so a regression +# in the guard itself fails the engine suite, not only CI. class SpecificationGuardTest < Minitest::Test REPO_ROOT = File.expand_path("../../..", __dir__) VALIDATOR = File.join(REPO_ROOT, "scripts", "validate_documents.rb") @@ -59,6 +61,50 @@ def test_shared_integer_definition_drifting_from_the_bound_fails assert_match(%r{common/integer.schema.json: \$defs/positiveInteger must use the shared maximum}, stderr) end + def test_fixture_missing_extension_key_fails + stderr = run_validator_with_file_edit("conformance/fixtures/usd-standard.yaml") do |content| + fixture = YAML.safe_load(content, aliases: false) + fixture.delete("extension") + YAML.dump(fixture) + end + + assert_match(%r{conformance/fixtures/usd-standard.yaml: missing required keys: extension}, stderr) + end + + def test_scenario_unexpected_top_level_key_fails + stderr = run_validator_with_file_edit("conformance/scenarios/timed-proxy/001-first-maximum-opens-at-opening.yaml") do |content| + "extra_key: true\n#{content}" + end + + assert_match(/unexpected top-level keys: extra_key/, stderr) + end + + def test_version_drift_fails + stderr = run_validator_with_file_edit("specification/VERSION") { "9.9.9-draft\n" } + + assert_match(/specification\/openapi.yaml: info\.version .* does not match specification\/VERSION/, stderr) + assert_match(/specification\/asyncapi.yaml: info\.version .* does not match specification\/VERSION/, stderr) + assert_match(/ruby\/engine\/lib\/rbbb\/version\.rb: SPECIFICATION_VERSION .* does not match specification\/VERSION/, stderr) + end + + def test_expanded_public_leak_denylist_catches_privileged_keys_in_public_events + stderr = run_validator_with_file_edit("conformance/scenarios/timed-proxy/001-first-maximum-opens-at-opening.yaml") do |content| + scenario = YAML.safe_load(content, aliases: false) + scenario["expected"]["public_events"][0]["bidder_notice"] = nil + YAML.dump(scenario) + end + + assert_match(/public_events\[0\] contains privileged keys: bidder_notice/, stderr) + end + + def test_invalid_proposal_schema_ref_fails + stderr = run_validator_with_mutation("rfcs/proposals/flexible-live-scheduling/submission.schema.json") do |schema| + schema["properties"]["command_id"] = {"$ref" => "contract.schema.json#/$defs/missing_def"} + end + + assert_match(%r{rfcs/proposals/flexible-live-scheduling/submission\.schema\.json: invalid \$ref}, stderr) + end + private def run_validator(root = REPO_ROOT) @@ -66,14 +112,24 @@ def run_validator(root = REPO_ROOT) end def run_validator_with_mutation(relative_path) + run_validator_with_file_edit(relative_path) do |content| + schema = JSON.parse(content) + yield schema + JSON.pretty_generate(schema) + end + end + + def run_validator_with_file_edit(relative_path) Dir.mktmpdir("rbbb-guard") do |dir| %w[scripts specification conformance rfcs].each do |entry| FileUtils.cp_r(File.join(REPO_ROOT, entry), dir) end + version_target = File.join(dir, "ruby/engine/lib/rbbb/version.rb") + FileUtils.mkdir_p(File.dirname(version_target)) + FileUtils.cp(File.join(REPO_ROOT, "ruby/engine/lib/rbbb/version.rb"), version_target) + target = File.join(dir, relative_path) - schema = JSON.parse(File.read(target)) - yield schema - File.write(target, JSON.pretty_generate(schema)) + File.write(target, yield(File.read(target))) _stdout, stderr, status = run_validator(dir) refute status.success?, "expected the validator to fail after mutating #{relative_path}" diff --git a/ruby/engine/test/support/conformance_runner.rb b/ruby/engine/test/support/conformance_runner.rb index 61996c1..22fed03 100644 --- a/ruby/engine/test/support/conformance_runner.rb +++ b/ruby/engine/test/support/conformance_runner.rb @@ -9,6 +9,8 @@ class ConformanceRunner AGGREGATE_SCHEMA = "specification/state/aggregate.schema.json" PUBLIC_STATE_SCHEMA = "specification/state/bidding-unit.schema.json" PUBLIC_EVENT_SCHEMA = "specification/events/public-event.schema.json" + PRIVILEGED_EVENT_SCHEMA = "specification/events/privileged-event.schema.json" + REJECTION_SCHEMA = "specification/rejections/rejection.schema.json" def initialize(test_case) @test_case = test_case @@ -30,6 +32,7 @@ def run(path) public_events = [] public_envelopes = [] privileged_events = [] + privileged_envelopes = [] rejections = [] scenario.fetch("commands").each do |command| @@ -37,7 +40,8 @@ def run(path) if decision.accepted? public_events.concat(decision.events.select(&:public?).map(&:to_h)) privileged_events.concat(decision.events.select(&:privileged?).map(&:to_h)) - public_envelopes.concat(public_event_envelopes(identity, command, decision.events)) + public_envelopes.concat(event_envelopes(identity, command, decision.events, visibility: :public)) + privileged_envelopes.concat(event_envelopes(identity, command, decision.events, visibility: :privileged)) state = engine.apply(state, decision.events) else rejections << decision.rejection @@ -62,6 +66,12 @@ def run(path) public_envelopes.each_with_index do |envelope, index| assert_schema(PUBLIC_EVENT_SCHEMA, envelope, "public event[#{index}]") end + privileged_envelopes.each_with_index do |envelope, index| + assert_schema(PRIVILEGED_EVENT_SCHEMA, envelope, "privileged event[#{index}]") + end + rejections.each_with_index do |rejection, index| + assert_schema(REJECTION_SCHEMA, rejection, "rejection[#{index}]") + end end private @@ -72,28 +82,30 @@ def load_yaml(path) YAML.safe_load_file(path, aliases: false) end - # Wraps each public event in the transport envelope described by - # specification/events/base.schema.json. The engine emits event data with - # the command_id and aggregate_version inline; the host lifts those into - # the envelope and supplies identity, ordering, and recording fields. - def public_event_envelopes(identity, command, events) + # Wraps each engine event of the given visibility in the transport envelope + # described by specification/events/base.schema.json. The engine emits + # command_id, aggregate_version, and (on transitions) effective_at inline; + # the host lifts those into the envelope and supplies identity, ordering, and + # recording fields. + def event_envelopes(identity, command, events, visibility:) events.each_with_index.filter_map do |event, event_index| - next unless event.public? + next unless event.visibility == visibility data = event.data.dup command_id = data.delete("command_id") aggregate_version = data.delete("aggregate_version") + effective_at = data.delete("effective_at") || command.fetch("effective_at") { "event_id" => "#{command_id}-#{event_index}", "type" => event.type, - "visibility" => "public", + "visibility" => visibility.to_s, "auction_id" => identity.fetch("auction_id"), "bidding_unit_id" => identity.fetch("bidding_unit_id"), "aggregate_version" => aggregate_version, "event_index" => event_index, "command_id" => command_id, - "effective_at" => command.fetch("effective_at"), - "recorded_at" => command.fetch("effective_at"), + "effective_at" => effective_at, + "recorded_at" => effective_at, "data" => data } end diff --git a/ruby/engine/test/support/schema_assertions.rb b/ruby/engine/test/support/schema_assertions.rb index 173e5ac..9347d27 100644 --- a/ruby/engine/test/support/schema_assertions.rb +++ b/ruby/engine/test/support/schema_assertions.rb @@ -2,15 +2,19 @@ require "json" require "pathname" +require "set" # A small JSON Schema 2020-12 checker covering the subset used by the RBBB -# state and event schemas: types, enum/const, minimum/maximum, string lengths, -# pattern/date-time, properties/required/additionalProperties, array lengths -# and uniqueness, items, chained $ref into -# $defs or into sibling schema files, oneOf, and allOf with if/then. It -# keeps the engine free of runtime dependencies while letting tests assert -# that produced documents satisfy the contract. +# command, state, rejection, and event schemas: types, enum/const, +# minimum/maximum, string lengths, pattern/date-time, +# properties/patternProperties/required/additionalProperties/unevaluatedProperties, +# array lengths and uniqueness, items, chained $ref into $defs or sibling schema +# files, oneOf, anyOf, allOf, if/then/else, and not. It keeps the engine free of +# runtime dependencies while letting tests assert that produced documents satisfy +# the contract. module SchemaAssertions + class SchemaError < StandardError; end + ROOT = Pathname(__dir__).join("../../../..").expand_path TYPES = { "string" => String, "integer" => Integer, "number" => Numeric, @@ -22,7 +26,39 @@ def load_schema(relative_path) end def assert_matches_schema(schema, document, root: schema, path: "document") - schema, root = resolve_schema_ref(schema, root) + validate_schema(schema, document, root: root, path: path, seen_refs: Set.new) + rescue SchemaError => e + flunk "#{path}: #{e.message}" + end + + private + + # Validates `document` against `schema` and returns the Set of property names + # on `document` evaluated at this instance location (used by + # `unevaluatedProperties` per JSON Schema 2020-12). + def validate_schema(schema, document, root:, path:, seen_refs:) + if schema == true + return document.is_a?(Hash) ? document.keys.to_set : Set.new + elsif schema == false + flunk "#{path} is disallowed by false schema" + end + + evaluated = Set.new + + if schema.key?("$ref") + location = [schema.object_id, root.object_id] + raise SchemaError, "cyclic schema reference" if seen_refs.include?(location) + + ref_schema, ref_root = resolve_single_schema_ref(schema, root) + ref_evaluated = validate_schema( + ref_schema, + document, + root: ref_root, + path: path, + seen_refs: seen_refs | [location] + ) + evaluated.merge(ref_evaluated) + end types = Array(schema["type"]) if types.any? @@ -50,61 +86,130 @@ def assert_matches_schema(schema, document, root: schema, path: "document") assert_match(Regexp.new(pattern), document, path) end if schema["format"] == "date-time" - RBBB::Timestamp.parse(document) + begin + RBBB::Timestamp.parse(document) + rescue ArgumentError => e + flunk "#{path}: #{e.message}" + end end end - assert_object_matches(schema, document, root, path) if document.is_a?(Hash) + if document.is_a?(Hash) + evaluated.merge(validate_object_keywords(schema, document, root: root, path: path)) + end + if document.is_a?(Array) assert_operator document.length, :>=, schema["minItems"], "#{path} has too few items" if schema.key?("minItems") assert_operator document.length, :<=, schema["maxItems"], "#{path} has too many items" if schema.key?("maxItems") assert_equal document.length, document.uniq.length, "#{path} has duplicate items" if schema["uniqueItems"] if schema["items"] document.each_with_index do |item, index| - assert_matches_schema(schema["items"], item, root: root, path: "#{path}[#{index}]") + validate_schema(schema["items"], item, root: root, path: "#{path}[#{index}]", seen_refs: Set.new) end end end + + Array(schema["allOf"]).each do |clause| + evaluated.merge(validate_schema(clause, document, root: root, path: path, seen_refs: seen_refs)) + end + if schema["oneOf"] - matching = schema["oneOf"].count { |alternative| matches_schema?(alternative, document, root) } - assert_equal 1, matching, "#{path} must match exactly one oneOf alternative" + matching = schema["oneOf"].filter_map do |alternative| + ok, alt_evaluated = probe_schema(alternative, document, root: root, path: path, seen_refs: seen_refs) + alt_evaluated if ok + end + assert_equal 1, matching.length, "#{path} must match exactly one oneOf alternative" + evaluated.merge(matching.first) end - Array(schema["allOf"]).each do |clause| - if clause.key?("if") - next unless matches_schema?(clause["if"], document, root) - assert_matches_schema(clause["then"], document, root: root, path: path) if clause["then"] - else - assert_matches_schema(clause, document, root: root, path: path) + if schema["anyOf"] + matching = schema["anyOf"].filter_map do |alternative| + ok, alt_evaluated = probe_schema(alternative, document, root: root, path: path, seen_refs: seen_refs) + alt_evaluated if ok end + assert_operator matching.length, :>=, 1, "#{path} must match at least one anyOf alternative" + matching.each { |alt_evaluated| evaluated.merge(alt_evaluated) } end - rescue ArgumentError => e - flunk "#{path}: #{e.message}" - end - private + if schema.key?("if") + matched, if_evaluated = probe_schema(schema["if"], document, root: root, path: path, seen_refs: seen_refs) + if matched + evaluated.merge(if_evaluated) + if schema.key?("then") + evaluated.merge(validate_schema(schema["then"], document, root: root, path: path, seen_refs: seen_refs)) + end + elsif schema.key?("else") + evaluated.merge(validate_schema(schema["else"], document, root: root, path: path, seen_refs: seen_refs)) + end + end + + if schema.key?("not") + matched, = probe_schema(schema["not"], document, root: root, path: path, seen_refs: seen_refs) + flunk "#{path} must not match negated schema" if matched + end + + if document.is_a?(Hash) && schema.key?("unevaluatedProperties") + remaining = document.keys.reject { |key| evaluated.include?(key) } + rule = schema["unevaluatedProperties"] + if rule == false + flunk "#{path} has unevaluated key #{remaining.first}" if remaining.any? + elsif rule == true + evaluated.merge(remaining) + elsif rule.is_a?(Hash) + remaining.each do |key| + validate_schema(rule, document.fetch(key), root: root, path: "#{path}.#{key}", seen_refs: Set.new) + evaluated << key + end + end + end + + evaluated + end - def assert_object_matches(schema, document, root, path) + def validate_object_keywords(schema, document, root:, path:) + evaluated = Set.new properties = schema["properties"] || {} + pattern_properties = schema["patternProperties"] || {} + Array(schema["required"]).each do |key| assert document.key?(key), "#{path} is missing #{key}" end + document.each do |key, value| + matched_here = false if properties.key?(key) - assert_matches_schema(properties.fetch(key), value, root: root, path: "#{path}.#{key}") - elsif schema["additionalProperties"].is_a?(Hash) - assert_matches_schema(schema["additionalProperties"], value, root: root, path: "#{path}.#{key}") + validate_schema(properties.fetch(key), value, root: root, path: "#{path}.#{key}", seen_refs: Set.new) + evaluated << key + matched_here = true + end + + pattern_properties.each do |pattern, subschema| + next unless Regexp.new(pattern.sub(/\A\^/) { "\\A" }).match?(key) + + validate_schema(subschema, value, root: root, path: "#{path}.#{key}", seen_refs: Set.new) + evaluated << key + matched_here = true + end + + next if matched_here + + if schema["additionalProperties"].is_a?(Hash) + validate_schema(schema["additionalProperties"], value, root: root, path: "#{path}.#{key}", seen_refs: Set.new) + evaluated << key + elsif schema["additionalProperties"] == true + evaluated << key elsif schema["additionalProperties"] == false flunk "#{path} has unexpected key #{key}" end end + + evaluated end - def matches_schema?(schema, document, root) - assert_matches_schema(schema, document, root: root) - true + def probe_schema(schema, document, root:, path:, seen_refs:) + [true, validate_schema(schema, document, root: root, path: path, seen_refs: seen_refs)] rescue Minitest::Assertion - false + [false, Set.new] end # Loaded schema documents keyed by absolute path, and the path each parsed @@ -122,21 +227,6 @@ def load_schema_file(path) schema_documents[path] ||= JSON.parse(path.read).tap { |schema| schema_sources[schema] = path } end - # Returns the referenced schema node and the root document it lives in. - # A ref with a file part switches the root so nested `#/$defs` refs inside - # the target file resolve against that file. - def resolve_schema_ref(schema, root) - seen = [] - while schema.is_a?(Hash) && schema["$ref"] - location = [schema.object_id, root.object_id] - raise ArgumentError, "cyclic schema reference" if seen.include?(location) - - seen << location - schema, root = resolve_single_schema_ref(schema, root) - end - [schema, root] - end - def resolve_single_schema_ref(schema, root) ref = schema.fetch("$ref") file_part, fragment = ref.split("#", 2) @@ -144,11 +234,11 @@ def resolve_single_schema_ref(schema, root) target_root = root else source = schema_sources[root] - raise ArgumentError, "cannot resolve #{ref}: root schema was not loaded from a file" unless source + raise SchemaError, "cannot resolve #{ref}: root schema was not loaded from a file" unless source target_path = source.dirname.join(file_part).cleanpath unless target_path.to_s.start_with?("#{ROOT}/") && target_path.file? - raise ArgumentError, "unresolved $ref #{ref} from #{source.relative_path_from(ROOT)}" + raise SchemaError, "unresolved $ref #{ref} from #{source.relative_path_from(ROOT)}" end target_root = load_schema_file(target_path) @@ -159,17 +249,17 @@ def resolve_single_schema_ref(schema, root) def resolve_json_pointer(document, fragment) return document if fragment.nil? || fragment.empty? - raise ArgumentError, "$ref fragment must be a JSON Pointer: ##{fragment}" unless fragment.start_with?("/") + raise SchemaError, "$ref fragment must be a JSON Pointer: ##{fragment}" unless fragment.start_with?("/") fragment.delete_prefix("/").split("/").reduce(document) do |value, token| decoded = token.gsub("~1", "/").gsub("~0", "~") case value when Hash then value.fetch(decoded) when Array then value.fetch(Integer(decoded, 10)) - else raise ArgumentError, "$ref ##{fragment} traverses a scalar" + else raise SchemaError, "$ref ##{fragment} traverses a scalar" end end - rescue KeyError, IndexError - raise ArgumentError, "$ref ##{fragment} does not exist in the target schema" + rescue KeyError, IndexError, ArgumentError + raise SchemaError, "$ref ##{fragment} does not exist in the target schema" end end diff --git a/scripts/validate_documents.rb b/scripts/validate_documents.rb index 9730b29..17f428f 100644 --- a/scripts/validate_documents.rb +++ b/scripts/validate_documents.rb @@ -5,6 +5,7 @@ require "yaml" ROOT = Pathname(__dir__).join("..").expand_path +FORBIDDEN_PUBLIC_KEYS = /maximum|reserve_minor_units|operator_id|reason|bidder_id|leader_id|winner_id|bid_id|bidder_notice|positions|executed_minor_units|authorization_history|reserve_history|voided_bid_ids/ def relative(path) Pathname(path).relative_path_from(ROOT) @@ -88,9 +89,102 @@ def property_names(document) names.uniq end +def non_negative_integer?(value, max) + value.is_a?(Integer) && value >= 0 && value <= max +end + +def positive_integer?(value, max) + value.is_a?(Integer) && value >= 1 && value <= max +end + +def validate_fixture(path, fixture, timed_proxy_schema, timestamp_regex, money_bound, errors) + label = relative(path) + unless fixture.is_a?(Hash) + errors << "#{label}: fixture must be an object" + return + end + + required = timed_proxy_schema.fetch("required") + allowed = timed_proxy_schema.fetch("properties").keys + missing = required.reject { |key| fixture.key?(key) } + errors << "#{label}: missing required keys: #{missing.join(', ')}" if missing.any? + extra = fixture.keys - allowed + errors << "#{label}: unexpected keys: #{extra.join(', ')}" if extra.any? + + currency = fixture["currency"] + unless currency.is_a?(String) && /\A[A-Z]{3}\z/.match?(currency) + errors << "#{label}: currency must be a 3-letter ISO 4217 code" + end + unless non_negative_integer?(fixture["opening_minor_units"], money_bound) + errors << "#{label}: opening_minor_units must be an integer in 0..#{money_bound}" + end + reserve = fixture["reserve_minor_units"] + unless reserve.nil? || non_negative_integer?(reserve, money_bound) + errors << "#{label}: reserve_minor_units must be null or an integer in 0..#{money_bound}" + end + + increments = fixture["increments"] + if !increments.is_a?(Array) || increments.empty? + errors << "#{label}: increments must be a non-empty array" + else + increments.each_with_index do |tier, index| + unless tier.is_a?(Hash) + errors << "#{label}: increments[#{index}] must be an object" + next + end + tier_missing = %w[from_minor_units amount_minor_units].reject { |key| tier.key?(key) } + errors << "#{label}: increments[#{index}] missing #{tier_missing.join(', ')}" if tier_missing.any? + tier_extra = tier.keys - %w[from_minor_units amount_minor_units] + errors << "#{label}: increments[#{index}] unexpected keys: #{tier_extra.join(', ')}" if tier_extra.any? + unless non_negative_integer?(tier["from_minor_units"], money_bound) + errors << "#{label}: increments[#{index}].from_minor_units must be an integer in 0..#{money_bound}" + end + unless positive_integer?(tier["amount_minor_units"], money_bound) + errors << "#{label}: increments[#{index}].amount_minor_units must be an integer in 1..#{money_bound}" + end + end + end + + %w[opens_at closes_at].each do |field| + value = fixture[field] + unless value.is_a?(String) && timestamp_regex.match?(value) + errors << "#{label}: #{field} must be a valid RFC 3339 timestamp with UTC offset" + end + end + + return unless fixture.key?("extension") + + extension = fixture["extension"] + return if extension.nil? + + unless extension.is_a?(Hash) + errors << "#{label}: extension must be null or an object" + return + end + + ext_schema = timed_proxy_schema.dig("$defs", "extension") + ext_missing = ext_schema.fetch("required").reject { |key| extension.key?(key) } + errors << "#{label}: extension missing #{ext_missing.join(', ')}" if ext_missing.any? + ext_extra = extension.keys - ext_schema.fetch("properties").keys + errors << "#{label}: extension unexpected keys: #{ext_extra.join(', ')}" if ext_extra.any? + unless non_negative_integer?(extension["trigger_window_seconds"], money_bound) + errors << "#{label}: extension.trigger_window_seconds must be an integer in 0..#{money_bound}" + end + unless positive_integer?(extension["duration_seconds"], money_bound) + errors << "#{label}: extension.duration_seconds must be an integer in 1..#{money_bound}" + end + if extension.key?("extend_on_void") && ![true, false].include?(extension["extend_on_void"]) + errors << "#{label}: extension.extend_on_void must be a boolean" + end +end + errors = [] -Dir[ROOT.join("{specification,conformance}/**/*.json")].sort.each do |path| +json_paths = ( + Dir[ROOT.join("{specification,conformance}/**/*.json")] + + Dir[ROOT.join("rfcs/proposals/flexible-live-scheduling/*.schema.json")] +).uniq.sort +json_paths.each do |path| JSON.parse(File.read(path)) rescue JSON::ParserError => e errors << "#{relative(path)}: invalid JSON: #{e.message}" @@ -110,12 +204,47 @@ def property_names(document) errors << "specification/asyncapi.yaml: expected AsyncAPI 3" unless asyncapi["asyncapi"]&.start_with?("3.") errors << "specification/asyncapi.yaml: channels must be an object" unless asyncapi["channels"].is_a?(Hash) -schemas = Dir[ROOT.join("{specification,conformance}/**/*.schema.json")].sort +# Version consistency across specification/VERSION, OpenAPI, AsyncAPI, and Ruby engine. +version_file = ROOT.join("specification/VERSION") +spec_version = version_file.file? ? version_file.read.strip : nil +if spec_version.nil? || spec_version.empty? + errors << "specification/VERSION: missing or empty specification version" +else + if openapi.dig("info", "version") != spec_version + errors << "specification/openapi.yaml: info.version (#{openapi.dig('info', 'version').inspect}) does not match specification/VERSION (#{spec_version.inspect})" + end + if asyncapi.dig("info", "version") != spec_version + errors << "specification/asyncapi.yaml: info.version (#{asyncapi.dig('info', 'version').inspect}) does not match specification/VERSION (#{spec_version.inspect})" + end + ruby_version_path = ROOT.join("ruby/engine/lib/rbbb/version.rb") + if !ruby_version_path.file? + errors << "ruby/engine/lib/rbbb/version.rb: missing engine version file" + else + ruby_spec_match = ruby_version_path.read.match(/SPECIFICATION_VERSION\s*=\s*"([^"]+)"/) + ruby_spec_version = ruby_spec_match && ruby_spec_match[1] + if ruby_spec_version != spec_version + errors << "ruby/engine/lib/rbbb/version.rb: SPECIFICATION_VERSION (#{ruby_spec_version.inspect}) does not match specification/VERSION (#{spec_version.inspect})" + end + end +end + +schemas = ( + Dir[ROOT.join("{specification,conformance}/**/*.schema.json")] + + Dir[ROOT.join("rfcs/proposals/flexible-live-scheduling/*.schema.json")] +).uniq.sort schema_documents = {} schema_ids = {} schemas.each do |path_string| path = Pathname(path_string) - schema = JSON.parse(path.read) + begin + schema = JSON.parse(path.read) + rescue JSON::ParserError + next + end + unless schema.is_a?(Hash) + errors << "#{relative(path)}: JSON Schema root must be an object" + next + end schema_documents[path] = schema errors << "#{relative(path)}: missing $schema" unless schema.key?("$schema") errors << "#{relative(path)}: missing $id" unless schema.key?("$id") @@ -173,6 +302,27 @@ def property_names(document) end end +money_schema = schema_documents.fetch(ROOT.join("specification/common/money.schema.json")) +money_bound = money_schema.dig("$defs", "minorUnits", "maximum") +timestamp_schema = schema_documents.fetch(ROOT.join("specification/common/timestamp.schema.json")) +timestamp_regex = Regexp.new(timestamp_schema.fetch("pattern").sub(/\A\^/) { "\\A" }.sub(/\$\z/) { "\\z" }) +timed_proxy_schema = schema_documents.fetch(ROOT.join("specification/configuration/timed-proxy.schema.json")) + +fixture_paths = Dir[ROOT.join("conformance/fixtures/*.yaml")].sort +fixture_paths.each do |path| + fixture = YAML.safe_load_file(path, aliases: false) + validate_fixture(path, fixture, timed_proxy_schema, timestamp_regex, money_bound, errors) +end + +scenario_schema = schema_documents.fetch(ROOT.join("conformance/schemas/scenario.schema.json")) +scenario_required = scenario_schema.fetch("required") +scenario_allowed = scenario_schema.fetch("properties").keys +expected_required = scenario_schema.dig("properties", "expected", "required") +expected_allowed = scenario_schema.dig("properties", "expected", "properties").keys +rfc_pattern = Regexp.new( + scenario_schema.dig("properties", "rfcs", "items", "pattern").sub(/\A\^/) { "\\A" }.sub(/\$\z/) { "\\z" } +) + scenario_paths = Dir[ROOT.join("conformance/scenarios/**/*.yaml")].sort scenario_names = {} scenario_command_types = [] @@ -183,42 +333,92 @@ def property_names(document) scenario_paths.each do |path| scenario = YAML.safe_load_file(path, aliases: false) - required = %w[name specification_version rfcs configuration starting_state commands expected] - missing = required.reject { |key| scenario.key?(key) } + unless scenario.is_a?(Hash) + errors << "#{relative(path)}: scenario must be an object" + next + end + + missing = scenario_required.reject { |key| scenario.key?(key) } errors << "#{relative(path)}: missing #{missing.join(', ')}" if missing.any? + extra = scenario.keys - scenario_allowed + errors << "#{relative(path)}: unexpected top-level keys: #{extra.join(', ')}" if extra.any? name = scenario["name"] + errors << "#{relative(path)}: name must be a non-empty string" unless name.is_a?(String) && !name.empty? if scenario_names.key?(name) errors << "#{relative(path)}: duplicate name also used by #{scenario_names[name]}" else scenario_names[name] = relative(path) end - fixture = scenario.dig("configuration", "fixture") + sv = scenario["specification_version"] + unless sv.is_a?(String) && !sv.empty? + errors << "#{relative(path)}: specification_version must be a non-empty string" + end + + unless scenario["configuration"].is_a?(Hash) + errors << "#{relative(path)}: configuration must be an object" + end + unless scenario["starting_state"].is_a?(Hash) + errors << "#{relative(path)}: starting_state must be an object" + end + commands = scenario["commands"] + if !commands.is_a?(Array) || commands.empty? || !commands.all? { |cmd| cmd.is_a?(Hash) } + errors << "#{relative(path)}: commands must be a non-empty array of objects" + end + + fixture = scenario.dig("configuration", "fixture") if scenario["configuration"].is_a?(Hash) fixture_path = ROOT.join("conformance/fixtures/#{fixture}.yaml") if fixture errors << "#{relative(path)}: unknown fixture #{fixture}" if fixture && !fixture_path.file? - Array(scenario["rfcs"]).each do |rfc| - matches = Dir[ROOT.join("rfcs/#{rfc}-*.md")] - errors << "#{relative(path)}: unknown RFC #{rfc}" if matches.empty? + rfcs = scenario["rfcs"] + if !rfcs.is_a?(Array) || rfcs.empty? + errors << "#{relative(path)}: rfcs must be a non-empty array" + else + rfcs.each do |rfc| + unless rfc.is_a?(String) && rfc_pattern.match?(rfc) + errors << "#{relative(path)}: invalid RFC identifier #{rfc.inspect} (expected 4-digit string)" + next + end + matches = Dir[ROOT.join("rfcs/#{rfc}-*.md")] + errors << "#{relative(path)}: unknown RFC #{rfc}" if matches.empty? + end end - expected = scenario["expected"] || {} - errors << "#{relative(path)}: expected.public_events must be an array" unless expected["public_events"].is_a?(Array) + expected = scenario["expected"] + unless expected.is_a?(Hash) + errors << "#{relative(path)}: expected must be an object" + next + end + expected_missing = expected_required.reject { |key| expected.key?(key) } + errors << "#{relative(path)}: expected missing #{expected_missing.join(', ')}" if expected_missing.any? + expected_extra = expected.keys - expected_allowed + errors << "#{relative(path)}: expected has unexpected keys: #{expected_extra.join(', ')}" if expected_extra.any? + + if !expected["public_events"].is_a?(Array) || !expected["public_events"].all? { |item| item.is_a?(Hash) } + errors << "#{relative(path)}: expected.public_events must be an array of objects" + end + if expected.key?("privileged_events") && + (!expected["privileged_events"].is_a?(Array) || !expected["privileged_events"].all? { |item| item.is_a?(Hash) }) + errors << "#{relative(path)}: expected.privileged_events must be an array of objects" + end + if expected.key?("rejections") && + (!expected["rejections"].is_a?(Array) || !expected["rejections"].all? { |item| item.is_a?(Hash) }) + errors << "#{relative(path)}: expected.rejections must be an array of objects" + end errors << "#{relative(path)}: expected.final_state must be an object" unless expected["final_state"].is_a?(Hash) - forbidden_public_keys = /maximum|reserve_minor_units|operator_id|reason|bidder_id|leader_id|winner_id/ Array(expected["public_events"]).each_with_index do |event, index| - leaked = deep_keys(event).grep(forbidden_public_keys).uniq + leaked = deep_keys(event).grep(FORBIDDEN_PUBLIC_KEYS).uniq next if leaked.empty? errors << "#{relative(path)}: public_events[#{index}] contains privileged keys: #{leaked.join(', ')}" end - scenario_command_types.concat(Array(scenario["commands"]).filter_map { |command| command["type"] }) - scenario_public_event_types.concat(Array(expected["public_events"]).filter_map { |event| event["type"] }) - scenario_privileged_event_types.concat(Array(expected["privileged_events"]).filter_map { |event| event["type"] }) - scenario_rejection_reasons.concat(Array(expected["rejections"]).filter_map { |rejection| rejection["reason"] }) + scenario_command_types.concat(Array(commands).filter_map { |command| command["type"] if command.is_a?(Hash) }) + scenario_public_event_types.concat(Array(expected["public_events"]).filter_map { |event| event["type"] if event.is_a?(Hash) }) + scenario_privileged_event_types.concat(Array(expected["privileged_events"]).filter_map { |event| event["type"] if event.is_a?(Hash) }) + scenario_rejection_reasons.concat(Array(expected["rejections"]).filter_map { |rejection| rejection["reason"] if rejection.is_a?(Hash) }) Array(expected["rejections"]).each_with_index do |rejection, index| scenario_rejections << [relative(path), index, rejection] if rejection.is_a?(Hash) end @@ -305,14 +505,13 @@ def property_names(document) errors << "#{label}: rejections[#{index}] contains keys the rejection schema does not declare for #{rejection['reason']}: #{undeclared_keys.join(', ')}" end -forbidden_contract_keys = /maximum|reserve_minor_units|operator_id|reason|bidder_id|leader_id|winner_id/ { "specification/events/public-event.schema.json" => public_event_schema, "specification/state/bidding-unit.schema.json" => schema_documents.fetch( ROOT.join("specification/state/bidding-unit.schema.json") ) }.each do |label, document| - leaked = property_names(document).grep(forbidden_contract_keys) + leaked = property_names(document).grep(FORBIDDEN_PUBLIC_KEYS) errors << "#{label}: public schema contains privileged properties: #{leaked.join(', ')}" if leaked.any? end @@ -336,8 +535,6 @@ def property_names(document) # Cross-language determinism: every amount and timestamp must go through the # shared bounded definitions so no implementation can accept a value that # another cannot represent exactly. -money_schema = schema_documents.fetch(ROOT.join("specification/common/money.schema.json")) -money_bound = money_schema.dig("$defs", "minorUnits", "maximum") errors << "specification/common/money.schema.json: minorUnits must declare maximum" unless money_bound money_schema.fetch("$defs").each do |name, definition| next if definition["maximum"] == money_bound @@ -414,4 +611,4 @@ def property_names(document) exit 1 end -puts "Validated #{schemas.length} JSON Schemas, #{scenario_paths.length} conformance scenarios, and the OpenAPI/AsyncAPI documents." +puts "Validated #{schemas.length} JSON Schemas, #{fixture_paths.length} conformance fixtures, #{scenario_paths.length} conformance scenarios, and the OpenAPI/AsyncAPI documents." diff --git a/specification/asyncapi.yaml b/specification/asyncapi.yaml index 0e642af..2b3794d 100644 --- a/specification/asyncapi.yaml +++ b/specification/asyncapi.yaml @@ -3,8 +3,9 @@ info: title: RBBB event subscription API version: 0.2.0-draft description: >- - Experimental contract for committed public RFC 0001 event delivery. - Private audit events require a separate privileged surface. + Experimental 0.2.0-draft contract for committed public event delivery under + RFC 0001 and RFC 0005 (fixed bid ladder). Private audit events require a + separate privileged surface. channels: biddingUnitEvents: address: auctions/{auctionId}/bidding-units/{biddingUnitId}/events diff --git a/specification/common/integer.schema.json b/specification/common/integer.schema.json index 4045fa0..bb7e34f 100644 --- a/specification/common/integer.schema.json +++ b/specification/common/integer.schema.json @@ -3,7 +3,7 @@ "$id": "https://github.com/willtmc/rbbb/specification/common/integer.schema.json", "title": "Bounded integer", "description": "Shared integer ranges for counters, versions, priorities, and durations. Every non-monetary integer property in the contract references one of the $defs below so all implementations share one interoperable range; monetary amounts use money.schema.json instead.", - "x-rbbb-status": "draft", + "x-rbbb-status": "experimental", "type": "integer", "minimum": 0, "maximum": 9007199254740991, diff --git a/specification/common/money.schema.json b/specification/common/money.schema.json index c666307..a25d6f7 100644 --- a/specification/common/money.schema.json +++ b/specification/common/money.schema.json @@ -3,7 +3,7 @@ "$id": "https://github.com/willtmc/rbbb/specification/common/money.schema.json", "title": "Money", "description": "A reusable exact monetary amount for boundaries that are not already scoped to one currency. RFC 0001 bidding-unit commands use *_minor_units fields instead; every such field references the shared $defs below so all implementations share one integer range.", - "x-rbbb-status": "draft", + "x-rbbb-status": "experimental", "type": "object", "additionalProperties": false, "required": ["currency", "minor_units"], diff --git a/specification/common/timestamp.schema.json b/specification/common/timestamp.schema.json index a586e3d..d09ceb9 100644 --- a/specification/common/timestamp.schema.json +++ b/specification/common/timestamp.schema.json @@ -3,7 +3,7 @@ "$id": "https://github.com/willtmc/rbbb/specification/common/timestamp.schema.json", "title": "Authoritative timestamp", "description": "RFC 3339 date-time with an explicit UTC offset and at most millisecond precision. Finer fractions are invalid so every implementation, including those whose native time type is millisecond-based, can replay the same command stream exactly.", - "x-rbbb-status": "draft", + "x-rbbb-status": "experimental", "type": "string", "format": "date-time", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,3})?(Z|[+-][0-9]{2}:[0-9]{2})$" diff --git a/specification/concepts.md b/specification/concepts.md index 22602a6..7ec8e1f 100644 --- a/specification/concepts.md +++ b/specification/concepts.md @@ -47,7 +47,11 @@ details. Money is represented as an ISO 4217 currency code and integer minor units. Floating-point amounts are forbidden at public boundaries. -## Deferred semantics - -This draft does not decide pricing, increment, tie, reserve, extension, -opening, or closing rules. Those require accepted RFCs and conformance cases. +## Normative semantics and RFCs + +Pricing, increment, fixed-ladder, tie, reserve, extension, scheduling, and +closing rules are defined by accepted RFCs +[0001](../rfcs/0001-timed-online-proxy-bidding.md) through +[0005](../rfcs/0005-fixed-bid-ladder.md) and backed by executable conformance +suites under [`conformance/`](../conformance/README.md). Any new or changed +auction semantics continue to require an accepted RFC and conformance cases. diff --git a/specification/contract.md b/specification/contract.md index 44d6707..5292ec4 100644 --- a/specification/contract.md +++ b/specification/contract.md @@ -83,8 +83,14 @@ unions: - `events/public-event.schema.json` contains only observable price, reserve status, schedule, and closing-result facts; - `events/privileged-event.schema.json` contains the identities, maxima, - reserve values, operator reasons, notification intent, and resulting state - needed for audit and replay. + reserve values, operator reasons, notification intent, and flat replay state + fields on transition event payloads (`maximum_accepted`, `maximum_increased`, + `maximum_reduced`, `bid_voided`, `reserve_changed`, `closing_time_changed`, + `bidding_closed`), while companion privileged events + (`executed_amount_changed`, `notification_requested`) carry only their + specific fields. Envelope metadata (`command_id`, `aggregate_version`, + `effective_at`) lives on `events/base.schema.json` rather than duplicated + inside `data`. The public schema must never acquire a bidder, leader, or winner identifier; a private maximum; a reserve amount; or an operator-only reason. A host may map @@ -227,6 +233,14 @@ must not stand in for a maximum revocation or partial execution removal. Missing source scope/authorization/audit evidence is unsupported, not inferred. The post-close correction boundary remains unchanged. +By default, an operator `void_bid` does not extend closing time. When +`extension.extend_on_void` is explicitly set to `true` in +`configuration/timed-proxy.schema.json`, a `void_bid` that changes the leader +or standing amount inside the trigger window extends `closes_at` using the +standard soft-close rule, records the extended `closes_at` on `bid_voided`, and +emits a public `closing_time_changed` event (scenario `044`). RFC 0004 linked +closing sets keep `extend_on_void` disabled. + ## Fixed ladder state and compatibility Position `maximum_minor_units` retains entered authority. diff --git a/specification/events/privileged-event.schema.json b/specification/events/privileged-event.schema.json index 6336882..f8b7852 100644 --- a/specification/events/privileged-event.schema.json +++ b/specification/events/privileged-event.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/willtmc/rbbb/specification/events/privileged-event.schema.json", "title": "Privileged RFC 0001 event", - "description": "Audit event that may contain bidder identity, private maxima, reserve amount, operator reason, or replay state.", + "description": "Audit event that may contain bidder identity, private maxima, reserve amount, operator reason, or flat replay state.", "x-rbbb-status": "experimental", "allOf": [{"$ref": "./base.schema.json"}], "oneOf": [ @@ -65,69 +65,125 @@ ], "unevaluatedProperties": false, "$defs": { - "state": {"$ref": "../state/aggregate.schema.json"}, - "maximumAccepted": { + "transitionState": { "type": "object", - "additionalProperties": false, "required": [ - "bid_id", - "bidder_id", - "maximum_minor_units", - "executed_minor_units", - "bidder_notice", - "state" + "leader_id", + "standing_minor_units", + "next_required_minor_units", + "reserve_status", + "reserve_minor_units", + "closes_at", + "positions", + "authorization_history", + "reserve_history", + "voided_bid_ids" ], "properties": { - "bid_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, - "executed_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, - "bidder_notice": {"$ref": "maximum-notice.schema.json"}, - "state": {"$ref": "#/$defs/state"} + "leader_id": {"type": ["string", "null"], "minLength": 1, "maxLength": 255}, + "standing_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, + "next_required_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "reserve_status": { + "type": ["string", "null"], + "enum": ["reserve_not_met", "reserve_met", null] + }, + "reserve_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, + "closes_at": {"$ref": "../common/timestamp.schema.json"}, + "positions": { + "type": "object", + "additionalProperties": {"$ref": "../state/aggregate.schema.json#/$defs/position"} + }, + "authorization_history": { + "type": "array", + "items": { + "oneOf": [ + {"$ref": "../state/aggregate.schema.json#/$defs/placeBidAuthorization"}, + {"$ref": "../state/aggregate.schema.json#/$defs/maximumReduction"} + ] + } + }, + "reserve_history": { + "type": "array", + "items": {"$ref": "../state/aggregate.schema.json#/$defs/reserveChange"} + }, + "voided_bid_ids": { + "type": "array", + "uniqueItems": true, + "items": {"type": "string", "minLength": 1, "maxLength": 255} + } } }, + "maximumAccepted": { + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": [ + "bid_id", + "bidder_id", + "maximum_minor_units", + "executed_minor_units", + "bidder_notice" + ], + "properties": { + "bid_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "executed_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "bidder_notice": {"$ref": "maximum-notice.schema.json"} + } + } + ], + "unevaluatedProperties": false + }, "maximumReduced": { - "type": "object", - "additionalProperties": false, - "required": [ - "bidder_id", - "old_maximum_minor_units", - "new_maximum_minor_units", - "executed_floor_minor_units", - "bidder_notice", - "state" + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": [ + "bidder_id", + "old_maximum_minor_units", + "new_maximum_minor_units", + "executed_floor_minor_units", + "bidder_notice" + ], + "properties": { + "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "old_maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "new_maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "executed_floor_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, + "bidder_notice": {"$ref": "maximum-notice.schema.json"} + } + } ], - "properties": { - "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "old_maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, - "new_maximum_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, - "executed_floor_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"}, - "bidder_notice": {"$ref": "maximum-notice.schema.json"}, - "state": {"$ref": "#/$defs/state"} - } + "unevaluatedProperties": false }, "bidVoided": { - "type": "object", - "additionalProperties": false, - "required": [ - "bid_id", - "bidder_id", - "operator_id", - "reason", - "notification_policy", - "state" + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": [ + "bid_id", + "bidder_id", + "operator_id", + "reason", + "notification_policy" + ], + "properties": { + "bid_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, + "notification_policy": { + "type": "string", + "enum": ["affected", "removed_bidder", "all_bidders", "none"] + } + } + } ], - "properties": { - "bid_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "bidder_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, - "notification_policy": { - "type": "string", - "enum": ["affected", "removed_bidder", "all_bidders", "none"] - }, - "state": {"$ref": "#/$defs/state"} - } + "unevaluatedProperties": false }, "executedAmountChanged": { "type": "object", @@ -158,45 +214,83 @@ } }, "reserveChanged": { - "type": "object", - "additionalProperties": false, - "required": [ - "operator_id", - "reason", - "old_reserve_minor_units", - "new_reserve_minor_units", - "state" + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": [ + "operator_id", + "reason", + "old_reserve_minor_units", + "new_reserve_minor_units" + ], + "properties": { + "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, + "old_reserve_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, + "new_reserve_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"} + } + } ], - "properties": { - "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, - "old_reserve_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, - "new_reserve_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, - "state": {"$ref": "#/$defs/state"} - } + "unevaluatedProperties": false }, "closingTimeChanged": { - "type": "object", - "additionalProperties": false, - "required": ["operator_id", "reason", "old_closes_at", "closes_at", "state"], - "properties": { - "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, - "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, - "old_closes_at": {"oneOf": [{"type": "null"}, {"$ref": "../common/timestamp.schema.json"}]}, - "closes_at": {"$ref": "../common/timestamp.schema.json"}, - "state": {"$ref": "#/$defs/state"} - } + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": ["operator_id", "reason", "old_closes_at"], + "properties": { + "operator_id": {"type": "string", "minLength": 1, "maxLength": 255}, + "reason": {"type": "string", "minLength": 1, "maxLength": 2000}, + "old_closes_at": {"$ref": "../common/timestamp.schema.json"} + } + } + ], + "unevaluatedProperties": false }, "biddingClosed": { - "type": "object", - "additionalProperties": false, - "required": ["result", "winner_id", "winning_minor_units", "state"], - "properties": { - "result": {"type": "string", "enum": ["sold", "no_sale", "no_bid"]}, - "winner_id": {"type": ["string", "null"], "minLength": 1, "maxLength": 255}, - "winning_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"}, - "state": {"$ref": "#/$defs/state"} - } + "allOf": [ + {"$ref": "#/$defs/transitionState"}, + { + "type": "object", + "required": ["status", "result", "winner_id", "winning_minor_units"], + "properties": { + "status": {"const": "closed"}, + "result": {"type": "string", "enum": ["sold", "no_sale", "no_bid"]}, + "winner_id": {"type": ["string", "null"], "minLength": 1, "maxLength": 255}, + "winning_minor_units": {"$ref": "../common/money.schema.json#/$defs/optionalMinorUnits"} + } + }, + { + "if": {"properties": {"result": {"const": "sold"}}}, + "then": { + "properties": { + "winner_id": {"type": "string", "minLength": 1}, + "winning_minor_units": {"$ref": "../common/money.schema.json#/$defs/minorUnits"} + } + } + }, + { + "if": {"properties": {"result": {"enum": ["no_sale", "no_bid"]}}}, + "then": { + "properties": { + "winner_id": {"const": null}, + "winning_minor_units": {"const": null} + } + } + }, + { + "if": {"properties": {"result": {"const": "no_bid"}}}, + "then": { + "properties": { + "leader_id": {"const": null}, + "standing_minor_units": {"const": null} + } + } + } + ], + "unevaluatedProperties": false } } } diff --git a/specification/events/public-event.schema.json b/specification/events/public-event.schema.json index 0109f72..84d603e 100644 --- a/specification/events/public-event.schema.json +++ b/specification/events/public-event.schema.json @@ -56,7 +56,7 @@ "additionalProperties": false, "required": ["closes_at"], "properties": { - "old_closes_at": {"oneOf": [{"type": "null"}, {"$ref": "../common/timestamp.schema.json"}]}, + "old_closes_at": {"$ref": "../common/timestamp.schema.json"}, "closes_at": {"$ref": "../common/timestamp.schema.json"} } }, diff --git a/specification/openapi.yaml b/specification/openapi.yaml index 85cbd1c..5e74680 100644 --- a/specification/openapi.yaml +++ b/specification/openapi.yaml @@ -3,7 +3,8 @@ info: title: RBBB command API version: 0.2.0-draft description: >- - Experimental language-neutral HTTP command contract for RFC 0001. No + Experimental 0.2.0-draft language-neutral HTTP command contract for RFC 0001 + timed online proxy bidding with RFC 0005 fixed bid ladder execution. No hosted service exists and production service guarantees are not yet stable. license: name: MIT @@ -31,8 +32,14 @@ paths: application/json: schema: $ref: "#/components/schemas/CommandResult" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" "409": - description: Aggregate version or command-id conflict + description: Aggregate version or bid-id conflict (stale_aggregate_version or bid_id_already_exists) content: application/json: schema: @@ -48,7 +55,42 @@ components: bearerAuth: type: http scheme: bearer + responses: + BadRequest: + description: Malformed request body or command envelope validation failure + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + Unauthorized: + description: Missing or invalid bearer authentication credentials + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + Forbidden: + description: Authenticated caller is not authorized for the requested command or bidding unit + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" schemas: + ErrorResponse: + type: object + additionalProperties: false + required: [status, error] + properties: + status: + type: string + enum: [error] + error: + type: string + minLength: 1 + maxLength: 255 + message: + type: string + minLength: 1 + maxLength: 2000 CommandResult: type: object additionalProperties: false