Skip to content

fix: move now = datetime.now() inside the lock to avoid stale timestamp#9349

Merged
RC-CHN merged 2 commits into
AstrBotDevs:masterfrom
yunyancuo:fix/rate-limit-stale-timestamp
Jul 22, 2026
Merged

fix: move now = datetime.now() inside the lock to avoid stale timestamp#9349
RC-CHN merged 2 commits into
AstrBotDevs:masterfrom
yunyancuo:fix/rate-limit-stale-timestamp

Conversation

@yunyancuo

@yunyancuo yunyancuo commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

问题

当多个协程等待同一个会话锁时,它们都在进入锁之前就捕获了 now = datetime.now()。等到协程真正获取到锁时,捕获的时间戳已经过时了——它反映的是等待前的时间,而不是实际获取锁的时间。这会导致过期时间戳未被清理,限流窗口从错误的时间点计算。

修复

now = datetime.now() 移到 async with self.locks[session_id]: 块内部,确保每个协程在获取锁的那一刻才获取当前时间。

测试

tests/test_rate_limit_stage.py 中新增 test_stalled_concurrent_events_use_current_time_after_lock

  • 使用虚拟时钟模拟并发 stall 事件
  • 验证竞争条件下的 sleep 持续时间正确
  • 验证时间戳单调有序

Fixes #9348

…mp in concurrent scenario

When multiple coroutines wait for the same session lock, they all capture

ow = datetime.now() before entering the lock. By the time a coroutine
actually acquires the lock, the captured timestamp is stale — it reflects
the time before the wait, not the actual acquisition time. This causes
expired timestamps to not be cleaned and the rate limit window to be
calculated from the wrong reference time.

Moving
ow = datetime.now() inside the lock ensures every coroutine
uses the current time at the moment it acquires the lock, fixing the
stale-timestamp bug for the stall strategy.

Co-authored-by: yunyancuo <3468440670@qq.com>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. area:core The bug / feature is about astrbot's core, backend labels Jul 22, 2026

@sourcery-ai sourcery-ai 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.

Hey - I've left some high level feedback:

  • The test monkeypatches rate_limit_stage.datetime with FakeDateTime, which only implements now(); if the module ever uses other datetime attributes this test will start failing in non-obvious ways—consider monkeypatching just datetime.now instead of the entire symbol.
  • The expected sleep_durations == pytest.approx([60.3, 60.3]) is a bit opaque; consider deriving these values from rate_limit_count and rate_limit_time (or adding a short comment) so the relationship between configuration and expected sleeps remains clear if the defaults are adjusted.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The test monkeypatches `rate_limit_stage.datetime` with `FakeDateTime`, which only implements `now()`; if the module ever uses other `datetime` attributes this test will start failing in non-obvious ways—consider monkeypatching just `datetime.now` instead of the entire symbol.
- The expected `sleep_durations == pytest.approx([60.3, 60.3])` is a bit opaque; consider deriving these values from `rate_limit_count` and `rate_limit_time` (or adding a short comment) so the relationship between configuration and expected sleeps remains clear if the defaults are adjusted.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@yunyancuo
yunyancuo force-pushed the fix/rate-limit-stale-timestamp branch from 3c9acde to d33b06f Compare July 22, 2026 07:41
@yunyancuo

Copy link
Copy Markdown
Contributor Author

感谢 review!已根据反馈修改:

  1. 仅 mock datetime.now 而非整个 datetime 符号:由于 datetime.datetime 是 C 扩展类型,无法直接修改其 now 属性。我将 FakeDateTime 改为继承 datetime.datetime 的子类,只重写 now(),其他所有 datetime 属性和方法都通过继承保留——如果模块后续用到其他 datetime 功能,也不会出问题。

  2. 期望值从配置推导:将硬编码的 pytest.approx([60.3, 60.3]) 改为 expected_stall = limiter.rate_limit_time.total_seconds() + 0.3,明确表达期望 sleep 时长与限流配置(rate_limit_time=60margin=0.3)之间的关系。

@RC-CHN
RC-CHN merged commit 2035dbd into AstrBotDevs:master Jul 22, 2026
21 checks passed
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 22, 2026
BegoniaHe pushed a commit to Xero-Team/AstrBot that referenced this pull request Jul 22, 2026
…mp (AstrBotDevs#9349)

* fix: move now = datetime.now() inside the lock to avoid stale timestamp in concurrent scenario

When multiple coroutines wait for the same session lock, they all capture

ow = datetime.now() before entering the lock. By the time a coroutine
actually acquires the lock, the captured timestamp is stale — it reflects
the time before the wait, not the actual acquisition time. This causes
expired timestamps to not be cleaned and the rate limit window to be
calculated from the wrong reference time.

Moving
ow = datetime.now() inside the lock ensures every coroutine
uses the current time at the moment it acquires the lock, fixing the
stale-timestamp bug for the stall strategy.

Co-authored-by: yunyancuo <3468440670@qq.com>

* test: address review - subclass datetime, derive expected stall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend lgtm This PR has been approved by a maintainer size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] concurrent session rate limiting causes exponentially increasing stalls

2 participants