Skip to content

perf: study contiguous order-book storage#119

Merged
div0rce merged 18 commits into
mainfrom
feat/m47-contiguous-order-book-storage
Jun 15, 2026
Merged

perf: study contiguous order-book storage#119
div0rce merged 18 commits into
mainfrom
feat/m47-contiguous-order-book-storage

Conversation

@div0rce

@div0rce div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner

Milestone

M47 — Contiguous order-book storage and cache-locality study.

Summary

  • Adds OrderBook::Storage::Contiguous, an opt-in fixed-band direct price-indexed storage mode.
  • Uses explicit resting-price band [1, 1024], occupancy bitmaps for best-level discovery, and contiguous per-level FIFO vectors.
  • Preserves baseline as the default and keeps matching deterministic inside the declared price-domain assumption.
  • Extends storage equivalence coverage so Baseline, PMR pooled, intrusive pooled, and contiguous storage produce identical generated-flow event streams, final EngineSnapshot, and last_seq.
  • Extends qsl-bench storage / make bench-storage and regenerates results/pool_backed_storage.txt with source-digest provenance.

Evidence

  • Artifact: results/pool_backed_storage.txt
  • Source digest: sha256:ecdd996360bc4b95e6d9111feda3daacccc9c346cceb3d8e88a901c3e9be1dfb
  • Dirty inputs: no
  • Benchmark rows compare baseline, PMR pooled, intrusive pooled, and contiguous storage on the same deterministic generated flow.
  • The committed result is local Apple clang / arm64 evidence only. It is not a production-latency, HFT-readiness, or portable speedup claim.

Tests

  • ./build/dev/tests/test_matching_engine — passed, 17 test cases / 65647 assertions
  • ./build/dev/tests/test_order_book — passed, 23 test cases / 126 assertions
  • git diff --check — passed
  • make check — passed, 225/225 tests
  • make asan — passed, 225/225 tests
  • make bench-storage — passed and regenerated the artifact

Notes

  • Out-of-band limit prices may still cross existing in-band liquidity; the contiguous mode only constrains where GTC remainders may rest.
  • A GTC remainder outside the contiguous band is refused before engine mutation via the existing storage guard path.
  • No cache-locality or speedup claim is made beyond the generated artifact.

Summary by CodeRabbit

  • New Features

    • Added an opt-in contiguous direct-price-indexed order-book storage mode with a fixed price band.
  • Behavior Changes

    • Modify requests that would reprice a remainder outside the contiguous band are pre-checked and rejected (gateway returns StorageExhausted).
  • Documentation

    • Expanded architecture, benchmarking, and release-readiness docs to cover the contiguous mode and its limitations.
  • Tests & Benchmarks

    • Benchmarks extended to include contiguous mode; added regression tests for out-of-band price and modify behavior.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@div0rce, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 45 minutes and 7 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 667138ed-b39d-47c6-8a15-09977a238f15

📥 Commits

Reviewing files that changed from the base of the PR and between f0f268b and 6250a44.

📒 Files selected for processing (8)
  • MILESTONES.md
  • PROGRESS.md
  • docs/pool_backed_storage.md
  • include/qsl/engine/order_book.hpp
  • results/pool_backed_storage.txt
  • src/engine/contiguous_store.hpp
  • src/engine/order_book.cpp
  • tests/unit/test_order_book.cpp

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements M47: Contiguous Order-Book Storage, adding a new fixed-band direct-price-indexed storage backend to OrderBook alongside existing baseline, pooled-node, and intrusive-pooled modes. The implementation includes the ContiguousStore backend, dispatch wiring throughout OrderBook, comprehensive tests, benchmark integration, and documentation of the bounded-domain architecture study.

Changes

M47 Contiguous Order-Book Storage

Layer / File(s) Summary
Project tracking and changelog
CHANGELOG.md, HANDOFF.md, MILESTONES.md, PROGRESS.md, README.md
Records M47 activation, marks M46 merged, updates current branch/PR and decision log, and updates CHANGELOG and README limitation wording.
Public API contract and constants
include/qsl/engine/order_book.hpp, include/qsl/engine/matching_engine.hpp
Storage enum extended with Contiguous; added kContiguousMinPrice/kContiguousMaxPrice; MatchResult and dispatch_storage declarations added; MatchingEngine::can_apply_modify exposed.
ContiguousStore backend implementation
src/engine/contiguous_store.hpp
Implements fixed-band per-side flat price arrays, occupancy bitmaps for discovery, per-level contiguous FIFO vectors with tombstones and compaction, matching/filling, add/cancel/modify (with remainder simulation and pre-gating), queries, and resting-order export.
OrderBook implementation and dispatch
src/engine/order_book.cpp
Adds shared matching/cancellation helpers, includes contiguous_store.hpp, refactors baseline/intrusive flows, adds dispatch_storage helpers, and routes public methods to baseline/intrusive/contiguous backends.
Engine and gateway pre-gates
src/engine/matching_engine.cpp, src/gateway/order_gateway.cpp
MatchingEngine::modify checks OrderBook::can_apply_modify and returns early if refused; gateway rejects failing modifies with RejectReason::StorageExhausted.
Benchmark invocation and artifact updates
benchmarks/bench_storage.cpp, scripts/run_storage_benchmarks.sh, results/pool_backed_storage.txt
Benchmarks now include Contiguous mode; script provenance/scenario/caveat text updated; results artifact refreshed with contiguous-mode row and updated metadata.
Documentation updates
docs/architecture.md, docs/pool_backed_storage.md, docs/benchmarking.md, docs/release_readiness.md, docs/review_request.md, results/README.md
Adds M47 contiguous-mode docs: fixed-band assumptions, occupancy-bitmap discovery, per-level storage, affected allocations, benchmark methodology, limitations, and reviewer guidance on replay-equivalence and cache-locality claims.
Unit tests and test helpers
tests/unit/test_matching_engine.cpp, tests/unit/test_order_book.cpp, tests/unit/test_risk_gateway.cpp
Storage-mode parity test includes Contiguous; added contiguous-specific tests for out-of-band GTC rejection, aggressor crossing, modify refusal vs crossing; added gateway regression test and test helper assertions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • div0rce/quant-systems-lab#108: Test-suite consolidation refactor touching the same matching-engine/order-book tests and helpers, related at the unit-test code level.

🐰 A hop through the price band we go,
With bitmaps that gleam and vectors that flow,
Contiguous queues in a fixed domain bright,
Cache-friendly storage for orders just right,
Benchmarks compare, results show no sleight!

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'perf: study contiguous order-book storage' accurately describes the main feature addition of a new storage mode and is clear, concise, and specific.
Description check ✅ Passed The PR description covers all required template sections: milestone M47, clear summary of changes, evidence with artifact digest, comprehensive test results, and relevant design notes about constraints and assumptions.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/m47-contiguous-order-book-storage

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dec326608c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/engine/order_book.cpp Outdated
div0rce added 2 commits June 12, 2026 10:35
Codex P2 on PR #119: a contiguous reprice whose re-add remainder would
rest out of band was refused inside OrderBook::modify after the engine
had already emitted OrderModified, so the event stream could report a
modify the book never applied. OrderBook::can_apply_modify now answers
the refusal before the event - MatchingEngine::modify no-ops without
emitting (mirroring how can_store_limit gates new_limit), the gateway
rejects such modifies with structured StorageExhausted, and the store
keeps the refusal as defense in depth so direct book callers also keep
the original order resting.

ContiguousStore moves to src/engine/contiguous_store.hpp: the extra
helpers pushed order_book.cpp to the brain-class function-count
threshold, and the M47 backend is a coherent unit of its own. Both
files score CodeScene 9.68 and the change-set quality gates pass; the
engine pre-gate also cleared the pre-existing new_market/modify code
duplication finding in matching_engine.cpp.
Artifact-only commit: results/pool_backed_storage.txt regenerated from
the clean source commit above so the recorded source digest matches the
modify pre-gate fix (Dirty inputs: no). All four storage modes still
produce identical event counts, resting totals, and last_seq on the
benchmark flow.
@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@codex review

codescene-delta-analysis[bot]

This comment was marked as outdated.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd2e36e1ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/engine/contiguous_store.hpp Outdated
@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@codex review

codescene-delta-analysis[bot]

This comment was marked as outdated.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7c40fe7e3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread results/pool_backed_storage.txt Outdated
@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@codex review

codescene-delta-analysis[bot]

This comment was marked as outdated.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: f0f268b54b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@div0rce

div0rce commented Jun 12, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
include/qsl/engine/order_book.hpp (1)

30-34: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Qualify the storage-equivalence claim.

Storage::Contiguous does change observable behavior for out-of-band GTC remainders and reprices, because can_store_limit(...) / can_apply_modify(...) can refuse them. The "never changes matching semantics" sentence should be narrowed to the declared in-band price-domain assumption.

Suggested wording
-    // is fixed at construction and never changes matching semantics or determinism; it only
-    // changes where resting-order state lives in memory.
+    // is fixed at construction. Within the declared contiguous price-domain assumption it does
+    // not change matching semantics or determinism; it only changes where resting-order state
+    // lives in memory.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@include/qsl/engine/order_book.hpp` around lines 30 - 34, The sentence
claiming Storage::Contiguous "never changes matching semantics or determinism"
is too broad; update the comment to qualify that Storage::Contiguous can change
observable behavior for out-of-band GTC remainders and reprices because
can_store_limit(...) and can_apply_modify(...) may refuse them, and narrow the
assertion to say it preserves matching semantics and determinism only under the
declared in-band price-domain assumption; reference Storage::Contiguous,
can_store_limit, and can_apply_modify in the revised comment so reviewers can
locate and verify the limitation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/engine/order_book.cpp`:
- Around line 370-380: The IntrusiveStore::add_limit path may call rest(...)
after matching and currently ignores rest failures, so preflight whether a GTC
remainder can be rested before calling OrderBook::match_incoming; mirror the
ContiguousStore::add_limit approach: if OrderBook::should_rest_limit(result,
input.tif) could leave a remainder, first validate pool capacity/can-rest for
input.id/input.side/input.price/result.remainder (using the same check
ContiguousStore uses) and if that preflight fails, avoid calling
OrderBook::match_incoming (or abort/return the appropriate error/indicator) so
the remainder is never silently dropped; update IntrusiveStore::add_limit and
any IntrusivePooled-specific helpers to perform this preflight check and
propagate failures instead of ignoring rest(...) return values.

---

Outside diff comments:
In `@include/qsl/engine/order_book.hpp`:
- Around line 30-34: The sentence claiming Storage::Contiguous "never changes
matching semantics or determinism" is too broad; update the comment to qualify
that Storage::Contiguous can change observable behavior for out-of-band GTC
remainders and reprices because can_store_limit(...) and can_apply_modify(...)
may refuse them, and narrow the assertion to say it preserves matching semantics
and determinism only under the declared in-band price-domain assumption;
reference Storage::Contiguous, can_store_limit, and can_apply_modify in the
revised comment so reviewers can locate and verify the limitation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2f9bd1fe-898c-4a46-9ff6-8f1e74ed0bf3

📥 Commits

Reviewing files that changed from the base of the PR and between 70b58fe and f0f268b.

📒 Files selected for processing (13)
  • PROGRESS.md
  • docs/architecture.md
  • docs/pool_backed_storage.md
  • include/qsl/engine/matching_engine.hpp
  • include/qsl/engine/order_book.hpp
  • results/pool_backed_storage.txt
  • src/engine/contiguous_store.hpp
  • src/engine/matching_engine.cpp
  • src/engine/order_book.cpp
  • src/gateway/order_gateway.cpp
  • tests/unit/test_matching_engine.cpp
  • tests/unit/test_order_book.cpp
  • tests/unit/test_risk_gateway.cpp
✅ Files skipped from review due to trivial changes (3)
  • results/pool_backed_storage.txt
  • docs/architecture.md
  • PROGRESS.md

Comment thread src/engine/order_book.cpp
div0rce added 3 commits June 15, 2026 09:28
CodeRabbit flagged that IntrusiveStore::add_limit ignored rest() failure:
a direct OrderBook{Storage::IntrusivePooled} caller that partially crossed
a GTC order and then ran out of pool capacity dropped the remainder, even
though the public add_limit contract rests it. It now runs can_store_limit
before matching (same guard the engine/gateway already applied, so their
behavior is unchanged), mirroring the contiguous-store fix.

Also narrow the Storage doc comment so the matching-semantics-preserved
claim is scoped to each mode's declared domain, add <utility> to
contiguous_store.hpp (std::move), and drop the now-unused <bit> from
order_book.cpp. Adds a direct-book regression filling the intrusive pool
and asserting a no-capacity bid is refused with maker liquidity intact.
Moving ContiguousStore to its own header surfaced its 5-argument
add_limit as a newly-introduced CodeScene finding in the new file. Hoist
the LimitInput bundle (id/side/price/quantity/tif) that IntrusiveStore
already used up to OrderBook scope and take it in both backends'
add_limit, so each storage entry point is single-argument and the
near-duplicate struct is removed. Behavior-preserving: the public
OrderBook::add_limit keeps its flat signature and only constructs the
bundle at the dispatch site.
Artifact-only: regenerate results/pool_backed_storage.txt from the clean
tree so its source digest matches the post-review source inputs
(Dirty inputs: no). All four storage modes still produce identical
event counts, resting totals, and last_seq on the benchmark flow.
codescene-delta-analysis[bot]

This comment was marked as outdated.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 169d61611c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/pool_backed_storage.md Outdated
Comment thread MILESTONES.md Outdated
Codex P2s on PR #119:
- docs/pool_backed_storage.md said contiguous was the fastest row, but
  the committed artifact has PMR 209.6 < contiguous 222.4 < baseline
  273.7 < intrusive 373.0 ns/cmd. Restate the actual ordering (PMR
  fastest, contiguous second, both ahead of baseline; intrusive slower
  than baseline) per the repo's measured-only benchmark discipline.
- MILESTONES.md assigned PR #119 to M45, but #119 is M47 and M45 landed
  as PR #117. Mark M45 merged (#117), and likewise the stale M44 (#115)
  and M46 (#118), and set M47 as the active PR #119 so resume/finish
  workflows route correctly.

Also repaired a fused PROGRESS.md decision-log line. Docs/roadmap only;
no source or artifact numbers changed.

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Health Improved (1 files improve in Code Health)

Our agent can fix these. Install it.

Gates Passed
6 Quality Gates Passed

View Improvements
File Code Health Impact Categories Improved
matching_engine.cpp 9.10 → 9.69 Code Duplication

Quality Gate Profile: Pay Down Tech Debt
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.

@div0rce

div0rce commented Jun 15, 2026

Copy link
Copy Markdown
Owner Author

@codex review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown

@div0rce Sure, I'll kick off a review of PR #119.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 6250a444b5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@div0rce div0rce merged commit 93d5062 into main Jun 15, 2026
8 checks passed
@div0rce div0rce deleted the feat/m47-contiguous-order-book-storage branch June 16, 2026 17:34
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