Skip to content

feat: add proactive rate-limit - #47

Merged
bobrykov merged 3 commits into
masterfrom
feat/proactive-rate-limit
Jul 12, 2026
Merged

feat: add proactive rate-limit#47
bobrykov merged 3 commits into
masterfrom
feat/proactive-rate-limit

Conversation

@bobrykov

Copy link
Copy Markdown
Contributor

No description provided.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ebd8800f-9d8b-499a-a47f-fa1ea377639c

📥 Commits

Reviewing files that changed from the base of the PR and between 24ff178 and 010927c.

📒 Files selected for processing (2)
  • src/stream/handler.rs
  • src/stream/rate_limit.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/stream/rate_limit.rs
  • src/stream/handler.rs

📝 Walkthrough

Walkthrough

Adds endpoint-keyed token-bucket rate limiting, exposes provider base URLs through ApiClient, and gates streaming attempts with cancellation-aware waits and a configurable max_wait.

Changes

Proactive stream rate limiting

Layer / File(s) Summary
Provider endpoint contract and exports
src/api.rs, src/provider/*.rs, src/stream.rs, CHANGELOG.md
Adds ApiClient::base_url(), implements it for provider clients, exports the new limiter types, and documents the capabilities.
Token-bucket limiter implementation
src/stream/rate_limit.rs
Implements continuous refill, per-endpoint buckets, disabled limiting, bounded waits, and unit tests for refill, isolation, and availability behavior.
Streaming gate integration
src/stream/handler.rs
Adds optional limiter configuration and gates stream attempts before SSE connection with cancellation-aware waiting, deadline clamping, max_wait handling, and integration tests.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant StreamHandler
  participant ApiClient
  participant RateLimiter
  participant TokenBucket
  participant SSE
  Client->>StreamHandler: start stream turn
  StreamHandler->>ApiClient: get base_url()
  StreamHandler->>RateLimiter: acquire(base_url)
  RateLimiter->>TokenBucket: take token
  TokenBucket-->>RateLimiter: permit or wait duration
  RateLimiter-->>StreamHandler: permit or wait
  StreamHandler->>SSE: open stream
Loading

Possibly related PRs

  • dch-labs/loopctl#44: Modifies the same streaming rate-limit integration points for mid-stream detection and retry/backoff handling.
  • dch-labs/loopctl#46: Modifies stream retry and rate-limit control flow adjacent to the new proactive gating behavior.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding proactive rate-limiting support.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 50.00%.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/proactive-rate-limit

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (2)
src/stream/handler.rs (2)

1330-1390: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

gate_on_rate_limit ignores total_deadline, so a turn can overrun its configured total_stream_timeout.

try_stream already receives total_deadline and threads it into process_events, but gate_on_rate_limit (called first, at Line 1339) doesn't receive it at all — its wait loop is bounded only by the limiter's own max_wait (default 30s). If total_stream_timeout is shorter than max_wait (or the gate wait is large relative to remaining budget), the turn can block in the gate well past the deadline before process_events gets a chance to fail with TotalTimeout. This is inconsistent with the precedent already established in this same file for rate-limit backoff sleeps, which are explicitly clamped to the deadline so a large Retry-After "cannot overrun the turn budget."

♻️ Proposed fix: thread `total_deadline` through the gate
     async fn try_stream<C: ApiClient>(
         &self,
         client: &C,
         conversation: Vec<Message>,
         system: Option<String>,
         tool_schemas: Option<Vec<ToolSchema>>,
         cancel: &Arc<CancelSignal>,
         total_deadline: Option<Instant>,
     ) -> Result<StreamTurnResult, StreamHandlerError> {
-        self.gate_on_rate_limit(client, cancel).await?;
+        self.gate_on_rate_limit(client, cancel, total_deadline).await?;
         let stream = client.stream_messages(conversation, system, tool_schemas);
         self.process_events(stream, cancel, total_deadline).await
     }

     async fn gate_on_rate_limit<C: ApiClient>(
         &self,
         client: &C,
         cancel: &Arc<CancelSignal>,
+        total_deadline: Option<Instant>,
     ) -> Result<(), StreamHandlerError> {
         let Some(limiter) = &self.rate_limiter else {
             return Ok(());
         };
         let key = client.base_url();
         let max_wait = limiter.max_wait();
         let mut waited = Duration::ZERO;
         loop {
             match limiter.acquire(&key) {
                 Ok(()) => return Ok(()),
                 Err(wait) => {
-                    if waited >= max_wait {
+                    if waited >= max_wait || Self::deadline_exceeded(total_deadline) {
                         return Ok(());
                     }
                     let remaining = max_wait.checked_sub(waited).unwrap_or(Duration::ZERO);
-                    let capped = wait.min(remaining);
+                    let mut capped = wait.min(remaining);
+                    if let Some(deadline) = total_deadline {
+                        if let Some(left) = deadline.checked_duration_since(Instant::now()) {
+                            capped = capped.min(left);
+                        }
+                    }
                     tokio::select! {
                         () = tokio::time::sleep(capped) => {}
                         () = cancel.notified() => return Err(StreamHandlerError::Cancelled),
                     }
                     waited = waited.saturating_add(capped);
                 }
             }
         }
     }
🤖 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 `@src/stream/handler.rs` around lines 1330 - 1390, Update try_stream and
gate_on_rate_limit to accept and enforce total_deadline while waiting for
rate-limit tokens. Clamp each rate-limit sleep to the remaining turn budget,
preserve cancellation handling, and return the existing TotalTimeout error when
the deadline expires so the gate cannot overrun total_stream_timeout.

1006-1014: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

RateLimitConfig::requests_per_minute no longer does proactive throttling
This field’s doc still says it “proactively throttle[s] outgoing requests,” but the runtime only gates requests through with_rate_limiter(). Either wire new()/with_rate_limit_config() to build a limiter from this value, or update the doc to point users at with_rate_limiter() instead.

🤖 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 `@src/stream/handler.rs` around lines 1006 - 1014, Update the documentation for
RateLimitConfig::requests_per_minute to describe its actual behavior and direct
users to StreamHandler::with_rate_limiter() for proactive throttling. Do not
claim that the field itself proactively throttles requests, and leave the
existing runtime configuration unchanged.
🤖 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/stream/rate_limit.rs`:
- Around line 57-83: Update TokenBucket::take_at (and the take path if it
contains equivalent logic) to detect refill_per_sec <= 0.0 before calculating
the wait duration, returning the existing Err result for an empty bucket instead
of passing an infinite value to Duration::from_secs_f64. Preserve normal refill
behavior for positive-capacity buckets.

---

Outside diff comments:
In `@src/stream/handler.rs`:
- Around line 1330-1390: Update try_stream and gate_on_rate_limit to accept and
enforce total_deadline while waiting for rate-limit tokens. Clamp each
rate-limit sleep to the remaining turn budget, preserve cancellation handling,
and return the existing TotalTimeout error when the deadline expires so the gate
cannot overrun total_stream_timeout.
- Around line 1006-1014: Update the documentation for
RateLimitConfig::requests_per_minute to describe its actual behavior and direct
users to StreamHandler::with_rate_limiter() for proactive throttling. Do not
claim that the field itself proactively throttles requests, and leave the
existing runtime configuration unchanged.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73db8823-39fb-4c4c-a1ea-2150cfc30d67

📥 Commits

Reviewing files that changed from the base of the PR and between bf2c5b1 and 24ff178.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • src/api.rs
  • src/provider/anthropic.rs
  • src/provider/gemini.rs
  • src/provider/openai.rs
  • src/stream.rs
  • src/stream/handler.rs
  • src/stream/rate_limit.rs

Comment thread src/stream/rate_limit.rs
@bobrykov
bobrykov merged commit 050469d into master Jul 12, 2026
8 checks passed
@bobrykov
bobrykov deleted the feat/proactive-rate-limit branch August 4, 2026 05:23
bobrykov added a commit that referenced this pull request Aug 18, 2026
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