Skip to content

fix(collector): overlap bounded trade polling - #37

Merged
proerror77 merged 3 commits into
mainfrom
codex/polymarket-rust-concurrent-polls
Jul 15, 2026
Merged

fix(collector): overlap bounded trade polling#37
proerror77 merged 3 commits into
mainfrom
codex/polymarket-rust-concurrent-polls

Conversation

@proerror77

@proerror77 proerror77 commented Jul 15, 2026

Copy link
Copy Markdown
Owner

Tokyo runtime evidence showed the 192-poll bounded cycle still missed the 180-second bootstrap deadline because Data API requests remained serial. The formal shadow gate failed closed and left Python production untouched.\n\nThis change keeps the 192-market cycle budget and 100ms per-request delay, but overlaps at most four trade requests. Health records and validates the concurrency bound. The request fan-out remains fixed and cannot exceed the per-cycle budget.\n\nVerified locally:\n- hft-collector lib: 82 passed\n- polymarket-raw-ops CLI: 1 passed\n- strict targeted Clippy: passed\n- Aliyun control-plane shell test: passed with exit 0\n- targeted rustfmt and diff check: passed\n\nNo production service, ACK node, ClickHouse instance, or trading ECS was started by this PR.

Summary by CodeRabbit

  • New Features

    • Added configurable concurrency for Polymarket trade polling, with a default maximum of four simultaneous requests.
    • Added request pacing controls to maintain at least 100 ms between request starts.
    • Health reporting now includes trade polling concurrency and request spacing.
  • Bug Fixes

    • Added validation to reject unsafe or out-of-range polling configurations.
  • Documentation

    • Documented request pacing, concurrency, and per-cycle processing limits.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@proerror77, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 58221bc5-11a7-40b7-a49a-7f9682bcd32c

📥 Commits

Reviewing files that changed from the base of the PR and between b3ff4fe and f576eca.

📒 Files selected for processing (4)
  • deployment/aliyun/README.md
  • deployment/aliyun/polymarket-rust-health-policy.jq
  • deployment/aliyun/test-polymarket-raw-ops-control-plane.sh
  • rust_hft/tools/collector/src/polymarket_raw.rs
📝 Walkthrough

Walkthrough

The Polymarket reference collector now supports bounded concurrent trade polling with shared request-start spacing. CLI configuration, runtime health output, deployment validation, control-plane tests, and Aliyun documentation reflect the new concurrency and minimum-spacing constraints.

Changes

Bounded Polymarket trade polling

Layer / File(s) Summary
Polling configuration and CLI wiring
rust_hft/tools/collector/src/polymak...
ReferenceConfig and the collect-reference CLI add concurrency defaults, validation against configured limits, and minimum request spacing checks.
Concurrent polling orchestration
rust_hft/tools/collector/src/polymak...
Trade targets are chunked and fetched with bounded concurrency; a shared mutex coordinates request start times before results are applied deterministically to collector state.
Health reporting and deployment validation
rust_hft/tools/collector/src/polymak..., deployment/aliyun/*
Health output, JQ policy checks, control-plane mutations, and Aliyun documentation describe and validate concurrency, request spacing, and chunk bounds.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant collect_once
  participant ReferenceCollector
  participant DataAPI
  participant next_state
  collect_once->>ReferenceCollector: Schedule bounded trade fetches
  ReferenceCollector->>ReferenceCollector: Wait for shared request slot
  ReferenceCollector->>DataAPI: Start spaced trade request
  DataAPI-->>ReferenceCollector: Return market trades
  ReferenceCollector->>next_state: Apply validated result
Loading

Possibly related PRs

  • proerror77/monday#34: Introduces the same Rust Polymarket collector configuration and trade-fetching code extended by this change.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: overlapping trade polling with bounded concurrency.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/polymarket-rust-concurrent-polls

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.

@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: 2bd03b298a

ℹ️ 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 on lines +1489 to +1490
.collect::<Vec<_>>()
.await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Process trade fetches as they complete

When a cycle selects many busy markets, this collect retains every fetched Vec<Value> until all selected requests finish. fetch_trades can return two 10k-row pages per market, so with the 192-market budget the peak memory becomes the whole cycle's raw trade payloads rather than the four in-flight requests; the deployed service is memory-capped, so a burst of large markets can OOM/restart before any results are applied. Consider draining the buffered stream as results arrive or otherwise bounding stored results.

Useful? React with 👍 / 👎.

}
(market_id, result)
})
.buffer_unordered(self.config.max_concurrent_trade_polls)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the global request pacing

With the default concurrency of four and a fast trades endpoint, buffer_unordered polls four fetch futures immediately, and the 100ms sleep inside each future only delays replacement of that slot; this changes the old per-market pacing from roughly one trade request every 100ms to bursts of up to four requests at once (and then up to four more per delay interval). In environments where per_market_delay is the rate-limit guard for the Polymarket Data API, this can trigger 429s/stale trade health even though the configured delay appears unchanged.

Useful? React with 👍 / 👎.

Comment on lines +118 to +119
if self.max_concurrent_trade_polls > self.max_trade_polls_per_cycle {
bail!("concurrent trade polls cannot exceed the per-cycle trade poll budget");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve reduced trade-poll budgets

When an operator lowers max_trade_polls_per_cycle below the new default concurrency of 4 (for example --max-trade-polls-per-cycle 1 for throttled testing), this validation now rejects a previously valid bounded configuration unless they also discover and set the new concurrency flag. If the budget is intended to remain independently tunable, the default concurrency should be clamped to the budget or the check should account for the defaulted value.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Intentional fail-closed configuration contract: when an operator lowers the per-cycle budget, they must also lower the explicit concurrency cap. We do not silently clamp because health evidence must report the configured/effective value identically; both config validation and the health policy enforce concurrency <= budget, and the reduced-budget case is covered by a unit test.

@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

🧹 Nitpick comments (1)
rust_hft/tools/collector/src/polymarket_raw.rs (1)

2233-2272: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy lift

Exercise the runtime scheduler, not only chunk partitioning.

Add an async regression test that records peak in-flight requests and request-start spacing, including a market requiring its second page. These are the central new runtime guarantees.

🤖 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 `@rust_hft/tools/collector/src/polymarket_raw.rs` around lines 2233 - 2272, The
existing target_chunks_preserve_order_and_bound_retained_selected_results test
only validates partitioning; add an async regression test that drives the
runtime scheduler and includes a market requiring a second page. Instrument the
request path to record peak in-flight requests and request-start timestamps,
then assert the scheduler enforces the configured concurrency and minimum
spacing while preserving correct multi-page processing.
🤖 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 `@rust_hft/tools/collector/src/polymarket_raw.rs`:
- Around line 1523-1547: Enforce the 180,000 ms absolute bootstrap/cycle
deadline around the trade-fetch loop in the collector flow at
rust_hft/tools/collector/src/polymarket_raw.rs:1523-1547, or validate the
configured timeout, budget, and concurrency so completion cannot exceed it.
Update the health policy at
deployment/aliyun/polymarket-rust-health-policy.jq:7-10 to reject
cycle_duration_ms values above 180,000, and extend
deployment/aliyun/test-polymarket-raw-ops-control-plane.sh:354-358 with a
mutation setting cycle_duration_ms to 180001 and asserting rejection.

---

Nitpick comments:
In `@rust_hft/tools/collector/src/polymarket_raw.rs`:
- Around line 2233-2272: The existing
target_chunks_preserve_order_and_bound_retained_selected_results test only
validates partitioning; add an async regression test that drives the runtime
scheduler and includes a market requiring a second page. Instrument the request
path to record peak in-flight requests and request-start timestamps, then assert
the scheduler enforces the configured concurrency and minimum spacing while
preserving correct multi-page processing.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: ad6471a0-df9c-40ca-9004-bdeba4a0ae8c

📥 Commits

Reviewing files that changed from the base of the PR and between 5d23a60 and b3ff4fe.

📒 Files selected for processing (5)
  • deployment/aliyun/README.md
  • deployment/aliyun/polymarket-rust-health-policy.jq
  • deployment/aliyun/test-polymarket-raw-ops-control-plane.sh
  • rust_hft/tools/collector/src/bin/polymarket-raw-ops.rs
  • rust_hft/tools/collector/src/polymarket_raw.rs

Comment thread rust_hft/tools/collector/src/polymarket_raw.rs
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