Skip to content

perf(engine): fix LiveScheduling projector/host bugs and eliminate history/coordinator allocation hotspots - #65

Merged
willtmc merged 2 commits into
mainfrom
perf/core-and-live-scheduling-correctness
Nov 26, 2026
Merged

willtmc merged 2 commits into
mainfrom
perf/core-and-live-scheduling-correctness

Conversation

@willtmc

@willtmc willtmc commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Summary

Supersedes #54.

Fixes LiveScheduling projector, coordinator, intent, and reference-host correctness/security bugs, and eliminates allocation and quadratic-scaling hotspots in core history validation, event deep-freezing, live scheduling, and retained-history verification — with zero bidding/pricing semantics changes.

Correctness & Security Fixes

  • LiveScheduling::Projector (projector.rb):
    • Include "maximum_reduced" alongside "maximum_accepted" / "maximum_increased" when replaying qualifying linked bid extensions.
    • Validate that any linked extension (closes_at > before.closes_at) actually qualified under the closing set's extension policy, occurred inside trigger_window_seconds, matches [before.closes_at, effective_at + duration_seconds].max, and matches the closing_configuration_changed delta's resulting closing set; reject forged, out-of-window, or unexpected scheduling deltas with RBBB::InvalidState.
    • Fix event visibility classification so executed_amount_changed, notification_requested, and all state-transition events are :privileged, and only public companion events (standing_bid_changed, reserve_status_changed, closing_time_changed, bidding_closed) are :public.
  • LiveScheduling::Coordinator & Intent (coordinator.rb, intent.rb):
    • Rescue ArgumentError, RangeError in Coordinator#close (returning reject("invalid_request")) instead of raising on invalid effective_at.
    • Guard year-9999 / RangeError extension overflow in Coordinator#bid cleanly with reject("invalid_closing_time").
    • Accept optional "extend_on_void": false in Intent.normalize_registration (preserving timed-proxy.schema.json compatibility while stripping it from closing_set["extension"] per contract.schema.json) and reject "extend_on_void": true with "extend_on_void is not supported for linked live scheduling".
  • Reference Examples (examples/):
    • LiveSchedulingHost: remove non-spec "notification_policy" from change_reserve allowlist, add "expected_version" to bid allowlist, and stop calling private coordinator.send(:reject, ...).
    • SharedGroupHost / DurableSharedGroupHost: replace private .send(:normalize_request) / .send(:normalize_close_request) and instance_variable_get(:@snapshot) with clean public methods (normalize_request, normalize_close_request, public_snapshot).
    • Extract shared examples/support/sqlite_store.rb (File::EXCL + File.lstat regular-file/uid/mode checks + BEGIN IMMEDIATE transactions) and adopt it in DurableSharedGroupHost, LiveSchedulingHost, and LiveSchedulingConsumer (closing the symlink/TOCTOU vulnerability in LiveSchedulingConsumer).
    • Use RFC 8785 canonical RBBB::LiveScheduling::Intent.canonical(payload) for SHA-256 checkpoint hashing in LiveSchedulingReader and LiveSchedulingConsumer.

Performance & Allocation Optimizations (Folding & Expanding #54)

  • Core State, Event, Engine:
    • Single-pass State#validate_authorization_history! and #validate_reserve_history! with monotonic prev_priority < priority checks, Hash lookups for bid_ids / auth_priorities, direct type comparisons, and empty-reserve-history short-circuit.
    • Fast-path already-frozen normalized hashes in State#coerce_authorization / #coerce_reserve_change, skip redundant transform_keys on string-keyed hashes, and skip re-allocating already-deeply-frozen structures in Event#deep_freeze.
    • Stop unnecessary state.authorization_history.map(&:dup) / state.reserve_history.map(&:dup) in Engine where entries are already frozen; preserve private method names/signatures (:position_priority, :price_positions, :apply_executions!, :replay_authorizations).
  • LiveScheduling & InitialClosingSchedule:
    • Replace JSON.parse(JSON.generate(value)) in LiveScheduling.copy with a pure Ruby recursive deep copy.
    • Eliminate O(N²) loops over closing_sets in Coordinator (discover, affected_sets, edit, change_kinds, result, bid, close) and Projector#apply via Hash indices (unit_to_set, group_to_set); replace before.to_h["closes_at"] in Projector with Timestamp.dump(before.closes_at).
    • Replace O(G²) / O(G × U) array scans in InitialClosingSchedule.plan with O(1) Hash lookups.
  • LiveSchedulingHost#validate_retained_history!:
    • Index journaled rows by commit_id in a Hash and batch-fetch outbox rows in a single SELECT ... INNER JOIN commits query instead of N+1 queries.

Verification

  • ruby scripts/validate_documents.rb: Validated 21 JSON Schemas, 44 conformance scenarios, and the OpenAPI/AsyncAPI documents.
  • cd ruby/engine && bundle exec rake: 439 runs, 357,557 assertions, 0 failures, 0 errors, 0 skips; verify_package.rb passed (19 files, clean install, smoke tests).
  • Synthetic allocation benchmark (ruby -Iruby/engine/lib ruby/engine/script/benchmark_history_validation.rb, Ruby 3.4.10 ARM, 1,000 history entries, 3 × 300 iterations):
    • restore: median 925,590 → 320,150 allocated objects (-65.4%), 0.280 s → 0.267 s
    • decide_and_apply: median 1,558,100 → 49,809 allocated objects (-96.8%), 0.466 s → 0.303 s (-35.0%)

@willtmc
willtmc merged commit 771d97f into main Nov 26, 2026
5 checks passed
@willtmc
willtmc deleted the perf/core-and-live-scheduling-correctness branch November 26, 2026 17:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant