diff --git a/examples/durable_shared_group_host.rb b/examples/durable_shared_group_host.rb index 9c6d5ea..a089e39 100644 --- a/examples/durable_shared_group_host.rb +++ b/examples/durable_shared_group_host.rb @@ -1,24 +1,19 @@ # frozen_string_literal: true require "json" -require "sqlite3" require "securerandom" +require_relative "support/sqlite_store" require_relative "shared_group_host" module RBBBExamples # Local SQLite reference adapter. The engine gem has no SQLite dependency. class DurableSharedGroupHost + include SqliteStore + def initialize(path:, configurations:, clock:) @path = File.expand_path(path) @document = canonical({"format" => 1, "configurations" => configurations, "clock" => clock}) build_host # Validate configuration before creating storage. - begin - File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| } - rescue Errno::EEXIST - stat = File.lstat(@path) - unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero? - raise ArgumentError, "database must be an owner-only regular file" - end - end + secure_file! transaction do |db| db.execute("CREATE TABLE IF NOT EXISTS metadata (id INTEGER PRIMARY KEY CHECK(id = 1), document TEXT NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS commits (sequence INTEGER PRIMARY KEY, command_id TEXT NOT NULL UNIQUE, request TEXT NOT NULL, result TEXT NOT NULL)") @@ -37,7 +32,7 @@ def initialize(path:, configurations:, clock:) def submit(unit_id:, command:, expected_revision:) transaction do |db| host = restore(db) - request = host.send(:normalize_request, unit_id, command, expected_revision) + request = host.normalize_request(unit_id, command, expected_revision) receipt = host.submit(unit_id: request.fetch("unit_id"), command: request.fetch("command"), expected_revision: expected_revision) persist(db, request, receipt) @@ -48,7 +43,7 @@ def submit(unit_id:, command:, expected_revision:) def close_group(command_id:, effective_at:, expected_revision:) transaction do |db| host = restore(db) - request = host.send(:normalize_close_request, command_id, effective_at, expected_revision) + request = host.normalize_close_request(command_id, effective_at, expected_revision) receipt = dispatch(host, request) persist(db, request, receipt) receipt @@ -58,9 +53,7 @@ def close_group(command_id:, effective_at:, expected_revision:) # One transaction returns both the revision and all member projections. def public_view transaction do |db| - host = restore(db) - snapshot = host.instance_variable_get(:@snapshot) - {"clock" => snapshot.clock.public_view, "units" => host.public_view} + restore(db).public_snapshot end end @@ -192,21 +185,6 @@ def canonical(value) JSON.generate(sort.call(normalized)) end - def transaction - db = SQLite3::Database.new(@path) - db.busy_timeout = 5000 - db.execute("PRAGMA synchronous = FULL") - db.execute("BEGIN IMMEDIATE") - result = yield db - db.execute("COMMIT") - result - rescue Exception - db.execute("ROLLBACK") if db&.transaction_active? - raise - ensure - db&.close - end - # Fault-injection seam: never deliver notifications before durable commit. def before_commit(_db) end diff --git a/examples/live_scheduling_consumer.rb b/examples/live_scheduling_consumer.rb index 571bdbd..5aeefa6 100644 --- a/examples/live_scheduling_consumer.rb +++ b/examples/live_scheduling_consumer.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require "sqlite3" +require_relative "support/sqlite_store" require_relative "live_scheduling_reader" module RBBBExamples @@ -8,13 +8,15 @@ module RBBBExamples # The fetch callback MUST authenticate/authorize each call and return only its # authorized projection. A digest is integrity bookkeeping, not authentication. class LiveSchedulingConsumer + include SqliteStore + class InvalidCheckpoint < StandardError; end def initialize(path:, tenant_id:, auction_id:, visibility:, fetch:) raise ArgumentError, "unsupported visibility" unless %w[public privileged].include?(visibility) - @path, @tenant, @auction, @visibility, @fetch = path, tenant_id, auction_id, visibility, fetch - File.open(path, File::RDWR | File::CREAT, 0o600) {} unless File.exist?(path) - File.chmod(0o600, path) + @path = File.expand_path(path) + @tenant, @auction, @visibility, @fetch = tenant_id, auction_id, visibility, fetch + secure_file! transaction do |db| db.execute("CREATE TABLE IF NOT EXISTS installation (slot INTEGER PRIMARY KEY CHECK(slot = 1), document TEXT NOT NULL)") end @@ -63,24 +65,14 @@ def validate!(result) payload["decision_sequence"].is_a?(Integer) && payload["decision_sequence"] >= 0 && payload["snapshot"].is_a?(Hash) raise InvalidCheckpoint, "invalid scope or checkpoint" end - unless result["sha256"] == Digest::SHA256.hexdigest(JSON.generate(payload)) + expected_digest = begin + Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(payload)) + rescue RBBB::LiveScheduling::Intent::Invalid + raise InvalidCheckpoint, "invalid digest" + end + unless result["sha256"] == expected_digest raise InvalidCheckpoint, "invalid digest" end - end - - def transaction - db = SQLite3::Database.new(@path) - db.busy_timeout = 5000 - db.execute("PRAGMA synchronous = FULL") - db.execute("BEGIN IMMEDIATE") - value = yield db - db.execute("COMMIT") - value - rescue Exception - db&.execute("ROLLBACK") if db&.transaction_active? - raise - ensure - db&.close end # Fault hooks for synthetic tests; no external effects. diff --git a/examples/live_scheduling_host.rb b/examples/live_scheduling_host.rb index 54a2ad4..8a1b9c4 100644 --- a/examples/live_scheduling_host.rb +++ b/examples/live_scheduling_host.rb @@ -2,9 +2,9 @@ require "json" require "securerandom" -require "sqlite3" require "rbbb" require "rbbb/live_scheduling" +require_relative "support/sqlite_store" module RBBBExamples # Embedded SQLite reference host, not an HTTP endpoint. Principal/permissions @@ -12,6 +12,8 @@ module RBBBExamples # writes across connections/processes (stronger than an auction-row lock). # Snapshot/receipts are privileged; never expose them directly to a bidder. class LiveSchedulingHost + include SqliteStore + class ResponseLost < StandardError; end attr_reader :auction_id, :tenant_id @@ -68,7 +70,7 @@ def bid(unit_id:, command:, principal_id:) raise ArgumentError, "server-assigned fields" if command.key?("effective_at") || command.key?("bidder_id") RBBB::LiveScheduling::Intent.identifier(unit_id) RBBB::LiveScheduling::Intent.identifier(principal_id) - allowed = %w[type command_id maximum_minor_units bid_id] + allowed = %w[type command_id maximum_minor_units bid_id expected_version] raise ArgumentError, "unknown bid property" unless (command.keys - allowed).empty? raise ArgumentError, "unsupported bid operation" unless %w[place_bid reduce_maximum].include?(command["type"]) RBBB::LiveScheduling::Intent.identifier(command["command_id"]) @@ -88,7 +90,7 @@ def void_bid(unit_id:, command:, principal_id:, permissions:) def change_reserve(unit_id:, command:, principal_id:, permissions:) RBBB::LiveScheduling::Intent.identifier(unit_id) RBBB::LiveScheduling::Intent.identifier(principal_id) - allowed = %w[type command_id reserve_minor_units reason notification_policy] + allowed = %w[type command_id reserve_minor_units reason] raise ArgumentError, "unknown reserve property" unless (command.keys - allowed).empty? raise ArgumentError, "unsupported reserve operation" unless command["type"] == "change_reserve" RBBB::LiveScheduling::Intent.identifier(command["command_id"]) @@ -175,14 +177,17 @@ def submit(request, principal, permissions) observed = RBBB::Timestamp.parse(@clock.call) at = last_time ? [observed, RBBB::Timestamp.parse(last_time)].max : observed clock_rollback(observed, at) if at > observed + retired_ids = JSON.parse(retired_json) coordinator = RBBB::LiveScheduling::Coordinator.new(auction_id: auction_id, configurations: document["configurations"], snapshot: state, policy: document["policy"], - profile: document["profile"], retired_group_ids: JSON.parse(retired_json)) + profile: document["profile"], retired_group_ids: retired_ids) commit_id = next_commit_id result = if sealed == 1 - coordinator.send(:reject, "auction_sealed") + RBBB::LiveScheduling::Coordinator::Result.new(state: coordinator.snapshot, records: [], + rejection_reason: "auction_sealed", retired_group_ids: retired_ids) elsif !permissions.include?(required) - coordinator.send(:reject, "not_authorized") + RBBB::LiveScheduling::Coordinator::Result.new(state: coordinator.snapshot, records: [], + rejection_reason: "not_authorized", retired_group_ids: retired_ids) else case request["kind"] when "register" @@ -248,12 +253,25 @@ def validate_retained_history!(db, stored) # Successful no-event operations can have a receipt without a journal batch. journaled = accepted.reject { |response| response.fetch("records").empty? } valid &&= commits.size == journaled.size - valid &&= commits.all? do |commit_id, encoded| - matching = journaled.select { |response| response["commit_id"] == commit_id } - records = JSON.parse(encoded) - outbox = db.execute("SELECT record_index, record FROM outbox WHERE commit_id = ? ORDER BY record_index", [commit_id]) - matching.size == 1 && matching.first.fetch("records") == records && - outbox == records.each_with_index.map { |record, index| [index, JSON.generate(record)] } + if valid && !commits.empty? + journaled_by_commit = Hash.new { |hash, key| hash[key] = [] } + journaled.each { |response| journaled_by_commit[response["commit_id"]] << response } + outbox_by_commit = Hash.new { |hash, key| hash[key] = [] } + db.execute( + "SELECT o.commit_id, o.record_index, o.record FROM outbox o " \ + "INNER JOIN commits c ON c.commit_id = o.commit_id " \ + "WHERE c.tenant = ? AND c.auction = ? ORDER BY o.commit_id, o.record_index", + [tenant_id, auction_id] + ).each do |commit_id, record_index, record| + outbox_by_commit[commit_id] << [record_index, record] + end + valid &&= commits.all? do |commit_id, encoded| + matching = journaled_by_commit[commit_id] + records = JSON.parse(encoded) + outbox = outbox_by_commit[commit_id] + matching.size == 1 && matching.first.fetch("records") == records && + outbox == records.each_with_index.map { |record, index| [index, JSON.generate(record)] } + end end raise RBBB::InvalidState, "incomplete retained registry or history" unless valid rescue JSON::ParserError, KeyError, TypeError @@ -268,28 +286,6 @@ def row(db) db.get_first_row("SELECT configuration, state, retired, sealed, last_time, sequence FROM auctions WHERE tenant = ? AND auction = ?", [tenant_id, auction_id]) end - def secure_file! - File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| } - rescue Errno::EEXIST - stat = File.lstat(@path) - raise ArgumentError, "database must be an owner-only regular file" unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero? - end - - def transaction - db = SQLite3::Database.new(@path) - db.busy_timeout = 5000 - db.execute("PRAGMA synchronous = FULL") - db.execute("BEGIN IMMEDIATE") - result = yield db - db.execute("COMMIT") - result - rescue Exception - db.execute("ROLLBACK") if db&.transaction_active? - raise - ensure - db&.close - end - def before_commit(_db); end def after_commit(_response); end def clock_rollback(_observed, _ordered) diff --git a/examples/live_scheduling_reader.rb b/examples/live_scheduling_reader.rb index dacfbc3..7ad2c33 100644 --- a/examples/live_scheduling_reader.rb +++ b/examples/live_scheduling_reader.rb @@ -47,7 +47,7 @@ def checkpoint(credential:, visibility:) end # Hash ONLY this authorized payload, never privileged state for a public # response. Reauthorize every refetch; no shared cross-principal cache. - {"payload" => payload, "sha256" => Digest::SHA256.hexdigest(JSON.generate(payload))} + {"payload" => payload, "sha256" => Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(payload))} end end end diff --git a/examples/shared_group_host.rb b/examples/shared_group_host.rb index eb4805e..a626b8e 100644 --- a/examples/shared_group_host.rb +++ b/examples/shared_group_host.rb @@ -101,22 +101,10 @@ def public_view @mutex.synchronize { public_units(@snapshot.states, @snapshot.clock) } end - private - - # A durable adapter needs a database transaction, group-wide lock/CAS, - # and atomic receipt/event outbox writes in place of this publication. - def publish(candidate) - @snapshot = candidate - end - - def synchronized_state(state, clock) - RBBB::State.from_h(state.to_h.merge("closes_at" => RBBB::Timestamp.dump(clock.closes_at))) - end - - def public_units(states, clock) - states.to_h do |id, state| - [id, synchronized_state(state, clock).public_view.transform_values { |v| v.freeze }.freeze] - end.freeze + def public_snapshot + @mutex.synchronize do + {"clock" => @snapshot.clock.public_view, "units" => public_units(@snapshot.states, @snapshot.clock)} + end end def normalize_close_request(command_id, effective_at, revision) @@ -143,5 +131,23 @@ def normalize_request(unit_id, command, revision) copied = values.to_h { |k, v| [k.dup.freeze, v.is_a?(String) ? v.dup.freeze : v] }.freeze {"unit_id" => unit_id.dup.freeze, "command" => copied, "expected_revision" => revision}.freeze end + + private + + # A durable adapter needs a database transaction, group-wide lock/CAS, + # and atomic receipt/event outbox writes in place of this publication. + def publish(candidate) + @snapshot = candidate + end + + def synchronized_state(state, clock) + RBBB::State.from_h(state.to_h.merge("closes_at" => RBBB::Timestamp.dump(clock.closes_at))) + end + + def public_units(states, clock) + states.to_h do |id, state| + [id, synchronized_state(state, clock).public_view.transform_values { |v| v.freeze }.freeze] + end.freeze + end end end diff --git a/examples/support/sqlite_store.rb b/examples/support/sqlite_store.rb new file mode 100644 index 0000000..65b30e6 --- /dev/null +++ b/examples/support/sqlite_store.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "sqlite3" + +module RBBBExamples + # Shared SQLite file-safety and serialized-transaction helpers for local + # reference adapters. The core engine gem has no SQLite dependency. + module SqliteStore + private + + def secure_file! + File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| } + rescue Errno::EEXIST + stat = File.lstat(@path) + unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero? + raise ArgumentError, "database must be an owner-only regular file" + end + end + + def transaction + db = SQLite3::Database.new(@path) + db.busy_timeout = 5000 + db.execute("PRAGMA synchronous = FULL") + db.execute("BEGIN IMMEDIATE") + result = yield db + db.execute("COMMIT") + result + rescue Exception + db.execute("ROLLBACK") if db&.transaction_active? + raise + ensure + db&.close + end + end +end diff --git a/ruby/engine/lib/rbbb/engine.rb b/ruby/engine/lib/rbbb/engine.rb index 9cfaa94..7928025 100644 --- a/ruby/engine/lib/rbbb/engine.rb +++ b/ruby/engine/lib/rbbb/engine.rb @@ -281,14 +281,14 @@ def decide_close_bidding(state, command) def build_bid_decision(state, command, bid_id, bidder_id, maximum, existing, effective_at) aggregate_version = next_aggregate_version(state) - authorization_history = state.authorization_history.map(&:dup) + authorization_history = state.authorization_history.dup authorization_history << { "type" => "place_bid", - "bid_id" => bid_id, - "bidder_id" => bidder_id, + "bid_id" => -bid_id, + "bidder_id" => -bidder_id, "maximum_minor_units" => maximum, "priority" => aggregate_version - } + }.freeze positions = state.positions.transform_values(&:to_h) positions[bidder_id] = { "maximum_minor_units" => maximum, @@ -361,13 +361,13 @@ def build_bid_decision(state, command, bid_id, bidder_id, maximum, existing, eff def build_reduction_decision(state, command, bidder_id, maximum, existing, effective_at) aggregate_version = next_aggregate_version(state) - authorization_history = state.authorization_history.map(&:dup) + authorization_history = state.authorization_history.dup authorization_history << { "type" => "maximum_reduced", - "bidder_id" => bidder_id, + "bidder_id" => -bidder_id, "maximum_minor_units" => maximum, "priority" => aggregate_version - } + }.freeze positions = state.positions.transform_values(&:to_h) positions[bidder_id] = { "maximum_minor_units" => maximum, @@ -421,12 +421,12 @@ def build_reduction_decision(state, command, bidder_id, maximum, existing, effec def build_reserve_change_decision(state, command, new_reserve, effective_at) aggregate_version = next_aggregate_version(state) - reserve_history = state.reserve_history.map(&:dup) + reserve_history = state.reserve_history.dup reserve_history << { "old_reserve_minor_units" => state.reserve_minor_units, "new_reserve_minor_units" => new_reserve, "priority" => aggregate_version - } + }.freeze leader = state.position_for(state.leader_id) reserve_status = reserve_status_for(leader&.to_h, new_reserve) transition = Event.new( diff --git a/ruby/engine/lib/rbbb/event.rb b/ruby/engine/lib/rbbb/event.rb index 74427b1..a290492 100644 --- a/ruby/engine/lib/rbbb/event.rb +++ b/ruby/engine/lib/rbbb/event.rb @@ -10,9 +10,10 @@ class Event def initialize(type:, visibility:, data: {}) raise ArgumentError, "unknown event visibility" unless VISIBILITIES.include?(visibility) - @type = type.to_s.freeze + @type = type.is_a?(String) ? -type : type.to_s.freeze @visibility = visibility - @data = deep_freeze(data.transform_keys(&:to_s)) + normalized = string_keyed_hash?(data) ? data : data.transform_keys(&:to_s) + @data = deep_freeze(normalized) freeze end @@ -39,12 +40,40 @@ def hash private + def string_keyed_hash?(value) + return false unless value.instance_of?(Hash) + + value.each_key { |key| return false unless key.is_a?(String) } + true + end + + def deeply_frozen?(value) + return false unless value.frozen? + + case value + when Hash + value.each_value { |nested| return false unless deeply_frozen?(nested) } + true + when Array + value.each { |nested| return false unless deeply_frozen?(nested) } + true + else + true + end + end + def deep_freeze(value) case value when Hash + return value if deeply_frozen?(value) + value.transform_values { |nested| deep_freeze(nested) }.freeze when Array + return value if deeply_frozen?(value) + value.map { |nested| deep_freeze(nested) }.freeze + when String + value.frozen? ? value : -value else value.freeze end diff --git a/ruby/engine/lib/rbbb/initial_closing_schedule.rb b/ruby/engine/lib/rbbb/initial_closing_schedule.rb index 62bfbcf..ee2f7f5 100644 --- a/ruby/engine/lib/rbbb/initial_closing_schedule.rb +++ b/ruby/engine/lib/rbbb/initial_closing_schedule.rb @@ -3,6 +3,8 @@ module RBBB # RFC 0002 initial planning only. Never applies a schedule to live state. module InitialClosingSchedule + ALLOWED_GROUP_KEYS = {"group_id" => true, "unit_ids" => true, "closes_at" => true}.freeze + module_function def plan(unit_ids:, opens_at:, first_closes_at:, lots_per_minute:, groups: []) @@ -19,20 +21,22 @@ def plan(unit_ids:, opens_at:, first_closes_at:, lots_per_minute:, groups: []) [id, timestamp(first + (index / lots_per_minute) * 60)] end resolved = original.dup - assigned = [] - group_ids = [] + assigned = {} + group_ids = {} planned_groups = groups.map do |group| - unless group.is_a?(Hash) && (group.keys - %w[group_id unit_ids closes_at]).empty? + unless group.is_a?(Hash) && group.each_key.all? { |key| ALLOWED_GROUP_KEYS.key?(key) } raise InvalidConfiguration, "invalid group shape" end id = identity(group["group_id"]) - raise InvalidConfiguration, "duplicate group identity" if group_ids.include?(id) - group_ids << id + raise InvalidConfiguration, "duplicate group identity" if group_ids.key?(id) + group_ids[id] = true members = identities(group["unit_ids"]).sort - unless (members - units).empty? && (members & assigned).empty? - raise InvalidConfiguration, "unknown or overlapping group member" + members.each do |member| + if !original.key?(member) || assigned.key?(member) + raise InvalidConfiguration, "unknown or overlapping group member" + end + assigned[member] = true end - assigned.concat(members) close = group.key?("closes_at") ? timestamp(group["closes_at"]) : members.map { |member| original.fetch(member) }.max raise InvalidConfiguration, "group closing must follow opening" unless close > opening members.each { |member| resolved[member] = close } @@ -52,9 +56,13 @@ def identity(value) def identities(values) raise InvalidConfiguration, "identities must be a nonempty array" unless values.is_a?(Array) && !values.empty? - result = values.map { |value| identity(value) } - raise InvalidConfiguration, "duplicate identity" unless result.uniq.size == result.size - result + seen = {} + values.map do |value| + id = identity(value) + raise InvalidConfiguration, "duplicate identity" if seen.key?(id) + seen[id] = true + id + end end private_class_method :identities diff --git a/ruby/engine/lib/rbbb/live_scheduling.rb b/ruby/engine/lib/rbbb/live_scheduling.rb index 49d99f0..201e220 100644 --- a/ruby/engine/lib/rbbb/live_scheduling.rb +++ b/ruby/engine/lib/rbbb/live_scheduling.rb @@ -21,7 +21,20 @@ def self.encoded_batch_size(records, commit_id) end def self.copy(value) - JSON.parse(JSON.generate(value)) + case value + when Hash + result = {} + value.each { |k, v| result[k.is_a?(String) ? k : k.to_s] = copy(v) } + result + when Array + value.map { |item| copy(item) } + when String + value.dup + when Symbol + value.to_s + else + value + end end def self.time(value) diff --git a/ruby/engine/lib/rbbb/live_scheduling/coordinator.rb b/ruby/engine/lib/rbbb/live_scheduling/coordinator.rb index 4ea67eb..5dd66e1 100644 --- a/ruby/engine/lib/rbbb/live_scheduling/coordinator.rb +++ b/ruby/engine/lib/rbbb/live_scheduling/coordinator.rb @@ -25,10 +25,17 @@ def initialize(auction_id:, configurations:, snapshot:, policy:, profile: PROFIL @snapshot = LiveScheduling.copy(snapshot) @original_closing_sets = LiveScheduling.copy(snapshot.fetch("closing_sets")) @retired_group_ids = retired_group_ids.dup + @retired_group_set = @retired_group_ids.to_h { |id| [id, true] } configurations.each_value { |config| Configuration.from_h(config) } snapshot.fetch("units").each_value { |unit| State.from_h(unit) } @snapshot["closing_sets"] = LiveScheduling.sort_sets(snapshot.fetch("closing_sets").map { |set| Intent.normalize_set(set) }) validate_snapshot! + @unit_to_set = {} + @group_to_set = {} + @snapshot["closing_sets"].each do |set| + @group_to_set[set["group_id"]] = set if set["group_id"] + set["member_unit_ids"].each { |id| @unit_to_set[id] = set } + end end def register_unit(intent:, principal_id:, permissions:, effective_at:, commit_id:) @@ -49,7 +56,8 @@ def register_unit(intent:, principal_id:, permissions:, effective_at:, commit_id empty = State.empty(Configuration.from_h(config)).to_h state["units"][id] = empty state["schedule_revision"] += 1 - set = {"group_id" => nil, "member_unit_ids" => [id], "closes_at" => config["closes_at"], "extension" => config["extension"]} + set_extension = config["extension"]&.slice("trigger_window_seconds", "duration_seconds") + set = {"group_id" => nil, "member_unit_ids" => [id], "closes_at" => config["closes_at"], "extension" => set_extension} state["closing_sets"] = LiveScheduling.sort_sets(state["closing_sets"] + [set]) creation = {"capability" => CAPABILITY, "type" => "bidding_unit_registered", "visibility" => "privileged", "command_id" => intent["command_id"], "commit_id" => commit_id, "auction_id" => auction_id, @@ -72,7 +80,7 @@ def edit(intent:, principal_id:, permissions:, effective_at:, commit_id:) versions = intent["expected_units"].to_h { |unit| unit.values_at("unit_id", "version") } return reject("stale_revision") if versions.any? { |id, version| snapshot["units"].key?(id) && snapshot["units"][id]["version"] != version } return reject("duplicate_membership") unless requested.uniq.size == requested.size - return reject("conflicting_group_definition") if sets.any? { |set| set["group_id"] && @retired_group_ids.include?(set["group_id"]) } + return reject("conflicting_group_definition") if sets.any? { |set| set["group_id"] && @retired_group_set.key?(set["group_id"]) } return reject("incomplete_affected_set") unless requested.sort == affected.sort && versions.keys.sort == affected.sort && affected.all? { |id| snapshot["units"].key?(id) } previous = affected_sets(affected) old_groups = previous.map { |set| set["group_id"] }.compact @@ -95,13 +103,18 @@ def edit(intent:, principal_id:, permissions:, effective_at:, commit_id:) return reject("version_exhausted") if exhausted?(affected) state = LiveScheduling.copy(snapshot) - affected.each do |id| - set = sets.find { |item| item["member_unit_ids"].include?(id) } - state["units"][id].merge!("version" => state["units"][id]["version"] + 1, - "closes_at" => LiveScheduling.dump_time(set["closes_at"]), "last_effective_at" => LiveScheduling.dump_time(at)) + dumped_at = LiveScheduling.dump_time(at) + sets.each do |set| + dumped_close = LiveScheduling.dump_time(set["closes_at"]) + set["member_unit_ids"].each do |id| + state["units"][id].merge!("version" => state["units"][id]["version"] + 1, + "closes_at" => dumped_close, "last_effective_at" => dumped_at) + end end state["schedule_revision"] += 1 - state["closing_sets"] = LiveScheduling.sort_sets(snapshot["closing_sets"] - previous + sets) + previous_set_ids = previous.to_h { |set| [set.object_id, true] } + remaining = snapshot["closing_sets"].reject { |set| previous_set_ids.key?(set.object_id) } + state["closing_sets"] = LiveScheduling.sort_sets(remaining + sets) public_record = change_record(intent["command_id"], commit_id, at, state, affected, sets, intent["retired_group_ids"]) audit = public_record.merge("type" => "closing_configuration_committed", "visibility" => "privileged", "operator_id" => principal_id, "reason" => intent["reason"], "allow_shortening" => intent["allow_shortening"], @@ -119,7 +132,7 @@ def edit(intent:, principal_id:, permissions:, effective_at:, commit_id:) def bid(unit_id:, command:, effective_at:, commit_id:) return reject("invalid_request") unless %w[place_bid reduce_maximum].include?(command["type"]) return reject("invalid_request") unless snapshot["units"].key?(unit_id) - set = snapshot["closing_sets"].find { |item| item["member_unit_ids"].include?(unit_id) } + set = @unit_to_set.fetch(unit_id) engine = unit_engine(unit_id, set, extension: nil) before = State.from_h(snapshot["units"].fetch(unit_id)) command = command.merge("effective_at" => LiveScheduling.dump_time(effective_at)) @@ -131,11 +144,17 @@ def bid(unit_id:, command:, effective_at:, commit_id:) qualifying = standing && !own_adjustment at = LiveScheduling.time(effective_at) return reject("effective_at_out_of_order") if set["member_unit_ids"].any? { |id| snapshot['units'][id]['last_effective_at'] && LiveScheduling.time(snapshot['units'][id]['last_effective_at']) > at } - closing = LiveScheduling.time(set["closes_at"]) - if qualifying && set["extension"] && at >= closing - set["extension"]["trigger_window_seconds"] - closing = [closing, at + set["extension"]["duration_seconds"]].max + original_closing = LiveScheduling.time(set["closes_at"]) + closing = original_closing + if qualifying && set["extension"] && at >= original_closing - set["extension"]["trigger_window_seconds"] + begin + candidate = [original_closing, at + set["extension"]["duration_seconds"]].max + closing = Timestamp.parse(candidate) + rescue ArgumentError, RangeError + return reject("invalid_closing_time") + end end - extended = closing > LiveScheduling.time(set["closes_at"]) + extended = closing > original_closing affected = extended ? set["member_unit_ids"] : [unit_id] return reject("resource_limit_exceeded") if affected.size > profile.fetch('affected_units') return reject("version_exhausted") if affected.any? { |id| snapshot["units"][id]["version"] >= MAX_SAFE_INTEGER } || (extended && snapshot["schedule_revision"] >= MAX_SAFE_INTEGER) @@ -144,17 +163,20 @@ def bid(unit_id:, command:, effective_at:, commit_id:) events = decision.events.map(&:to_h) records = [] if extended + dumped_closing = LiveScheduling.dump_time(closing) + dumped_at = LiveScheduling.dump_time(at) state["schedule_revision"] += 1 - new_set = set.merge("closes_at" => LiveScheduling.dump_time(closing)) - state["closing_sets"] = LiveScheduling.sort_sets(snapshot["closing_sets"] - [set] + [new_set]) + new_set = set.merge("closes_at" => dumped_closing) + remaining = snapshot["closing_sets"].reject { |item| item.equal?(set) } + state["closing_sets"] = LiveScheduling.sort_sets(remaining + [new_set]) affected.each do |id| unit = state["units"][id] unit["version"] += 1 unless id == unit_id - unit.merge!("closes_at" => LiveScheduling.dump_time(closing), "last_effective_at" => LiveScheduling.dump_time(at)) + unit.merge!("closes_at" => dumped_closing, "last_effective_at" => dumped_at) end - events.each { |event| event["closes_at"] = LiveScheduling.dump_time(closing) if event.key?("closes_at") } + events.each { |event| event["closes_at"] = dumped_closing if event.key?("closes_at") } events << {"type" => "closing_time_changed", "command_id" => command["command_id"], - "aggregate_version" => after.version, "closes_at" => LiveScheduling.dump_time(closing)} + "aggregate_version" => after.version, "closes_at" => dumped_closing} records << change_record(command["command_id"], commit_id, at, state, affected, [new_set], []) end result(state, events.map { |event| {"unit_id" => unit_id, "event" => event} } + records, commit_id: commit_id) @@ -174,7 +196,7 @@ def change_reserve(unit_id:, command:, effective_at:, commit_id:) def operator_unit_change(unit_id:, command:, effective_at:, commit_id:) return reject("invalid_request") unless snapshot["units"].key?(unit_id) - set = snapshot["closing_sets"].find { |item| item["member_unit_ids"].include?(unit_id) } + set = @unit_to_set.fetch(unit_id) at = LiveScheduling.time(effective_at) return reject("effective_at_out_of_order") if set["member_unit_ids"].any? { |id| snapshot["units"][id]["last_effective_at"] && LiveScheduling.time(snapshot["units"][id]["last_effective_at"]) > at } return reject("version_exhausted") if snapshot["units"][unit_id]["version"] >= MAX_SAFE_INTEGER @@ -194,8 +216,15 @@ def operator_unit_change(unit_id:, command:, effective_at:, commit_id:) def close(group_id: nil, unit_id: nil, command:, effective_at:, commit_id:) return reject("invalid_request") unless command["type"] == "close_bidding" && (!!group_id != !!unit_id) - set = snapshot["closing_sets"].find { |item| group_id ? item["group_id"] == group_id : item["group_id"].nil? && item["member_unit_ids"] == [unit_id] } + set = if group_id + @group_to_set[group_id] + else + candidate = @unit_to_set[unit_id] + candidate if candidate && candidate["group_id"].nil? + end return reject("invalid_request") unless set + at = LiveScheduling.time(effective_at) + dumped_at = LiveScheduling.dump_time(at) ids = set["member_unit_ids"].sort return reject("resource_limit_exceeded") if ids.size > profile["affected_units"] return reject("version_exhausted") if exhausted?(ids) @@ -204,14 +233,16 @@ def close(group_id: nil, unit_id: nil, command:, effective_at:, commit_id:) ids.each do |id| engine = unit_engine(id, set, extension: set["extension"]) before = State.from_h(snapshot["units"][id]) - decision = engine.decide(before, command.merge("effective_at" => LiveScheduling.dump_time(effective_at))) + decision = engine.decide(before, command.merge("effective_at" => dumped_at)) return reject(decision.rejection.fetch("reason")) if decision.rejected? state["units"][id] = engine.apply(before, decision.events).to_h records.concat(decision.events.map { |event| {"unit_id" => id, "event" => event.to_h} }) end state["schedule_revision"] += 1 - records << change_record(command["command_id"], commit_id, effective_at, state, ids, [set], []) + records << change_record(command["command_id"], commit_id, at, state, ids, [set], []) result(state, records, commit_id: commit_id) + rescue ArgumentError, RangeError + reject("invalid_request") end private @@ -221,24 +252,34 @@ def validate_snapshot! members = snapshot["closing_sets"].flat_map { |set| set["member_unit_ids"] } raise InvalidState, "invalid partition" unless members.sort == snapshot["units"].keys.sort && members.uniq.size == members.size && configurations.keys.sort == members.sort snapshot["closing_sets"].each do |set| + set_close = LiveScheduling.time(set["closes_at"]) set["member_unit_ids"].each do |id| - raise InvalidState, "deadline mismatch" unless LiveScheduling.time(snapshot["units"][id]["closes_at"]) == LiveScheduling.time(set["closes_at"]) + raise InvalidState, "deadline mismatch" unless LiveScheduling.time(snapshot["units"][id]["closes_at"]) == set_close end end end def discover(ids, group_ids) - found = ids.dup - loop do - more = snapshot["closing_sets"].select { |set| (set["member_unit_ids"] & found).any? || group_ids.include?(set["group_id"]) }.flat_map { |set| set["member_unit_ids"] } - union = (found + more).uniq - return union.sort if union.size == found.uniq.size - found = union + found = {} + ids.each do |id| + found[id] = true + set = @unit_to_set[id] + set["member_unit_ids"].each { |member| found[member] = true } if set end + group_ids.each do |group_id| + set = @group_to_set[group_id] + set["member_unit_ids"].each { |member| found[member] = true } if set + end + found.keys.sort end def affected_sets(ids) - snapshot["closing_sets"].select { |set| (set["member_unit_ids"] & ids).any? } + seen = {} + ids.each do |id| + set = @unit_to_set[id] + seen[set.object_id] = set if set + end + LiveScheduling.sort_sets(seen.values) end def membership(sets) @@ -272,11 +313,19 @@ def change_record(command_id, commit_id, at, state, ids, sets, retired) def change_kinds(previous, sets) kinds = [] kinds << "membership" unless membership(previous) == membership(sets) + old_by_unit = {} + old_times = {} + previous.each do |item| + old_times[item.object_id] = LiveScheduling.time(item["closes_at"]) + item["member_unit_ids"].each { |id| old_by_unit[id] = item } + end sets.each do |set| + new_time = LiveScheduling.time(set["closes_at"]) set["member_unit_ids"].each do |id| - old = previous.find { |item| item["member_unit_ids"].include?(id) } - kinds << "extended" if LiveScheduling.time(set["closes_at"]) > LiveScheduling.time(old["closes_at"]) - kinds << "shortened" if LiveScheduling.time(set["closes_at"]) < LiveScheduling.time(old["closes_at"]) + old = old_by_unit.fetch(id) + old_time = old_times.fetch(old.object_id) + kinds << "extended" if new_time > old_time + kinds << "shortened" if new_time < old_time kinds << "policy" unless set["extension"] == old["extension"] end end @@ -291,11 +340,18 @@ def result(state, records, retired = @retired_group_ids, commit_id:) return reject("resource_limit_exceeded") if LiveScheduling.encoded_batch_size(records, commit_id) > profile["batch_bytes"] # Only the scheduling delta's affected sets change in whole-commit # replay. Preserve all other sets exactly, including timestamp spelling. - changed_ids = records.select { |record| record["type"] == "closing_configuration_changed" } - .flat_map { |record| record.fetch("unit_versions").map { |unit| unit.fetch("unit_id") } } - untouched = @original_closing_sets.select { |set| (set["member_unit_ids"] & changed_ids).empty? } - affected = state["closing_sets"].reject { |set| (set["member_unit_ids"] & changed_ids).empty? } - state["closing_sets"] = LiveScheduling.sort_sets(LiveScheduling.copy(untouched) + wire_sets(affected)) + changed_set = {} + records.each do |record| + next unless record["type"] == "closing_configuration_changed" + record.fetch("unit_versions").each { |unit| changed_set[unit.fetch("unit_id")] = true } + end + if changed_set.empty? + state["closing_sets"] = LiveScheduling.sort_sets(LiveScheduling.copy(@original_closing_sets)) + else + untouched = @original_closing_sets.reject { |set| set["member_unit_ids"].any? { |id| changed_set.key?(id) } } + affected = state["closing_sets"].select { |set| set["member_unit_ids"].any? { |id| changed_set.key?(id) } } + state["closing_sets"] = LiveScheduling.sort_sets(LiveScheduling.copy(untouched) + wire_sets(affected)) + end Result.new(state: state, records: records, rejection_reason: nil, retired_group_ids: retired.uniq.sort) end end diff --git a/ruby/engine/lib/rbbb/live_scheduling/intent.rb b/ruby/engine/lib/rbbb/live_scheduling/intent.rb index 5e9de2a..c9c36f5 100644 --- a/ruby/engine/lib/rbbb/live_scheduling/intent.rb +++ b/ruby/engine/lib/rbbb/live_scheduling/intent.rb @@ -43,7 +43,7 @@ def normalize_registration(value) config = value["configuration"] object(config, %w[currency opening_minor_units reserve_minor_units increments opens_at closes_at extension]) array(config["increments"], minimum: 1).each { |tier| object(tier, %w[from_minor_units amount_minor_units]) } - object(config["extension"], %w[trigger_window_seconds duration_seconds]) unless config["extension"].nil? + validate_registration_extension(config["extension"]) unless config["extension"].nil? Configuration.from_h(config) canonical(value) # Reject invalid text and unsupported/unsafe JSON values. normalized = LiveScheduling.copy(value) @@ -83,6 +83,9 @@ def normalize_set(set) raise Invalid, "ungrouped set needs one unit" if set["group_id"].nil? && ids.size != 1 extension = set["extension"] unless extension.nil? + if extension.is_a?(Hash) && extension["extend_on_void"] == true + raise Invalid, "extend_on_void is not supported for linked live scheduling" + end object(extension, %w[trigger_window_seconds duration_seconds]) revision(extension["trigger_window_seconds"]) revision(extension["duration_seconds"]) @@ -92,6 +95,22 @@ def normalize_set(set) set.merge("member_unit_ids" => ids.sort, "closes_at" => at.utc.iso8601(3)) end + def validate_registration_extension(extension) + raise Invalid, "invalid object properties" unless extension.is_a?(Hash) + keys = extension.keys.sort + unless keys == %w[duration_seconds trigger_window_seconds] || + keys == %w[duration_seconds extend_on_void trigger_window_seconds] + raise Invalid, "invalid object properties" + end + if extension.key?("extend_on_void") + if extension["extend_on_void"] == true + raise Invalid, "extend_on_void is not supported for linked live scheduling" + end + raise Invalid, "invalid extend_on_void" unless extension["extend_on_void"] == false + end + end + private_class_method :validate_registration_extension + def fingerprint(principal, intent) identifier(principal) Digest::SHA256.hexdigest(canonical({"principal_id" => principal, "intent" => intent})) diff --git a/ruby/engine/lib/rbbb/live_scheduling/projector.rb b/ruby/engine/lib/rbbb/live_scheduling/projector.rb index 2a1d2ed..4075d2b 100644 --- a/ruby/engine/lib/rbbb/live_scheduling/projector.rb +++ b/ruby/engine/lib/rbbb/live_scheduling/projector.rb @@ -5,6 +5,13 @@ module LiveScheduling # Privileged whole-commit replay. A public consumer instead refetches a # consistent snapshot; it cannot synthesize private baseline bid history. module Projector + PUBLIC_UNIT_EVENTS = %w[ + standing_bid_changed + reserve_status_changed + closing_time_changed + bidding_closed + ].freeze + module_function # Returns both detached registries. Callers must install them atomically. @@ -60,6 +67,14 @@ def apply(snapshot:, configurations:, records:) raise InvalidState, "audit delta conflict" unless %w[schedule_revision unit_versions resulting_closing_sets retired_group_ids].all? { |key| audit[key] == change[key] } end end + unit_to_set = {} + state.fetch("closing_sets").each do |set| + set.fetch("member_unit_ids").each { |member| unit_to_set[member] = set } + end + baseline_units = {} + baseline.each { |record| baseline_units[record.fetch("unit_id")] = true } + extended_bid = false + baseline.group_by { |record| record.fetch("unit_id") }.sort.each do |id, entries| transitions = entries.select { |entry| entry.fetch("event").key?("positions") && Engine::STATE_TRANSITION_EVENTS.include?(entry["event"]["type"]) } raise InvalidState, "missing or reordered unit transition" unless transitions.size == 1 && entries.first == transitions.first @@ -68,12 +83,15 @@ def apply(snapshot:, configurations:, records:) if changes.any? raise InvalidState, "command identity conflict" unless identities.first.first == changes.first.fetch("command_id") end + closing_set = unit_to_set[id] + raise InvalidState, "missing closing set" unless closing_set before = State.from_h(state.fetch("units").fetch(id)) - engine = Engine.new(Configuration.from_h(configurations.fetch(id).merge("closes_at" => before.to_h["closes_at"], "extension" => nil))) - validate_unit_records!(engine, before, entries.map { |entry| entry.fetch("event") }, changes.first) + engine = Engine.new(Configuration.from_h(configurations.fetch(id).merge("closes_at" => Timestamp.dump(before.closes_at), "extension" => nil))) + extended = validate_unit_records!(engine, before, id, closing_set, entries.map { |entry| entry.fetch("event") }, changes.first) + extended_bid ||= extended events = entries.map do |entry| data = entry.fetch("event") - Event.new(type: data.fetch("type"), visibility: data.key?("positions") ? :privileged : :public, + Event.new(type: data.fetch("type"), visibility: event_visibility(data), data: data.reject { |key, _| key == "type" }) end state["units"][id] = engine.apply(before, events).to_h @@ -95,35 +113,60 @@ def apply(snapshot:, configurations:, records:) closing = baseline.select { |record| record.dig("event", "type") == "bidding_closed" } if closing.any? raise InvalidState, "partial group close" unless closing == baseline && closing.map { |record| record["unit_id"] }.uniq.sort == ids.sort + elsif !baseline.empty? && !extended_bid + raise InvalidState, "unexpected scheduling delta" end sets = change.fetch("resulting_closing_sets") members = sets.flat_map { |set| set.fetch("member_unit_ids") } raise InvalidState, "incomplete scheduling delta" unless members.sort == ids.sort - previous = state["closing_sets"].select { |set| (set["member_unit_ids"] & ids).any? } + seen_previous = {} + ids.each do |id| + set = unit_to_set[id] + seen_previous[set.object_id] = set if set + end + previous = seen_previous.values raise InvalidState, "partial closing set" unless previous.flat_map { |set| set["member_unit_ids"] }.sort == ids.sort retired = change.fetch("retired_group_ids") raise InvalidState, "incorrect retired groups" unless (previous.map { |set| set["group_id"] }.compact - sets.map { |set| set["group_id"] }.compact).sort == retired.sort + new_unit_to_set = {} + sets.each do |set| + set.fetch("member_unit_ids").each { |member| new_unit_to_set[member] = set } + end versions.each do |entry| id, version = entry.values_at("unit_id", "version") raise InvalidState, "unit version gap" unless version == snapshot["units"].fetch(id).fetch("version") + 1 unit = state["units"].fetch(id) - native = baseline.any? { |record| record["unit_id"] == id } + native = baseline_units.key?(id) raise InvalidState, "baseline version conflict" if native && unit["version"] != version - set = sets.find { |item| item["member_unit_ids"].include?(id) } + set = new_unit_to_set.fetch(id) + if native && LiveScheduling.time(unit.fetch("closes_at")) != LiveScheduling.time(set.fetch("closes_at")) + raise InvalidState, "conflicting closing deadline" + end unit.merge!("version" => version, "closes_at" => set.fetch("closes_at"), "last_effective_at" => change.fetch("effective_at")) State.from_h(unit) end - state["closing_sets"] = LiveScheduling.sort_sets(state["closing_sets"] - previous + sets) + previous_set_ids = seen_previous + remaining = state["closing_sets"].reject { |set| previous_set_ids.key?(set.object_id) } + state["closing_sets"] = LiveScheduling.sort_sets(remaining + sets) state["schedule_revision"] = change["schedule_revision"] state rescue KeyError, TypeError, ArgumentError => e raise InvalidState, "incoherent scheduling commit: #{e.message}" end + def event_visibility(data) + if data.key?("positions") || !PUBLIC_UNIT_EVENTS.include?(data.fetch("type")) + :privileged + else + :public + end + end + private_class_method :event_visibility + # Derive the complete native event batch from its privileged transition. # Engine.apply alone restores that transition even when public/audit # companions are missing. Whole-commit replay must refuse that damage. - def validate_unit_records!(engine, before, records, change) + def validate_unit_records!(engine, before, unit_id, closing_set, records, change) transition = records.first command = transition.slice("command_id", "effective_at", "bidder_id", "bid_id", "operator_id", "reason", "notification_policy") command["type"] = case transition.fetch("type") @@ -143,13 +186,40 @@ def validate_unit_records!(engine, before, records, change) decision = engine.decide(before, command) raise InvalidState, "invalid unit transition" if decision.rejected? expected = decision.events.map(&:to_h) - if %w[maximum_accepted maximum_increased].include?(transition["type"]) && - LiveScheduling.time(transition.fetch("closes_at")) > before.closes_at - raise InvalidState, "missing linked extension" unless change && change["effective_at"] == transition["effective_at"] - expected.each { |event| event["closes_at"] = transition["closes_at"] if event.key?("closes_at") } - expected << transition.slice("command_id", "aggregate_version", "closes_at").merge("type" => "closing_time_changed") + extended = false + if %w[maximum_accepted maximum_increased maximum_reduced].include?(transition["type"]) + transition_closes_at = LiveScheduling.time(transition.fetch("closes_at")) + at = LiveScheduling.time(transition.fetch("effective_at")) + standing = decision.events.find { |event| event.public? && event.type == "standing_bid_changed" } + after = engine.apply(before, decision.events) + own_adjustment = before.leader_id == command["bidder_id"] && + before.position_for(command["bidder_id"]) && after.leader_id == before.leader_id + qualifying = !standing.nil? && !own_adjustment + extension = closing_set["extension"] + expected_closes_at = if qualifying && extension && + at >= before.closes_at - extension.fetch("trigger_window_seconds") + [before.closes_at, at + extension.fetch("duration_seconds")].max + else + before.closes_at + end + if transition_closes_at > before.closes_at + unless expected_closes_at > before.closes_at && transition_closes_at == expected_closes_at + raise InvalidState, "invalid linked extension" + end + raise InvalidState, "missing linked extension" unless change && change["effective_at"] == transition["effective_at"] + resulting_set = change.fetch("resulting_closing_sets").find { |set| set.fetch("member_unit_ids").include?(unit_id) } + unless resulting_set && LiveScheduling.time(resulting_set.fetch("closes_at")) == expected_closes_at + raise InvalidState, "conflicting linked extension" + end + expected.each { |event| event["closes_at"] = transition["closes_at"] if event.key?("closes_at") } + expected << transition.slice("command_id", "aggregate_version", "closes_at").merge("type" => "closing_time_changed") + extended = true + elsif expected_closes_at > before.closes_at + raise InvalidState, "missing linked extension" + end end raise InvalidState, "incomplete or conflicting unit records" unless records == expected + extended end private_class_method :validate_unit_records! end diff --git a/ruby/engine/lib/rbbb/state.rb b/ruby/engine/lib/rbbb/state.rb index 40091ec..2d6886e 100644 --- a/ruby/engine/lib/rbbb/state.rb +++ b/ruby/engine/lib/rbbb/state.rb @@ -52,6 +52,8 @@ def to_h authorization_history reserve_history voided_bid_ids ].freeze + EMPTY_ARRAY = [].freeze + def self.empty(configuration) new( version: 0, @@ -76,9 +78,11 @@ def self.empty(configuration) def self.from_h(snapshot, bid_ladder: nil) raise InvalidState, "snapshot must be an object" unless snapshot.respond_to?(:transform_keys) - values = snapshot.transform_keys(&:to_s) - missing = SNAPSHOT_KEYS.reject { |key| values.key?(key) } - raise InvalidState, "snapshot is missing #{missing.join(', ')}" if missing.any? + values = string_keyed_hash?(snapshot) ? snapshot : snapshot.transform_keys(&:to_s) + unless SNAPSHOT_KEYS.all? { |key| values.key?(key) } + missing = SNAPSHOT_KEYS.reject { |key| values.key?(key) } + raise InvalidState, "snapshot is missing #{missing.join(', ')}" + end new( version: values.fetch("version"), @@ -113,9 +117,11 @@ def self.from_transition(configuration, event_or_data) data = event_or_data.respond_to?(:data) ? event_or_data.data : event_or_data raise InvalidState, "transition data must be an object" unless data.respond_to?(:transform_keys) - values = data.transform_keys(&:to_s) - missing = TRANSITION_KEYS.reject { |key| values.key?(key) } - raise InvalidState, "transition is missing #{missing.join(', ')}" if missing.any? + values = string_keyed_hash?(data) ? data : data.transform_keys(&:to_s) + unless TRANSITION_KEYS.all? { |key| values.key?(key) } + missing = TRANSITION_KEYS.reject { |key| values.key?(key) } + raise InvalidState, "transition is missing #{missing.join(', ')}" + end from_h( { @@ -141,6 +147,14 @@ def self.from_transition(configuration, event_or_data) ) end + def self.string_keyed_hash?(value) + return false unless value.instance_of?(Hash) + + value.each_key { |key| return false unless key.is_a?(String) } + true + end + private_class_method :string_keyed_hash? + def initialize(version:, positions:, leader_id:, standing_minor_units:, next_required_minor_units:, reserve_status: nil, opens_at: nil, closes_at: nil, last_effective_at: nil, reserve_minor_units: nil, @@ -149,26 +163,34 @@ def initialize(version:, positions:, leader_id:, standing_minor_units:, winning_minor_units: nil, bid_ladder: nil) @version = version @positions = positions.each_with_object({}) do |(bidder_id, position), copy| - copy[bidder_id.to_s.freeze] = coerce_position(position) + copy[freeze_string(bidder_id)] = coerce_position(position) end.freeze - @leader_id = leader_id&.to_s&.freeze + @leader_id = leader_id.nil? ? nil : freeze_string(leader_id) @standing_minor_units = standing_minor_units @next_required_minor_units = next_required_minor_units - @reserve_status = reserve_status&.to_s&.freeze + @reserve_status = reserve_status.nil? ? nil : freeze_string(reserve_status) @reserve_minor_units = reserve_minor_units @opens_at = coerce_timestamp(opens_at, "opens_at") @closes_at = coerce_timestamp(closes_at, "closes_at") @last_effective_at = coerce_timestamp(last_effective_at, "last_effective_at") - @authorization_history = authorization_history.map do |entry| - coerce_authorization(entry) - end.freeze - @reserve_history = reserve_history.map do |entry| - coerce_reserve_change(entry) - end.freeze - @voided_bid_ids = voided_bid_ids.map { |bid_id| bid_id.to_s.freeze }.freeze - @status = status.to_s.freeze - @result = result&.to_s&.freeze - @winner_id = winner_id&.to_s&.freeze + @authorization_history = if authorization_history.empty? + EMPTY_ARRAY + else + authorization_history.map { |entry| coerce_authorization(entry) }.freeze + end + @reserve_history = if reserve_history.empty? + EMPTY_ARRAY + else + reserve_history.map { |entry| coerce_reserve_change(entry) }.freeze + end + @voided_bid_ids = if voided_bid_ids.empty? + EMPTY_ARRAY + else + voided_bid_ids.map { |bid_id| freeze_string(bid_id) }.freeze + end + @status = freeze_string(status) + @result = result.nil? ? nil : freeze_string(result) + @winner_id = winner_id.nil? ? nil : freeze_string(winner_id) @winning_minor_units = winning_minor_units validate!(bid_ladder: bid_ladder) freeze @@ -260,7 +282,13 @@ def coerce_timestamp(value, field) def coerce_position(position) return position if position.is_a?(Position) && position.frozen? - values = position.respond_to?(:to_h) ? position.to_h.transform_keys(&:to_s) : {} + values = if self.class.send(:string_keyed_hash?, position) + position + elsif position.respond_to?(:to_h) + position.to_h.transform_keys(&:to_s) + else + {} + end Position.new( maximum_minor_units: values.fetch("maximum_minor_units"), executable_maximum_minor_units: values.fetch("executable_maximum_minor_units"), @@ -272,15 +300,36 @@ def coerce_position(position) end def coerce_authorization(entry) - values = entry.respond_to?(:to_h) ? entry.to_h.transform_keys(&:to_s) : {} + if entry.instance_of?(Hash) && entry.frozen? + type = entry["type"] + bidder_id = entry["bidder_id"] + if type.is_a?(String) && type.frozen? && bidder_id.is_a?(String) && bidder_id.frozen? && + entry.key?("maximum_minor_units") && entry.key?("priority") + if type == "place_bid" && entry.size == 5 && + (bid_id = entry["bid_id"]).is_a?(String) && bid_id.frozen? + return entry + elsif type == "maximum_reduced" && entry.size == 4 + return entry + end + end + end + + values = if self.class.send(:string_keyed_hash?, entry) + entry + elsif entry.respond_to?(:to_h) + entry.to_h.transform_keys(&:to_s) + else + {} + end + type = freeze_string(values.fetch("type")) normalized = { - "type" => values.fetch("type").to_s.freeze, - "bidder_id" => values.fetch("bidder_id").to_s.freeze, + "type" => type, + "bidder_id" => freeze_string(values.fetch("bidder_id")), "maximum_minor_units" => values.fetch("maximum_minor_units"), "priority" => values.fetch("priority") } - if normalized.fetch("type") == "place_bid" - normalized["bid_id"] = values.fetch("bid_id").to_s.freeze + if type == "place_bid" + normalized["bid_id"] = freeze_string(values.fetch("bid_id")) end normalized.freeze rescue KeyError => e @@ -288,7 +337,20 @@ def coerce_authorization(entry) end def coerce_reserve_change(entry) - values = entry.respond_to?(:to_h) ? entry.to_h.transform_keys(&:to_s) : {} + if entry.instance_of?(Hash) && entry.frozen? && entry.size == 3 && + entry.key?("old_reserve_minor_units") && + entry.key?("new_reserve_minor_units") && + entry.key?("priority") + return entry + end + + values = if self.class.send(:string_keyed_hash?, entry) + entry + elsif entry.respond_to?(:to_h) + entry.to_h.transform_keys(&:to_s) + else + {} + end { "old_reserve_minor_units" => values.fetch("old_reserve_minor_units"), "new_reserve_minor_units" => values.fetch("new_reserve_minor_units"), @@ -298,6 +360,10 @@ def coerce_reserve_change(entry) raise InvalidState, "reserve change is missing #{e.key}" end + def freeze_string(value) + value.is_a?(String) ? -value : value.to_s.freeze + end + def validate!(bid_ladder: nil) unless version.is_a?(Integer) && version.between?(0, MAX_SAFE_INTEGER) raise InvalidState, "version must be a non-negative integer no greater than #{MAX_SAFE_INTEGER}" @@ -305,7 +371,7 @@ def validate!(bid_ladder: nil) unless Money.amount?(next_required_minor_units) raise InvalidState, "next required amount must be a non-negative integer no greater than #{Money::MAX_MINOR_UNITS}" end - unless [nil, "reserve_not_met", "reserve_met"].include?(reserve_status) + unless reserve_status.nil? || reserve_status == "reserve_not_met" || reserve_status == "reserve_met" raise InvalidState, "reserve status is invalid" end unless valid_optional_minor_units?(reserve_minor_units) @@ -319,8 +385,8 @@ def validate!(bid_ladder: nil) if opens_at >= closes_at raise InvalidState, "opens_at must be earlier than closes_at" end - validate_authorization_history! - validate_reserve_history! + auth_priorities = validate_authorization_history! + validate_reserve_history!(auth_priorities) validate_lifecycle! if leader_id && !positions.key?(leader_id) raise InvalidState, "leader must have a position" @@ -366,24 +432,33 @@ def validate!(bid_ladder: nil) raise InvalidState, "next required amount must exceed standing amount" end - ranked_leader = positions.min_by do |bidder_id, position| - [-position.executable_maximum_minor_units, position.priority, bidder_id] - end.first + ranked_leader = if positions.size == 1 + positions.each_key.first + else + positions.min_by do |bidder_id, position| + [-position.executable_maximum_minor_units, position.priority, bidder_id] + end.first + end raise InvalidState, "leader does not match maximum priority" unless ranked_leader == leader_id end def validate_authorization_history! - priorities = authorization_history.map { |entry| entry.fetch("priority") } - unless priorities.all? { |priority| priority.is_a?(Integer) } - raise InvalidState, "authorization priority must belong to the event stream" - end - unless priorities == priorities.sort && priorities.uniq == priorities - raise InvalidState, "authorization priorities must be unique and ordered" - end + prev_priority = nil + bid_ids = {} + auth_priorities = reserve_history.empty? ? nil : {} - bid_ids = [] authorization_history.each do |entry| - unless %w[place_bid maximum_reduced].include?(entry.fetch("type")) + priority = entry.fetch("priority") + unless priority.is_a?(Integer) + raise InvalidState, "authorization priority must belong to the event stream" + end + if prev_priority && priority <= prev_priority + raise InvalidState, "authorization priorities must be unique and ordered" + end + prev_priority = priority + + type = entry.fetch("type") + unless type == "place_bid" || type == "maximum_reduced" raise InvalidState, "authorization type is invalid" end unless Money.amount?(entry.fetch("maximum_minor_units")) @@ -392,54 +467,65 @@ def validate_authorization_history! if entry.fetch("bidder_id").empty? raise InvalidState, "authorization bidder ID must be present" end - unless entry.fetch("priority").positive? && entry.fetch("priority") <= version + unless priority.positive? && priority <= version raise InvalidState, "authorization priority must belong to the event stream" end - next unless entry.fetch("type") == "place_bid" + auth_priorities[priority] = true if auth_priorities + + next unless type == "place_bid" bid_id = entry.fetch("bid_id") raise InvalidState, "authorization bid ID must be present" if bid_id.empty? + raise InvalidState, "bid IDs must be unique" if bid_ids.key?(bid_id) - bid_ids << bid_id - end - raise InvalidState, "bid IDs must be unique" unless bid_ids.uniq == bid_ids - unless voided_bid_ids.uniq == voided_bid_ids - raise InvalidState, "voided bid IDs must be unique" + bid_ids[bid_id] = true end - unless voided_bid_ids.all? { |bid_id| bid_ids.include?(bid_id) } - raise InvalidState, "voided bid IDs must refer to accepted bids" + + unless voided_bid_ids.empty? + seen_voided = {} + missing_voided = false + voided_bid_ids.each do |bid_id| + raise InvalidState, "voided bid IDs must be unique" if seen_voided.key?(bid_id) + seen_voided[bid_id] = true + missing_voided = true unless bid_ids.key?(bid_id) + end + raise InvalidState, "voided bid IDs must refer to accepted bids" if missing_voided end + + auth_priorities end - def validate_reserve_history! - priorities = reserve_history.map { |entry| entry.fetch("priority") } - valid_priorities = priorities.all? do |priority| - priority.is_a?(Integer) && priority.positive? && priority <= version - end - unless valid_priorities - raise InvalidState, "reserve change priority must belong to the event stream" - end - unless priorities == priorities.sort && priorities.uniq == priorities - raise InvalidState, "reserve change priorities must be unique and ordered" - end - unless (priorities & authorization_history.map { |entry| entry.fetch("priority") }).empty? - raise InvalidState, "state history priorities must be unique" - end + def validate_reserve_history!(auth_priorities) + return if reserve_history.empty? + prev_priority = nil + prev_new_reserve = nil + has_prev = false reserve_history.each do |entry| - unless valid_optional_minor_units?(entry.fetch("old_reserve_minor_units")) && - valid_optional_minor_units?(entry.fetch("new_reserve_minor_units")) + priority = entry.fetch("priority") + unless priority.is_a?(Integer) && priority.positive? && priority <= version + raise InvalidState, "reserve change priority must belong to the event stream" + end + if prev_priority && priority <= prev_priority + raise InvalidState, "reserve change priorities must be unique and ordered" + end + if auth_priorities&.key?(priority) + raise InvalidState, "state history priorities must be unique" + end + prev_priority = priority + + old_reserve = entry.fetch("old_reserve_minor_units") + new_reserve = entry.fetch("new_reserve_minor_units") + unless valid_optional_minor_units?(old_reserve) && valid_optional_minor_units?(new_reserve) raise InvalidState, "reserve change values must be non-negative integers or nil" end - end - reserve_history.each_cons(2) do |previous, current| - unless previous.fetch("new_reserve_minor_units") == - current.fetch("old_reserve_minor_units") + if has_prev && prev_new_reserve != old_reserve raise InvalidState, "reserve change history must be continuous" end + prev_new_reserve = new_reserve + has_prev = true end - if reserve_history.any? && - reserve_history.last.fetch("new_reserve_minor_units") != reserve_minor_units + if prev_new_reserve != reserve_minor_units raise InvalidState, "current reserve must match reserve change history" end end @@ -449,7 +535,7 @@ def valid_optional_minor_units?(value) end def validate_lifecycle! - unless %w[open closed].include?(status) + unless status == "open" || status == "closed" raise InvalidState, "bidding status is invalid" end if status == "open" @@ -459,7 +545,7 @@ def validate_lifecycle! return end - unless %w[sold no_sale no_bid].include?(result) + unless result == "sold" || result == "no_sale" || result == "no_bid" raise InvalidState, "closed bidding result is invalid" end case result diff --git a/ruby/engine/script/benchmark_history_validation.rb b/ruby/engine/script/benchmark_history_validation.rb new file mode 100644 index 0000000..31bc979 --- /dev/null +++ b/ruby/engine/script/benchmark_history_validation.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +# Synthetic diagnostic only; no timing threshold is an engine contract. +require "json" +require_relative "../lib/rbbb" + +engine = RBBB::Engine.new(RBBB::Configuration.new( + currency: "USD", opening_minor_units: 100, + increments: [{from_minor_units: 0, amount_minor_units: 100}], + opens_at: "2026-01-01T00:00:00Z", closes_at: "2026-01-02T00:00:00Z" +)) +state = engine.initial_state +1_000.times do |index| + decision = engine.decide(state, { + command_id: "synthetic-#{index}", type: "place_bid", + bid_id: "synthetic-#{index}", bidder_id: "synthetic-bidder", + maximum_minor_units: 100 * (index + 1), effective_at: "2026-01-01T12:00:00Z" + }) + raise "synthetic setup rejected" if decision.rejected? + + state = engine.apply(state, decision.events) +end +snapshot = state.to_h +command = { + command_id: "synthetic-next", type: "place_bid", bid_id: "synthetic-next", + bidder_id: "synthetic-bidder", maximum_minor_units: 100_100, + effective_at: "2026-01-01T12:00:01Z" +} +measurements = {} +{ + restore: -> { RBBB::State.from_h(snapshot) }, + decide_and_apply: -> { engine.apply(state, engine.decide(state, command).events) } +}.each do |name, operation| + 10.times { operation.call } + measurements[name] = 3.times.map do + GC.start + allocated_before = GC.stat(:total_allocated_objects) + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 300.times { operation.call } + { + seconds: Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, + allocated_objects: GC.stat(:total_allocated_objects) - allocated_before + } + end +end +puts JSON.pretty_generate(ruby: RUBY_DESCRIPTION, history_entries: 1_000, + iterations_per_measurement: 300, measurements: measurements) diff --git a/ruby/engine/test/live_registration_test.rb b/ruby/engine/test/live_registration_test.rb index 2eaadcc..1984436 100644 --- a/ruby/engine/test/live_registration_test.rb +++ b/ruby/engine/test/live_registration_test.rb @@ -115,4 +115,34 @@ def test_closed_admission_semantics_and_duplicate_keys malformed["configuration"]["opens_at"] = malformed["configuration"]["closes_at"] assert_raises(RBBB::LiveScheduling::Intent::Invalid) { register(malformed) } end + + def test_registration_accepts_extend_on_void_false_and_rejects_true + with_false = Marshal.load(Marshal.dump(@intent)) + with_false["configuration"]["extension"]["extend_on_void"] = false + normalized = RBBB::LiveScheduling::Intent.normalize_registration(with_false) + assert_equal false, normalized["configuration"]["extension"]["extend_on_void"] + + result = register(with_false) + assert_nil result.rejection_reason + assert_equal({"trigger_window_seconds" => 60, "duration_seconds" => 120}, + result.state["closing_sets"].first["extension"]) + assert_equal false, result.configurations["unit-new"]["extension"]["extend_on_void"] + + reloaded = coordinator(result.state, result.configurations) + assert_equal result.state["units"], reloaded.snapshot["units"] + assert_equal result.state["schedule_revision"], reloaded.snapshot["schedule_revision"] + replayed = RBBB::LiveScheduling::Projector.apply_commit( + snapshot: @snapshot, configurations: {}, records: result.records, + policy: {"minimum_shortening_lead_seconds" => 60}, auction_id: "auction-one" + ) + assert_equal result.state, replayed["snapshot"] + assert_equal result.configurations, replayed["configurations"] + + with_true = Marshal.load(Marshal.dump(@intent)) + with_true["configuration"]["extension"]["extend_on_void"] = true + error = assert_raises(RBBB::LiveScheduling::Intent::Invalid) do + RBBB::LiveScheduling::Intent.normalize_registration(with_true) + end + assert_equal "extend_on_void is not supported for linked live scheduling", error.message + end end diff --git a/ruby/engine/test/live_scheduling_admission_integration_test.rb b/ruby/engine/test/live_scheduling_admission_integration_test.rb index 0249010..65c7b7e 100644 --- a/ruby/engine/test/live_scheduling_admission_integration_test.rb +++ b/ruby/engine/test/live_scheduling_admission_integration_test.rb @@ -28,7 +28,7 @@ def setup bid: {unit_id: "unit-c", command: {"type" => "place_bid", "command_id" => "bid-demo", "bid_id" => "bid-demo", "maximum_minor_units" => 5000}}, void_bid: {unit_id: "unit-c", command: {"type" => "void_bid", "command_id" => "void-demo", "bid_id" => "bid-demo", "reason" => "Synthetic correction", "notification_policy" => "affected"}}, change_reserve: {unit_id: "unit-c", command: {"type" => "change_reserve", "command_id" => "reserve-demo", "reserve_minor_units" => 100, - "reason" => "Synthetic correction", "notification_policy" => "affected"}}, + "reason" => "Synthetic correction"}}, close: {unit_id: "unit-c", command_id: "close-demo"} } end diff --git a/ruby/engine/test/live_scheduling_consumer_test.rb b/ruby/engine/test/live_scheduling_consumer_test.rb index 91e3dd3..b8506a9 100644 --- a/ruby/engine/test/live_scheduling_consumer_test.rb +++ b/ruby/engine/test/live_scheduling_consumer_test.rb @@ -78,7 +78,7 @@ def test_catalog_policy_change_replaces_view_with_only_authorized_digest refute current["payload"]["snapshot"]["units"].key?(@hidden) refute_equal old["sha256"], current["sha256"] assert_equal current, stored - assert_equal Digest::SHA256.hexdigest(JSON.generate(current["payload"])), current["sha256"] + assert_equal Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(current["payload"])), current["sha256"] refute current["payload"]["snapshot"].key?("closing_sets") assert_raises(RBBBExamples::LiveSchedulingReader::NotAuthorized) do @reader.checkpoint(credential: "token", visibility: "privileged") @@ -89,14 +89,14 @@ def test_scope_digest_and_conflicting_identity_fail_closed original = read mutated = JSON.parse(JSON.generate(original)) mutated["payload"]["snapshot"]["units"].clear - mutated["sha256"] = Digest::SHA256.hexdigest(JSON.generate(mutated["payload"])) + mutated["sha256"] = Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(mutated["payload"])) adapter = RBBBExamples::LiveSchedulingConsumer.new(**@args.merge(fetch: ->(**_args) { mutated })) assert_raises(RBBBExamples::LiveSchedulingConsumer::InvalidCheckpoint) { adapter.read(credential: "token") } assert_equal original, stored %w[tenant_id auction_id visibility].each do |field| changed = JSON.parse(JSON.generate(original)) changed["payload"][field] = "wrong" - changed["sha256"] = Digest::SHA256.hexdigest(JSON.generate(changed["payload"])) + changed["sha256"] = Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(changed["payload"])) adapter = RBBBExamples::LiveSchedulingConsumer.new(**@args.merge(fetch: ->(**_args) { changed })) assert_raises(RBBBExamples::LiveSchedulingConsumer::InvalidCheckpoint) { adapter.read(credential: "token") } end @@ -106,6 +106,38 @@ def test_scope_digest_and_conflicting_identity_fail_closed assert_equal original, stored end + def test_canonical_digest_accepts_reordered_payload_keys + original = read + reordered = { + "sha256" => original.fetch("sha256"), + "payload" => original.fetch("payload").to_a.reverse.to_h + } + adapter = RBBBExamples::LiveSchedulingConsumer.new(**@args.merge( + path: File.join(@dir, "reordered.sqlite3"), + fetch: ->(**_args) { reordered } + )) + assert_equal original.fetch("sha256"), adapter.read(credential: "token").fetch("sha256") + end + + def test_consumer_rejects_symlink_and_world_readable_database_paths + target = File.join(@dir, "target.sqlite3") + File.write(target, "") + File.chmod(0o600, target) + symlink = File.join(@dir, "link.sqlite3") + File.symlink(target, symlink) + assert_raises(ArgumentError) { RBBBExamples::LiveSchedulingConsumer.new(**@args.merge(path: symlink)) } + + dangling = File.join(@dir, "dangling.sqlite3") + File.symlink(File.join(@dir, "missing.sqlite3"), dangling) + assert_raises(ArgumentError) { RBBBExamples::LiveSchedulingConsumer.new(**@args.merge(path: dangling)) } + refute File.exist?(File.join(@dir, "missing.sqlite3")) + + loose = File.join(@dir, "loose.sqlite3") + File.write(loose, "") + File.chmod(0o644, loose) + assert_raises(ArgumentError) { RBBBExamples::LiveSchedulingConsumer.new(**@args.merge(path: loose)) } + end + def test_public_and_privileged_stores_are_isolated_and_no_offline_fallback_is_served public_result = read private_args = @args.merge(path: File.join(@dir, "private.sqlite3"), visibility: "privileged") diff --git a/ruby/engine/test/live_scheduling_coordinator_test.rb b/ruby/engine/test/live_scheduling_coordinator_test.rb index e949676..3ddcd29 100644 --- a/ruby/engine/test/live_scheduling_coordinator_test.rb +++ b/ruby/engine/test/live_scheduling_coordinator_test.rb @@ -87,4 +87,153 @@ def normalize_times(value) end end end + + def test_leader_changing_reduce_maximum_extension_replays_cleanly_through_projector + config = {"currency" => "USD", "opening_minor_units" => 100, "reserve_minor_units" => nil, + "increments" => [{"from_minor_units" => 0, "amount_minor_units" => 100}], + "opens_at" => "2031-04-17T12:00:00Z", "closes_at" => "2031-04-17T13:00:00Z", + "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}} + configs = {"unit-a" => config, "unit-b" => config} + engine = RBBB::Engine.new(RBBB::Configuration.from_h(config.merge("extension" => nil))) + # bidder-a bids 500 (priority 1), bidder-b matches 500 (priority 2), bidder-a raises to 700 (priority 3). + # When bidder-a reduces back to 500 (priority 4), bidder-b wins the tie on earlier priority (2 < 4). + state_a = engine.initial_state + [ + {"command_id" => "a1", "type" => "place_bid", "bidder_id" => "bidder-a", "maximum_minor_units" => 500, "effective_at" => "2031-04-17T12:10:00Z"}, + {"command_id" => "b1", "type" => "place_bid", "bidder_id" => "bidder-b", "maximum_minor_units" => 500, "effective_at" => "2031-04-17T12:11:00Z"}, + {"command_id" => "a2", "type" => "place_bid", "bidder_id" => "bidder-a", "maximum_minor_units" => 700, "effective_at" => "2031-04-17T12:12:00Z"} + ].each do |cmd| + state_a = engine.apply(state_a, engine.decide(state_a, cmd).events) + end + assert_equal "bidder-a", state_a.leader_id + assert_equal 500, state_a.standing_minor_units + snapshot = { + "schedule_revision" => 0, + "units" => {"unit-a" => state_a.to_h, "unit-b" => engine.initial_state.to_h}, + "closing_sets" => [{"group_id" => "group-1", "member_unit_ids" => %w[unit-a unit-b], + "closes_at" => "2031-04-17T13:00:00Z", "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}}] + } + coordinator = RBBB::LiveScheduling::Coordinator.new(auction_id: "auction-demo", configurations: configs, + snapshot: snapshot, policy: {"minimum_shortening_lead_seconds" => 60}) + result = coordinator.bid( + unit_id: "unit-a", + command: {"type" => "reduce_maximum", "command_id" => "reduce-flip", "bidder_id" => "bidder-a", "maximum_minor_units" => 500}, + effective_at: "2031-04-17T12:59:30Z", + commit_id: "commit-reduce-flip" + ) + assert_nil result.rejection_reason + assert_equal "bidder-b", result.state["units"]["unit-a"]["leader_id"] + assert_equal "2031-04-17T13:01:30Z", result.state["units"]["unit-a"]["closes_at"] + assert_equal "2031-04-17T13:01:30Z", result.state["units"]["unit-b"]["closes_at"] + + replayed = RBBB::LiveScheduling::Projector.apply(snapshot: snapshot, configurations: configs, records: result.records) + assert_equal normalize_times(result.state), normalize_times(replayed) + end + + def test_projector_rejects_forged_and_out_of_window_bid_extensions + config = {"currency" => "USD", "opening_minor_units" => 100, "reserve_minor_units" => nil, + "increments" => [{"from_minor_units" => 0, "amount_minor_units" => 100}], + "opens_at" => "2031-04-17T12:00:00Z", "closes_at" => "2031-04-17T13:00:00Z", + "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}} + configs = {"unit-a" => config} + empty = RBBB::State.empty(RBBB::Configuration.from_h(config)).to_h + snapshot = { + "schedule_revision" => 0, + "units" => {"unit-a" => empty}, + "closing_sets" => [{"group_id" => nil, "member_unit_ids" => ["unit-a"], + "closes_at" => "2031-04-17T13:00:00Z", "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}}] + } + coordinator = RBBB::LiveScheduling::Coordinator.new(auction_id: "auction-demo", configurations: configs, + snapshot: snapshot, policy: {"minimum_shortening_lead_seconds" => 60}) + + # 1. Forged extension on an out-of-window bid (at 12:30:00Z, trigger window is 60s before 13:00:00Z) + early = coordinator.bid( + unit_id: "unit-a", + command: {"type" => "place_bid", "command_id" => "early-bid", "bidder_id" => "bidder-a", "maximum_minor_units" => 500}, + effective_at: "2031-04-17T12:30:00Z", + commit_id: "commit-early" + ) + assert_nil early.rejection_reason + forged_records = RBBB::LiveScheduling.copy(early.records) + forged_close = "2031-04-17T13:05:00Z" + forged_records.each { |r| r["event"]["closes_at"] = forged_close if r["event"].key?("closes_at") } + forged_records << {"unit_id" => "unit-a", "event" => {"type" => "closing_time_changed", + "command_id" => "early-bid", "aggregate_version" => 1, "closes_at" => forged_close}} + forged_records << {"capability" => RBBB::LiveScheduling::CAPABILITY, "type" => "closing_configuration_changed", + "command_id" => "early-bid", "commit_id" => "commit-early", "auction_id" => "auction-demo", + "effective_at" => "2031-04-17T12:30:00Z", "visibility" => "public", "schedule_revision" => 1, + "unit_versions" => [{"unit_id" => "unit-a", "version" => 1}], + "resulting_closing_sets" => [{"group_id" => nil, "member_unit_ids" => ["unit-a"], + "closes_at" => forged_close, "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}}], + "retired_group_ids" => []} + assert_raises(RBBB::InvalidState) do + RBBB::LiveScheduling::Projector.apply(snapshot: snapshot, configurations: configs, records: forged_records) + end + + # 2. Forged duration on an in-window bid (should extend to 13:01:30Z, forged to 13:10:00Z) + in_window = coordinator.bid( + unit_id: "unit-a", + command: {"type" => "place_bid", "command_id" => "late-bid", "bidder_id" => "bidder-a", "maximum_minor_units" => 500}, + effective_at: "2031-04-17T12:59:30Z", + commit_id: "commit-late" + ) + assert_nil in_window.rejection_reason + tampered = RBBB::LiveScheduling.copy(in_window.records) + tampered.each do |record| + if record.key?("event") + record["event"]["closes_at"] = "2031-04-17T13:10:00Z" if record["event"].key?("closes_at") + elsif record["type"] == "closing_configuration_changed" + record["resulting_closing_sets"].first["closes_at"] = "2031-04-17T13:10:00Z" + end + end + assert_raises(RBBB::InvalidState) do + RBBB::LiveScheduling::Projector.apply(snapshot: snapshot, configurations: configs, records: tampered) + end + end + + def test_projector_assigns_accurate_privileged_and_public_event_visibility + assert_equal :privileged, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "executed_amount_changed"}) + assert_equal :privileged, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "notification_requested"}) + assert_equal :privileged, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "bidding_closed", "positions" => {}}) + assert_equal :privileged, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "closing_time_changed", "positions" => {}}) + assert_equal :public, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "standing_bid_changed"}) + assert_equal :public, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "reserve_status_changed"}) + assert_equal :public, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "closing_time_changed"}) + assert_equal :public, RBBB::LiveScheduling::Projector.send(:event_visibility, {"type" => "bidding_closed"}) + end + + def test_coordinator_close_rejects_invalid_effective_at_and_bid_guards_year_9999_overflow + config = {"currency" => "USD", "opening_minor_units" => 100, "reserve_minor_units" => nil, + "increments" => [{"from_minor_units" => 0, "amount_minor_units" => 100}], + "opens_at" => "9999-12-31T22:00:00Z", "closes_at" => "9999-12-31T23:59:59Z", + "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}} + configs = {"unit-a" => config} + empty = RBBB::State.empty(RBBB::Configuration.from_h(config)).to_h + snapshot = { + "schedule_revision" => 0, + "units" => {"unit-a" => empty}, + "closing_sets" => [{"group_id" => nil, "member_unit_ids" => ["unit-a"], + "closes_at" => "9999-12-31T23:59:59Z", "extension" => {"trigger_window_seconds" => 60, "duration_seconds" => 120}}] + } + coordinator = RBBB::LiveScheduling::Coordinator.new(auction_id: "auction-demo", configurations: configs, + snapshot: snapshot, policy: {"minimum_shortening_lead_seconds" => 60}) + + bad_close = coordinator.close( + unit_id: "unit-a", + command: {"type" => "close_bidding", "command_id" => "bad-close"}, + effective_at: "not-a-timestamp", + commit_id: "commit-bad-close" + ) + assert_equal "invalid_request", bad_close.rejection_reason + assert_empty bad_close.records + + overflow_bid = coordinator.bid( + unit_id: "unit-a", + command: {"type" => "place_bid", "command_id" => "overflow-bid", "bidder_id" => "bidder-a", "maximum_minor_units" => 500}, + effective_at: "9999-12-31T23:59:30Z", + commit_id: "commit-overflow" + ) + assert_equal "invalid_closing_time", overflow_bid.rejection_reason + assert_empty overflow_bid.records + end end diff --git a/ruby/engine/test/live_scheduling_host_test.rb b/ruby/engine/test/live_scheduling_host_test.rb index 45fd654..07719bf 100644 --- a/ruby/engine/test/live_scheduling_host_test.rb +++ b/ruby/engine/test/live_scheduling_host_test.rb @@ -651,7 +651,7 @@ def test_void_process_kill_before_and_after_commit_preserves_exact_replay_and_de def reserve_command(id = "reserve-command", amount = 100) {"type" => "change_reserve", "command_id" => id, "reserve_minor_units" => amount, - "reason" => "Synthetic reserve correction", "notification_policy" => "affected"} + "reason" => "Synthetic reserve correction"} end def reserve(host = @host, command = reserve_command, principal = "operator-demo", permissions = ["reserve"]) @@ -676,11 +676,25 @@ def test_reserve_change_is_durable_authorized_and_preserves_scheduling assert_empty denied["records"] end assert_equal "command_id_reused", reserve(reopened, reserve_command("reserve-command", 50))["rejection_reason"] - %w[operator_id effective_at].each do |field| + %w[operator_id effective_at notification_policy].each do |field| assert_raises(ArgumentError) { reserve(@host, reserve_command.merge(field => "spoof")) } end end + def test_bid_accepts_expected_version_and_enforces_optimistic_concurrency + version = @host.snapshot["units"]["unit-c"]["version"] + stale = @host.bid(unit_id: "unit-c", + command: {"type" => "place_bid", "command_id" => "stale-bid", "maximum_minor_units" => 5000, "expected_version" => version + 1}, + principal_id: "bidder-new") + assert_equal "stale_aggregate_version", stale["rejection_reason"] + + accepted = @host.bid(unit_id: "unit-c", + command: {"type" => "place_bid", "command_id" => "fresh-bid", "maximum_minor_units" => 5000, "expected_version" => version}, + principal_id: "bidder-new") + assert_nil accepted["rejection_reason"] + assert_equal version + 1, @host.snapshot["units"]["unit-c"]["version"] + end + def test_reserve_commit_failure_rolls_back_and_retry_commits_once before, history, count = @host.snapshot, @host.records, @host.receipt_count failing = Class.new(RBBBExamples::LiveSchedulingHost) do diff --git a/ruby/engine/test/live_scheduling_reader_test.rb b/ruby/engine/test/live_scheduling_reader_test.rb index f506200..2eaea95 100644 --- a/ruby/engine/test/live_scheduling_reader_test.rb +++ b/ruby/engine/test/live_scheduling_reader_test.rb @@ -49,7 +49,7 @@ def test_public_digest_is_of_only_authorized_projection_and_catalog_is_checked_e expected = @host.snapshot.fetch("units").reject { |id, _| id == @hidden }.transform_values { |unit| RBBB::State.from_h(unit).public_view } assert_equal expected, payload.fetch("snapshot").fetch("units") refute payload.fetch("snapshot").key?("closing_sets") - assert_equal Digest::SHA256.hexdigest(JSON.generate(payload)), result.fetch("sha256") + assert_equal Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(payload)), result.fetch("sha256") assert_equal "tenant-demo", @scope[:tenant_id] assert_equal "auction-demo", @scope[:auction_id] assert_equal "reader-demo", @scope[:principal_id] diff --git a/ruby/engine/test/state_history_validation_test.rb b/ruby/engine/test/state_history_validation_test.rb new file mode 100644 index 0000000..252643f --- /dev/null +++ b/ruby/engine/test/state_history_validation_test.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +require_relative "test_helper" + +class StateHistoryValidationTest < Minitest::Test + def setup + engine = RBBB::Engine.new(RBBB::Configuration.new( + currency: "USD", opening_minor_units: 100, reserve_minor_units: 1_000, + increments: [{from_minor_units: 0, amount_minor_units: 100}], + opens_at: "2026-01-01T00:00:00Z", closes_at: "2026-01-02T00:00:00Z" + )) + state = engine.initial_state + [ + {type: "place_bid", bidder_id: "bidder-a", bid_id: "bid-a", maximum_minor_units: 2_000}, + {type: "place_bid", bidder_id: "bidder-b", bid_id: "bid-b", maximum_minor_units: 1_500}, + {type: "change_reserve", operator_id: "operator", reason: "synthetic", reserve_minor_units: 900}, + {type: "change_reserve", operator_id: "operator", reason: "synthetic", reserve_minor_units: 800} + ].each_with_index do |command, index| + decision = engine.decide(state, command.merge(command_id: "command-#{index}", + effective_at: "2026-01-01T12:00:00Z")) + raise "invalid synthetic fixture" if decision.rejected? + + state = engine.apply(state, decision.events) + end + @snapshot = state.to_h + end + + def test_valid_history_with_and_without_reserve_changes_round_trips + assert_equal @snapshot, RBBB::State.from_h(@snapshot).to_h + @snapshot["reserve_history"] = [] + assert_equal @snapshot, RBBB::State.from_h(@snapshot).to_h + end + + def test_authorization_types_remain_an_exact_allowlist + entry = @snapshot.fetch("authorization_history").last + entry["type"] = "maximum_reduced" + entry.delete("bid_id") + assert_equal @snapshot, RBBB::State.from_h(@snapshot).to_h + + ["", "PLACE_BID", "place_bid ", "reduce_maximum", nil].each do |type| + entry["type"] = type + assert_invalid("authorization type is invalid") + end + end + + def test_empty_reserve_history_does_not_bypass_authorization_validation + @snapshot["reserve_history"] = [] + assert_authorization_errors + end + + def test_nonempty_reserve_history_preserves_authorization_validation + assert_authorization_errors + end + + def test_reserve_order_range_and_cross_history_collisions_are_validated + history = @snapshot.fetch("reserve_history") + [[0, 4], [3, 5], ["3", 4]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("reserve change priority must belong to the event stream") + end + [[4, 3], [3, 3]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("reserve change priorities must be unique and ordered") + end + [[1, 4], [2, 4]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("state history priorities must be unique") + end + set_priorities(history, [3, 4]) + assert_equal @snapshot, RBBB::State.from_h(@snapshot).to_h + end + + def test_reserve_values_continuity_and_current_value_remain_validated + history = @snapshot.fetch("reserve_history") + history.first["old_reserve_minor_units"] = -1 + assert_invalid("reserve change values must be non-negative integers or nil") + history.first["old_reserve_minor_units"] = 1_000 + history.last["old_reserve_minor_units"] = 700 + assert_invalid("reserve change history must be continuous") + history.last["old_reserve_minor_units"] = 900 + history.last["new_reserve_minor_units"] = 700 + assert_invalid("current reserve must match reserve change history") + end + + private + + def assert_authorization_errors + history = @snapshot.fetch("authorization_history") + [["1", 2], [1, nil]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("authorization priority must belong to the event stream") + end + [[2, 1], [1, 1]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("authorization priorities must be unique and ordered") + end + [[0, 2], [1, 5]].each do |priorities| + set_priorities(history, priorities) + assert_invalid("authorization priority must belong to the event stream") + end + set_priorities(history, [1, 2]) + history.last["bid_id"] = "bid-a" + assert_invalid("bid IDs must be unique") + history.last["bid_id"] = "bid-b" + history.last["maximum_minor_units"] = -1 + assert_invalid("authorization maximum must be a non-negative integer no greater than #{RBBB::Money::MAX_MINOR_UNITS}") + history.last["maximum_minor_units"] = 1_500 + @snapshot["voided_bid_ids"] = ["missing-bid"] + assert_invalid("voided bid IDs must refer to accepted bids") + @snapshot["voided_bid_ids"] = ["bid-b", "bid-b"] + assert_invalid("voided bid IDs must be unique") + end + + def set_priorities(history, priorities) + history.zip(priorities).each { |entry, priority| entry["priority"] = priority } + end + + def assert_invalid(message) + error = assert_raises(RBBB::InvalidState) { RBBB::State.from_h(@snapshot) } + assert_equal message, error.message + end +end