Skip to content

fix: exclude failed requests from memory rate limit success count - #6528

Open
feitianbubu wants to merge 1 commit into
QuantumNous:mainfrom
feitianbubu:pr/630b7986c
Open

fix: exclude failed requests from memory rate limit success count#6528
feitianbubu wants to merge 1 commit into
QuantumNous:mainfrom
feitianbubu:pr/630b7986c

Conversation

@feitianbubu

@feitianbubu feitianbubu commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

  1. 内存限流的版最大成功请求数将失败也计入了总数
  2. 客户端实际成功数远没到配置值就开始收 429,且响应是空 body(429),不好排查问题

修法:

  • 失败的请求不再计入成功请求数
  • 两处空 body 429 换成 abortWithOpenAiMessage,文案与 Redis 一致。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • 无独立 Issue,现象与根因见上面描述

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

设置:
image

成功数限制(不含失败):
image

总请求数限制:
image

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The in-memory rate limiter adds a non-counting eligibility check. Model middleware uses it before downstream execution and records only successful requests afterward. Tests verify failed responses do not consume the success quota and successful requests eventually receive HTTP 429.

Changes

Model rate-limit success accounting

Layer / File(s) Summary
Non-mutating limiter eligibility check
common/rate-limit.go
Adds CanRequest to evaluate stored timestamps without recording a request.
Middleware success flow and validation
middleware/model-rate-limit.go, middleware/model_rate_limit_test.go
Checks success capacity before c.Next(), records successful requests afterward, uses the localized 429 response, and tests failed-request handling.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant memoryRateLimitHandler
  participant InMemoryRateLimiter
  participant DownstreamHandler
  Client->>memoryRateLimitHandler: Send model request
  memoryRateLimitHandler->>InMemoryRateLimiter: CanRequest success key
  InMemoryRateLimiter-->>memoryRateLimitHandler: Return eligibility
  memoryRateLimitHandler->>DownstreamHandler: c.Next()
  DownstreamHandler-->>memoryRateLimitHandler: Return response status
  memoryRateLimitHandler->>InMemoryRateLimiter: Request success key for successful response
  memoryRateLimitHandler-->>Client: Return response or HTTP 429
Loading

Suggested reviewers: calcium-ion

Poem

I’m a bunny guarding the gate,
Failed hops no longer count toward fate.
Check first, then tally the cheer,
Success fills the quota crystal-clear.
When full, 429 says, “Not here!”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: failed requests are excluded from the in-memory success rate-limit count.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 4

🤖 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 `@middleware/model_rate_limit_test.go`:
- Around line 39-44: Replace the wall-clock-derived userID in
TestModelMemoryRateLimitSuccessCountIgnoresFailedRequests with deterministic
isolation: reset or inject the process-global limiter for the test, or generate
IDs through an atomic counter in a reserved namespace. Ensure repeated and
parallel test runs cannot reuse stale quota state.
- Around line 65-68: Update the 429 response assertions in the do test to verify
the JSON contract rather than only searching response text: assert an
application/json content type and decode or inspect the body to confirm the
expected JSON field and value contain the rate-limit message.

In `@middleware/model-rate-limit.go`:
- Around line 147-156: Update the success-limit flow around CanRequest and the
subsequent accounting after c.Next() to reserve capacity atomically before
admitting a request, then commit the reservation only when the request succeeds
and roll it back otherwise. Ensure concurrent requests cannot collectively
exceed successMaxCount, and handle the recording operation’s result rather than
ignoring it; extend coverage with a concurrent regression test for this race.
- Around line 147-156: Update the success-rate-limit flow around CanRequest and
the subsequent success-count Request call to bypass both in-memory limiter
operations when successMaxCount is zero, preserving the Redis zero-value
contract and allowing successful requests without creating limiter entries.
🪄 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: 85969bbe-c029-428e-b22b-cda7c70bb582

📥 Commits

Reviewing files that changed from the base of the PR and between 66ee6b8 and 17455a6.

📒 Files selected for processing (3)
  • common/rate-limit.go
  • middleware/model-rate-limit.go
  • middleware/model_rate_limit_test.go

Comment on lines +39 to +44
// 成功数限制只统计成功请求,失败请求不占配额;拒绝时返回 JSON 错误体而非空 429。
func TestModelMemoryRateLimitSuccessCountIgnoresFailedRequests(t *testing.T) {
gin.SetMode(gin.TestMode)

// 限流器是进程级全局且无重置接口,user id 每次唯一才能保证 -count=2 复跑
userID := int(time.Now().UnixNano() % 1_000_000_000)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Use deterministic isolation for the global limiter state.

A wall-clock-derived ID can collide with another test or repeated execution, reusing stale process-global quota state. Reset/inject the limiter for the test, or allocate IDs from a reserved namespace using an atomic counter.

As per coding guidelines, backend tests should prefer deterministic inputs and explicit state.

🤖 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 `@middleware/model_rate_limit_test.go` around lines 39 - 44, Replace the
wall-clock-derived userID in
TestModelMemoryRateLimitSuccessCountIgnoresFailedRequests with deterministic
isolation: reset or inject the process-global limiter for the test, or generate
IDs through an atomic counter in a reserved namespace. Ensure repeated and
parallel test runs cannot reuse stale quota state.

Source: Coding guidelines

Comment on lines +65 to +68
limited := do(http.StatusOK)
require.Equal(t, http.StatusTooManyRequests, limited.Code)
assert.Contains(t, limited.Body.String(), "您已达到请求数限制", "429 must carry the same error message as the Redis path")
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the JSON response contract, not only the message text.

assert.Contains would pass for a plain-text 429 containing the same phrase. Also assert an application/json content type and validate the expected JSON field/body shape.

🤖 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 `@middleware/model_rate_limit_test.go` around lines 65 - 68, Update the 429
response assertions in the do test to verify the JSON contract rather than only
searching response text: assert an application/json content type and decode or
inspect the body to confirm the expected JSON field and value contain the
rate-limit message.

Comment on lines +147 to +156
// 2. 检查成功请求数限制:只检查不计数,成功后才在步骤4计入
if !inMemoryRateLimiter.CanRequest(successKey, successMaxCount, duration) {
abortWithOpenAiMessage(c, http.StatusTooManyRequests, fmt.Sprintf("您已达到请求数限制:%d分钟内最多请求%d次", setting.ModelRequestRateLimitDurationMinutes, successMaxCount))
return
}

// 3. 处理请求
c.Next()

// 4. 如果请求成功,记录到实际的成功请求计数中
// 4. 如果请求成功,记录到成功请求计数中

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Make success-limit admission atomic with success accounting.

CanRequest releases the limiter lock before c.Next(), so concurrent requests can all pass the check while capacity is available. They are then all admitted, even though only some later Request calls can be recorded; the return value from that recording is ignored. Use reservation/commit/rollback semantics or track in-flight reservations so successful traffic cannot exceed the configured quota. The current sequential regression test will not catch this race.

🤖 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 `@middleware/model-rate-limit.go` around lines 147 - 156, Update the
success-limit flow around CanRequest and the subsequent accounting after
c.Next() to reserve capacity atomically before admitting a request, then commit
the reservation only when the request succeeds and roll it back otherwise.
Ensure concurrent requests cannot collectively exceed successMaxCount, and
handle the recording operation’s result rather than ignoring it; extend coverage
with a concurrent regression test for this race.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files matching middleware/model-rate-limit.go:"
fd -a 'model-rate-limit\.go$' . || true

file="$(fd 'model-rate-limit\.go$' . | head -n 1 || true)"
if [ -z "${file:-}" ]; then
  echo "Target file not found"
  exit 1
fi

echo "File: $file"
wc -l "$file"
echo "--- outline ---"
ast-grep outline "$file" --view compact || true
echo "--- relevant lines 1-220 ---"
sed -n '1,220p' "$file" | cat -n

echo "--- related successMaxCount occurrences ---"
rg -n "successMaxCount|ModelRequestRateLimitDurationMinutes|ModelSuccessRateLimit|rate.*limit|InMemoryRateLimiter|Request\\(|CanRequest" "$file"

Repository: QuantumNous/new-api

Length of output: 9826


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "locating limiter package files:"
fd -a '.*\.go$' common/limiter || true

echo "--- common/limiter files sizes ---"
while IFS= read -r f; do wc -l "$f"; done < <(fd '.*\.go$' common/limiter)

echo "--- common/limiter outline/contents ---"
while IFS= read -r f; do
  echo "===== $f ====="
  sed -n '1,260p' "$f" | cat -n
done < <(fd '.*\.go$' common/limiter)

echo "--- inMemoryRateLimiter declarations/usages ---"
rg -n "inMemoryRateLimiter|CanRequest|func .*Request|type .*Limiter" common middleware

Repository: QuantumNous/new-api

Length of output: 321


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- common/limiter/limiter.go ---"
wc -l common/limiter/limiter.go
sed -n '1,260p' common/limiter/limiter.go | cat -n

echo "--- inMemoryRateLimiter declarations/usages ---"
rg -n "inMemoryRateLimiter|CanRequest|func .*Request|type .*Limiter" common middleware

Repository: QuantumNous/new-api

Length of output: 7278


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- common/rate-limit.go ---"
wc -l common/rate-limit.go
sed -n '1,140p' common/rate-limit.go | cat -n

echo "--- model_rate_limit_test.go relevant lines ---"
sed -n '1,140p' middleware/model_rate_limit_test.go | cat -n

Repository: QuantumNous/new-api

Length of output: 5615


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
def can_request(store, key, max_request_num, now, duration):
    queue = store.get(key)
    if queue is None or len(queue) < max_request_num:
        return True
    return (now - queue[0]) >= duration

def request(store, key, max_request_num, now, duration):
    now = now
    queue = store.get(key)
    if queue is not None:
        if len(queue) < max_request_num:
            store[key] = queue + [now]
            return True
        else:
            if now - queue[0] >= duration:
                store[key] = queue[1:] + [now]
                return True
            else:
                return False
    else:
        store[key] = [now]
        return True

def memory_handler(store, key_prefix, user_id, downstream_statuses, duration):
    store[:] = {}
    for status in downstream_statuses:
        success_key = key_prefix + str(user_id)
        allowed = can_request(store, success_key, 0, 100, duration)
        if not allowed:
            yield "abort", 429
            continue
        # process
        if status < 400:
            request(store, success_key, 0, 100, duration)
        yield "processed", status, store.get(success_key)

statuses = [200, 200, 200]
events = list(memory_handler([], "model_success_", 1, statuses, 60))
for e in events:
    print(e)
PY

Repository: QuantumNous/new-api

Length of output: 370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
def can_request(store, key, max_request_num, now, duration):
    queue = store.get(key)
    if queue is None or len(queue) < max_request_num:
        return True
    return (now - queue[0]) >= duration

def request(store, key, max_request_num, now, duration):
    queue = store.get(key)
    if queue is not None:
        if len(queue) < max_request_num:
            store[key] = queue + [now]
            return True
        else:
            if now - queue[0] >= duration:
                store[key] = queue[1:] + [now]
                return True
            else:
                return False
    else:
        store[key] = [now]
        return True

def memory_handler(store, key_prefix, user_id, downstream_statuses, duration):
    for status in downstream_statuses:
        success_key = key_prefix + str(user_id)
        allowed = can_request(store, success_key, 0, 100, duration)
        if not allowed:
            yield "abort", 429
            continue
        if status < 400:
            request(store, success_key, 0, 100, duration, )
        yield "processed_after", status, store.get(success_key)

statuses = [200, 200, 200]
events = list(memory_handler({}, "model_success_", 1, statuses, 60))
for e in events:
    print(e)
PY

Repository: QuantumNous/new-api

Length of output: 219


Guard the in-memory success limiter when successMaxCount is zero.

In-memory handling mirrors the Redis zero-value contract for total limits, but the success path calls CanRequest and Request with successMaxCount == 0, so a single successful request records an entry and subsequent successful requests are rejected until expiry. Skip both calls when successMaxCount == 0, or document and enforce a 0-as-1 request limit consistently.

🤖 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 `@middleware/model-rate-limit.go` around lines 147 - 156, Update the
success-rate-limit flow around CanRequest and the subsequent success-count
Request call to bypass both in-memory limiter operations when successMaxCount is
zero, preserving the Redis zero-value contract and allowing successful requests
without creating limiter entries.

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