diff --git a/examples/README.md b/examples/README.md index 21c13ae..b95d8bb 100644 --- a/examples/README.md +++ b/examples/README.md @@ -20,3 +20,5 @@ clock results and retry receipts across process restarts. It tests crash recover and competing local processes; it remains an evaluation adapter outside the gem. The durable adapter also [closes every group member in one transaction](durable-shared-group-host.md#closing-all-members-together), with per-lot outcomes and restart-safe retries. + +The [public-results outbox](durable-shared-group-host.md#public-result-delivery) retains delivery progress across restarts and supplies stable IDs for receiver deduplication. It sends no external messages by itself. diff --git a/examples/durable-shared-group-host.md b/examples/durable-shared-group-host.md index c5e2f9c..18597cc 100644 --- a/examples/durable-shared-group-host.md +++ b/examples/durable-shared-group-host.md @@ -75,7 +75,7 @@ replay mismatch and proxy adjustment after restart. This implementation replays the entire journal per operation and retains unbounded history. It is intended for correctness evaluation, not auction-scale -load. Checkpointing, durable notification delivery, +load. Checkpointing, production notification transport, live regrouping, authentication, backups and operational recovery tooling remain separate work. It is not a deployed bidding service or a production-readiness claim. Keep the adapter and engine source pinned when reopening existing data. @@ -116,3 +116,55 @@ Run `bundle exec ruby -Ilib:test test/durable_group_close_test.rb` from `ruby/engine` for mixed outcomes, shared-deadline enforcement, member refusal, restart/retry, actual process crashes, competing processes and privacy tests. Notification delivery and external invoicing remain separate from this commit. + +## Public result delivery + +The committed journal also serves as a durable public-results outbox. No separate +enqueue step can be lost between saving a bid or group close and making its +result available. Each accepted journal entry yields one envelope containing +only `delivery_id`, `clock` and `units`; rejected bids yield none. A group close +is one envelope containing every member's public outcome. The feed contains +historical committed projections, not necessarily the latest query state. + +```ruby +host.deliver_next_public(consumer_id: "public-feed") do |payload| + # Your receiver must persist delivery_id with its applied update atomically. + receiver.apply_once(payload.fetch("delivery_id"), payload) + # Return normally only after the receiver confirms success; raise on failure. +end +``` + +This example supplies no network transport and sends no email or bidder notices. +The caller's receiver implements the actual delivery. The callback executes +outside the database lock. A failure leaves the entry pending; returning normally +acknowledges it in a separate SQLite transaction. `nil` means nothing is pending. +For separate workers, `next_public_delivery(consumer_id:)` returns an envelope +and `acknowledge_public_delivery(consumer_id:, delivery_id:)` advances its cursor. +Only the next pending envelope may be acknowledged. Repeated acknowledgment is +a no-op, and one consumer's cursor never advances another's. + +Delivery is **at least once**. A crash after the receiver accepts an update but +before acknowledgment causes the same stable ID to be delivered again. The ID +combines a database-persisted stream UUID and journal sequence. The receiver must +deduplicate that ID atomically with its own side effects. This is not an +exactly-once guarantee for arbitrary external systems. Run one worker per consumer +for ordered callback execution; there is no lease preventing concurrent callbacks +for the same consumer. Separate consumers can independently read the whole stream. + +The adapter validates journal replay before exposing results and explicitly +selects only public projections. Privileged events, winner identities, maxima +and command IDs are excluded. Do not use this public feed as an invoice input: +privileged, authorized accounting handoff is separate work. + +Opening an existing database creates delivery metadata without changing its +journal. A new consumer starts at the oldest accepted commit, including commits +saved before this feature; nothing is sent automatically. Keep the database and +its delivery metadata together during backup/restore. Restoring an older backup +can redeliver records, so receiver deduplication remains necessary. Do not run +independently writable copies of the same database as distinct streams. + +Run `bundle exec ruby -Ilib:test test/public_delivery_test.rb` from `ruby/engine` +for restart/ack recovery, actual process exit after receiver handoff, callback +failure, cursor ordering, independent consumers, privacy, retries and rollback. +Full-history replay, checkpointing and production transport operations remain +separate from this local evaluation example. diff --git a/examples/durable_shared_group_host.rb b/examples/durable_shared_group_host.rb index 4b6d7be..9c6d5ea 100644 --- a/examples/durable_shared_group_host.rb +++ b/examples/durable_shared_group_host.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "json" require "sqlite3" +require "securerandom" require_relative "shared_group_host" module RBBBExamples @@ -21,6 +22,9 @@ def initialize(path:, configurations:, clock:) 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)") + db.execute("CREATE TABLE IF NOT EXISTS delivery_stream (id INTEGER PRIMARY KEY CHECK(id = 1), identity TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS delivery_cursors (consumer TEXT PRIMARY KEY, sequence INTEGER NOT NULL)") + db.execute("INSERT OR IGNORE INTO delivery_stream (id, identity) VALUES (1, ?)", [SecureRandom.uuid]) saved = db.get_first_value("SELECT document FROM metadata WHERE id = 1") if saved raise ArgumentError, "stored configuration differs" unless saved == @document @@ -60,8 +64,67 @@ def public_view end end + # Journal commits are the outbox: no separate enqueue can be lost. + def next_public_delivery(consumer_id:) + consumer = delivery_consumer(consumer_id) + transaction do |db| + restore(db) # Validate committed results before exposing any projection. + pending_delivery(db, consumer) + end + end + + def acknowledge_public_delivery(consumer_id:, delivery_id:) + consumer = delivery_consumer(consumer_id) + transaction do |db| + restore(db) + stream = db.get_first_value("SELECT identity FROM delivery_stream WHERE id = 1") + unless delivery_id.is_a?(String) && delivery_id.match?(/\A#{Regexp.escape(stream)}:[1-9][0-9]*\z/) + raise ArgumentError, "invalid delivery identity" + end + sequence = delivery_id.split(":").last.to_i + cursor = db.get_first_value("SELECT sequence FROM delivery_cursors WHERE consumer = ?", [consumer]) || 0 + next false if sequence <= cursor + pending = pending_delivery(db, consumer) + unless pending && pending.fetch("delivery_id") == delivery_id + raise ArgumentError, "only the next pending delivery can be acknowledged" + end + db.execute("INSERT INTO delivery_cursors (consumer, sequence) VALUES (?, ?) ON CONFLICT(consumer) DO UPDATE SET sequence = excluded.sequence", [consumer, sequence]) + true + end + end + + # Caller owns transport and sink deduplication. Never call under the DB lock. + def deliver_next_public(consumer_id:) + consumer_id = delivery_consumer(consumer_id) + raise ArgumentError, "delivery callback required" unless block_given? + payload = next_public_delivery(consumer_id: consumer_id) + return nil unless payload + identity = payload.fetch("delivery_id").dup.freeze + yield payload + acknowledge_public_delivery(consumer_id: consumer_id, delivery_id: identity) + payload + end + private + def delivery_consumer(value) + raise ArgumentError, "consumer ID required" unless value.is_a?(String) && !value.empty? + value.dup.freeze + end + + def pending_delivery(db, consumer) + cursor = db.get_first_value("SELECT sequence FROM delivery_cursors WHERE consumer = ?", [consumer]) || 0 + stream = db.get_first_value("SELECT identity FROM delivery_stream WHERE id = 1") + db.execute("SELECT sequence, result FROM commits WHERE sequence > ? ORDER BY sequence", [cursor]).each do |sequence, json| + result = JSON.parse(json) + next if result["rejection"] + # Explicit allowlist: never copy privileged events or receipt metadata. + return {"delivery_id" => "#{stream}:#{sequence}", + "clock" => result.fetch("clock"), "units" => result.fetch("units")} + end + nil + end + def build_host document = JSON.parse(@document) configs = document.fetch("configurations").transform_values { |v| RBBB::Configuration.from_h(v) } diff --git a/ruby/engine/test/public_delivery_test.rb b/ruby/engine/test/public_delivery_test.rb new file mode 100644 index 0000000..7bc0742 --- /dev/null +++ b/ruby/engine/test/public_delivery_test.rb @@ -0,0 +1,130 @@ +# frozen_string_literal: true +require_relative "test_helper" +require "tmpdir" +require_relative "../../../examples/durable_shared_group_host" + +class PublicDeliveryTest < Minitest::Test + def setup + @directory = Dir.mktmpdir("rbbb-delivery-") + @path = File.join(@directory, "group.sqlite3") + end + def teardown + FileUtils.remove_entry(@directory) + end + def host(klass = RBBBExamples::DurableSharedGroupHost) + config = {currency: "USD", opening_minor_units: 1000, + increments: [{from_minor_units: 0, amount_minor_units: 100}], + opens_at: "2030-01-01T12:00:00Z", closes_at: "2030-01-01T13:00:00Z"} + klass.new(path: @path, configurations: {"lot-12" => config, "lot-47" => config}, + clock: {group_id: "group-a", unit_ids: %w[lot-12 lot-47], closes_at: config[:closes_at], quiet_period_seconds: 180}) + end + def bid(id: "bid-a", maximum: 5000) + {unit_id: "lot-12", expected_revision: 0, command: {command_id: id, + type: "place_bid", bidder_id: "private-bidder", maximum_minor_units: maximum, + effective_at: "2030-01-01T12:30:00Z"}} + end + def pending(consumer = "public-feed") + host.next_public_delivery(consumer_id: consumer) + end + def test_committed_bid_and_group_close_are_delivered_in_order_after_restart + host.submit(**bid) + host.close_group(command_id: "close", effective_at: "2030-01-01T13:00:00Z", expected_revision: 0) + first = pending + assert_equal ["open"], first["units"].values.map { |v| v["status"] }.uniq + assert host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: first["delivery_id"]) + second = pending + assert_equal ["closed"], second["units"].values.map { |v| v["status"] }.uniq + refute_equal first["delivery_id"], second["delivery_id"] + host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: second["delivery_id"]) + assert_nil pending + end + def test_failed_callback_remains_pending_with_same_identity + host.submit(**bid) + original = pending + assert_raises(RuntimeError) do + host.deliver_next_public(consumer_id: "public-feed") { raise "transport unavailable" } + end + assert_equal original, pending + end + def test_crash_after_sink_write_before_ack_retries_stable_identity + host.submit(**bid) + sink = File.join(@directory, "sink-id") + pid = fork do + host.deliver_next_public(consumer_id: "public-feed") do |payload| + File.write(sink, payload["delivery_id"]) + Process.exit!(79) + end + end + assert_equal 79, Process.wait2(pid).last.exitstatus + assert_equal File.read(sink), pending["delivery_id"] + applied = {File.read(sink) => true} + host.deliver_next_public(consumer_id: "public-feed") { |p| applied[p["delivery_id"]] ||= true } + assert_equal 1, applied.size + assert_nil pending + end + def test_ack_is_idempotent_and_consumers_are_independent + host.submit(**bid) + id = pending["delivery_id"] + assert host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: id) + refute host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: id) + assert_nil pending + assert_equal id, pending("second-feed")["delivery_id"] + end + def test_ack_cannot_skip_pending_or_use_foreign_stream + host.submit(**bid) + host.submit(**bid(id: "increase", maximum: 6000)) + id = pending["delivery_id"] + assert_raises(ArgumentError) { host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: id.sub(/:1$/, ":2")) } + assert_raises(ArgumentError) { host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: "foreign:1") } + assert_equal id, pending["delivery_id"] + end + def test_rejections_and_command_retries_do_not_create_extra_delivery + host.submit(**bid(id: "low", maximum: 1)) + assert_nil pending + host.submit(**bid) + host.submit(**bid) + host.deliver_next_public(consumer_id: "public-feed") { |_| } + assert_nil pending + end + def test_rolled_back_commit_creates_no_delivery + crashing = Class.new(RBBBExamples::DurableSharedGroupHost) do + private + def before_commit(_db) + raise "failed save" + end + end + assert_raises(RuntimeError) { host(crashing).submit(**bid) } + assert_nil pending + end + def test_delivery_excludes_private_bid_records + host.submit(**bid) + host.close_group(command_id: "close", effective_at: "2030-01-01T13:00:00Z", expected_revision: 0) + 2.times do + payload = pending + %w[private-bidder maximum_minor_units winner_id leader_id positions events command_id].each do |secret| + refute_includes JSON.generate(payload), secret + end + host.acknowledge_public_delivery(consumer_id: "public-feed", delivery_id: payload["delivery_id"]) + end + end + def test_callback_does_not_hold_writer_lock + host.submit(**bid) + host.deliver_next_public(consumer_id: "public-feed") do |_| + host.submit(**bid(id: "increase", maximum: 6000)) + end + assert pending + end + def test_callback_cannot_change_which_delivery_is_acknowledged + host.submit(**bid) + host.submit(**bid(id: "increase", maximum: 6000)) + consumer = +"public-feed" + first_id = pending["delivery_id"] + host.deliver_next_public(consumer_id: consumer) do |payload| + consumer.replace("other-feed") + payload["delivery_id"].replace(first_id.sub(/:1$/, ":2")) + end + assert_equal first_id.sub(/:1$/, ":2"), pending["delivery_id"] + assert_equal first_id, pending("other-feed")["delivery_id"] + end + +end