Skip to content

fix: handle expired keys in Redis rate limit - #8124

Open
sstar16 wants to merge 2 commits into
QuantumNous:mainfrom
sstar16:fix/redis-rate-limit-expiry
Open

sstar16 wants to merge 2 commits into
QuantumNous:mainfrom
sstar16:fix/redis-rate-limit-expiry

Conversation

@sstar16

@sstar16 sstar16 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Agent

  • Tool: DeepSeek Harness
  • Tool version: k3.1-pro
  • Model (full id): k3.1-pro
  • Host (CLI / IDE / GitHub coding agent / other): DeepSeek Harness coding agent on Windows 11 with PowerShell
  • Date (UTC): 2026-10-30
  • Code provenance: AI-assisted implementation by a non-core contributor;sstar16 与仓库近期核心作者不同。

Links

User request

  • Verbatim: “你觉得我们还有合适的pr可以提吗?能提尽量提”
  • Later constraints or corrections from the user (quote, or none): 无。

Out of scope — refuse

  • Coding Plan

  • Reverse-engineered channels

  • Third-party API wrappers

  • Codex channel-type changes, or compatibility from exposing Codex as a general-purpose API

  • Codex API-specific protocol or behavior treated as standard OpenAI API behavior

  • Pass-through-only forwarding

  • Third-party hosting sites, relay services, or API services

  • Usage, configuration, or integration

  • Matched: no

  • If yes, what was told to the user (stop here; do not open a PR): 不适用。

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user (stop here): 不适用。

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

  • Actual behavior: key 在 LLEN 与 LINDEX 之间过期时,LINDEX 返回 redis.Nil;当前代码忽略错误并解析空字符串,最终返回 HTTP 500。
  • Impact: 没有成功记录的请求被误拒;其他 LINDEX 后端错误也被误报为时间格式错误。
  • Frequency: 竞态窗口非每次出现,但通过 go-redis hook 在 LLEN 后删除 key 可确定性复现。
  • Evidence that the problem is in new-api rather than the client or upstream: 错误发生在上游调用之前;middleware/model-rate-limit.go 对 LIndex(...).Result() 使用空白标识符丢弃错误。直接调用该函数即可复现,不依赖客户端或 provider。
  • Applicable types and their fields: relay/deployment,Redis 模型限流;不涉及 billing 或 frontend。

Change

捕获 LINDEX 错误:redis.Nil 按列表不存在处理并返回 (true, nil);其他错误原样返回,继续 fail closed。既有 middleware/model_rate_limit_test.go 增加 hook 驱动的确定性回归测试,不改变限流算法。

Research

Duplicate / prior art

Docs and code

  • https://docs.newapi.ai/ : 查阅文档入口与限流相关内容,未见该竞态属于预期行为的说明。
  • https://deepwiki.com/QuantumNous/new-api : 遇到 Vercel 429 安全验证,未将其内容作为依据。
  • README / repo docs: 阅读根 AGENTS.md、.agents/github/ISSUE.md 和 .agents/github/PR.md。
  • Code paths and what they imply for this change: checkRedisRateLimit 只在 LLEN 达到上限后读取最旧时间戳;redis.Nil 表示列表已不存在,与 LLEN=0 的现有放行语义一致。

Alternatives considered

  • Option A: 所有 LINDEX 错误都放行,会掩盖真实 Redis 故障。
  • Option B: 只对 redis.Nil 放行,其他错误原样返回。
  • Why this approach: 保持真实故障 fail closed,同时修复 key 过期的误拒绝,改动最小。

Files

Path Why
middleware/model-rate-limit.go 捕获并分类 LINDEX 错误。
middleware/model_rate_limit_test.go 在现有限流测试文件中增加确定性过期竞态回归。

Behavior

  • Before: key 在两次读取之间消失时解析空时间并返回 500;真实 LINDEX 错误也被吞掉。
  • After: 已消失的 key 按无成功记录放行;其他读取错误保留并返回。
  • Explicit non-goals / leftover work: 不修改整体滑动窗口、LLEN/LPUSH 原子性、成功请求记录策略、计费或其他 Redis 操作。

Verification

  • Commands and results:
    • 修复前:go test -mod=readonly ./middleware -run '^TestCheckRedisRateLimitAllowsKeyExpiringBeforeTimestampRead$' -count=1 稳定失败,返回 parsing time "" ... cannot parse "" as "2006"。
    • 修复后:同一命令通过,输出 ok github.com/QuantumNous/new-api/middleware 0.697s。
    • 未修改 main 工作树:go test -mod=readonly ./middleware -run '^TestCheckRedisRateLimitPreservesTimestampReadErrors$' -count=1 失败,注入的 LINDEX 错误被吞掉并返回 nil;修复后该用例通过。
    • 两个聚焦回归:go test -mod=readonly ./middleware -run '^TestCheckRedisRateLimit(AllowsKeyExpiringBeforeTimestampRead|PreservesTimestampReadErrors)$' -count=1 通过,输出 ok github.com/QuantumNous/new-api/middleware 0.741s。
    • go test -mod=readonly ./middleware -run '^(TestCheckRedisRateLimit.*|TestModelRedisRateLimit.*|TestModelRateLimit.*|TestModelMemoryRateLimit.*)$' -count=1 通过,输出 ok github.com/QuantumNous/new-api/middleware 0.632s。
    • go vet ./middleware 退出码 0,无诊断。
    • git diff --check 无输出;提交仅含上述两个文件。
  • Manual steps and observed result: 逐行复核差异,确认生产改动仅分类 LINDEX 错误,测试通过 hook 在 LLEN 后删除 key;无内部地址、配置、凭据或用户正文。
  • UI: 无 UI 变化,因此无截图或录屏。
  • Tests added or updated, or why none: 更新既有 middleware/model_rate_limit_test.go,覆盖 LLEN 后、LINDEX 前 key 消失,以及非 redis.Nil 的 LINDEX 错误必须原样返回两个确定性场景。
  • Databases / providers / platforms exercised: Windows 11 amd64、Go 1.26.10、miniredis;未调用真实 Redis、主数据库或 provider。
  • Not verified: 未做真实 Redis 的完整 HTTP 端到端验证;-race 因本机缺少 CGO 编译器未运行。完整 go test ./middleware 另有 TestAccessAndPanicLogsFollowLogRotation 的 Windows 日志文件占用清理失败,本 PR 不将其计为通过。

Risks

  • Failure modes: 若 key 消失被误判,本分支会放行;这与现有 LLEN=0 语义一致。其他 Redis 错误不会被放行。
  • Billing / quota / auth impact: 无计费或鉴权代码变化;只影响达到成功请求上限后读取历史时间的错误分支。
  • Follow-ups: 整体并发准入与 LLEN/LPUSH 原子性继续在 redisRateLimiter 高并发下存在竞态条件导致限流失效 #2841 等既有线程处理,不在本 PR 扩张。

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

Summary by CodeRabbit

  • Bug Fixes
    • Requests are no longer incorrectly blocked when rate-limit data expires during a check.
    • Errors encountered while checking rate-limit data are now handled explicitly, preventing requests from being allowed based on an invalid timestamp.

Treat redis.Nil from LINDEX as an empty success-history window and preserve other errors, avoiding spurious HTTP 500s when keys expire between LLEN and LINDEX.

Add deterministic miniredis regression coverage. Verified the focused model rate-limit test suite, go vet, and git diff --check.
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 74fac383-7b59-4ed7-bb04-58bc172a5dd4
Commits

Reviewing files that changed from the base of the PR and between 3f3ee01 and 1889c02.

Files selected for processing: 1
  • middleware/model_rate_limit_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Walkthrough

The Redis model rate-limit check allows a request when its timestamp list expires before the timestamp lookup. It returns other lookup errors. Tests cover both behaviors.

Changes

Redis model rate-limit handling

Layer / File(s) Summary
Handle missing timestamp entries
middleware/model-rate-limit.go, middleware/model_rate_limit_test.go
checkRedisRateLimit allows the request when LIndex returns redis.Nil and returns other lookup errors. Tests simulate key deletion after LLEN and an error after LINDEX.

Priority: Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 1889c

Expired rate-limit keys no longer block requests, and successful requests remain counted. No merge-blocking issue was identified.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: handling expired Redis rate-limit keys.
Linked Issues check Passed 直接关联的 #8123 已关闭,仅提供历史背景。根据规则,该 issue 不产生本 PR 的编码要求。变更仍与其背景一致:checkRedisRateLimit 分类处理 LINDEX 错误,并以测试覆盖 key 过期和错误传播场景。
Out of Scope Changes check Passed 变更仅涉及 middleware/model-rate-limit.go 和对应测试文件。生产代码只处理 LINDEX 的 redis.Nil 与其他错误。测试直接验证该行为。未见整体限流原子性、计费、前端或其他无关功能变更。
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 2 files.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the list with care,
A missing key means room is there.
Other errors keep their name,
Tests now guard each lookup game.
Soft paws hop; the checks stay fair.

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

Verify injected non-Nil LINDEX failures remain errors instead of being swallowed, alongside the existing key-expiry regression.

Confirmed the new case fails on the unmodified main worktree and passes with the fix; reran the focused model rate-limit suite and go vet.
soulteary added a commit to soulteary/yunqi that referenced this pull request Nov 22, 2026
Delegate configured channel RPM and concurrency to Redis while keeping
local discovered limits and cooldowns. Do not reintroduce the channel's
configured defaults as local key/quota limits. Preserve explicit key
safeguards even when a background refresher reapplies inherited settings.

Add a real two-node regression that repeatedly rejects node B while A
holds global capacity, then verifies B can send immediately after release
without waiting for a non-refundable local RPM window.

Refs: soulteary/yunqi PR #101 #101
Refs: QuantumNous/new-api issue #1730 QuantumNous/new-api#1730
Refs: QuantumNous/new-api PR #6583 QuantumNous/new-api#6583
Refs: QuantumNous/new-api PR #8124 QuantumNous/new-api#8124
soulteary added a commit to soulteary/yunqi that referenced this pull request Nov 22, 2026
soulteary added a commit to soulteary/yunqi that referenced this pull request Nov 22, 2026
docs: finalize community improvement batches and validation

Document eight implemented capabilities, review fixes, exact commits, CI evidence and upstream correspondence. Preserve identity, Redis and evaluation boundaries, and provide the model governance lifecycle/API guide.

All functional PRs were reviewed and merged after successful regression tests and Verify CI. The running checkout and services were not changed.

Refs: QuantumNous/new-api issue #1730 QuantumNous/new-api#1730
Refs: QuantumNous/new-api issue #2841 QuantumNous/new-api#2841
Refs: QuantumNous/new-api issue #3240 QuantumNous/new-api#3240
Refs: QuantumNous/new-api PR #3345 QuantumNous/new-api#3345
Refs: QuantumNous/new-api issue #4328 QuantumNous/new-api#4328
Refs: QuantumNous/new-api PR #4329 QuantumNous/new-api#4329
Refs: QuantumNous/new-api PR #4492 QuantumNous/new-api#4492
Refs: QuantumNous/new-api PR #5431 QuantumNous/new-api#5431
Refs: QuantumNous/new-api PR #5791 QuantumNous/new-api#5791
Refs: QuantumNous/new-api PR #6264 QuantumNous/new-api#6264
Refs: QuantumNous/new-api PR #6583 QuantumNous/new-api#6583
Refs: QuantumNous/new-api PR #6620 QuantumNous/new-api#6620
Refs: QuantumNous/new-api PR #6673 QuantumNous/new-api#6673
Refs: QuantumNous/new-api issue #6972 QuantumNous/new-api#6972
Refs: QuantumNous/new-api PR #7028 QuantumNous/new-api#7028
Refs: QuantumNous/new-api issue #7951 QuantumNous/new-api#7951
Refs: QuantumNous/new-api issue #7952 QuantumNous/new-api#7952
Refs: QuantumNous/new-api PR #7953 QuantumNous/new-api#7953
Refs: QuantumNous/new-api PR #7955 QuantumNous/new-api#7955
Refs: QuantumNous/new-api issue #8034 QuantumNous/new-api#8034
Refs: QuantumNous/new-api PR #8076 QuantumNous/new-api#8076
Refs: QuantumNous/new-api issue #8123 QuantumNous/new-api#8123
Refs: QuantumNous/new-api PR #8124 QuantumNous/new-api#8124
Refs: QuantumNous/new-api issue #8232 QuantumNous/new-api#8232
Refs: QuantumNous/new-api PR #8233 QuantumNous/new-api#8233
Refs: QuantumNous/new-api issue #8295 QuantumNous/new-api#8295
Refs: QuantumNous/new-api PR #8296 QuantumNous/new-api#8296
Refs: QuantumNous/new-api PR #8350 QuantumNous/new-api#8350
Refs: QuantumNous/new-api PR #8357 QuantumNous/new-api#8357
Refs: QuantumNous/new-api PR #8363 QuantumNous/new-api#8363
Refs: #99 #99
Refs: #100 #100
Refs: #101 #101
Refs: #102 #102
Refs: #103 #103
Refs: #104 #104
Refs: #105 #105
Refs: #106 #106
Refs: #107 #107
Refs: #108 #108

Refs: #109 #109

Documentation Verify CI passed: https://github.com/soulteary/yunqi/actions/runs/45003986698

This branch has not been deployed

No deployments
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.

Redis 模型限流在 key 过期时误返回 500

1 participant