Skip to content

fix(engine): clamp rate-limit retryAfterMs to at most one window on a backward clock - #5855

Merged
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
real-venus:fix/loopover-engine-ratelimit-backward-clock
Jul 14, 2026
Merged

fix(engine): clamp rate-limit retryAfterMs to at most one window on a backward clock#5855
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
real-venus:fix/loopover-engine-ratelimit-backward-clock

Conversation

@real-venus

Copy link
Copy Markdown
Contributor

Summary

evaluateLocalRateLimit (the Governor's pure rolling-window rate-limit primitive) computes retryAfterMs from resetAtMs - now, but its windowElapsed check only detects a forward-moving clock:

const windowElapsed = now - windowStartMs >= windowMs;

If nowMs ever steps backward relative to a bucket's windowStartMs — a real possibility for a Date.now()-derived clock across an NTP correction or a container/VM clock reset — windowElapsed stays false, effectiveWindowStart keeps the old windowStartMs, and resetAtMs - now grows by the full backward-jump distance on top of windowMs. A caller blocked right after a half-second backward step on a 60-second window is told to wait minutes, worse the larger the jump (#5829).

Fix: clamp retryAfterMs to at most one windowMs, so a rolling-window limiter can never report a wait longer than its own window:

const retryAfterMs = allowed ? 0 : Math.min(windowMs, Math.max(0, resetAtMs - now));

Forward behavior is unchanged — when resetAtMs - now <= windowMs (the normal case) the clamp is a no-op. This is the minimal, targeted fix the issue asks for; it does not alter the allow/deny or window-reset logic.

The module had no dedicated test (it was only exercised indirectly, never with nowMs moving backward). This adds test/unit/governor-rate-limit-backoff.test.ts covering the three branches of the changed line: allowed (no wait), blocked under a forward clock (clamp is a no-op), and blocked after a backward clock jump (clamped to windowMs, not the inflated value).

Scope

Validation

  • git diff --check
  • npm run typecheck (root + @loopover/engine build) clean
  • npm run test:coverage — the changed line (rate-limit.ts:71) is at 100% line + branch coverage (verified via the v8 JSON report: the allowed ? 0 branch, and both sides of the Math.min clamp). 3 new tests pass.
  • Behavior unchanged for existing consumers: governor-*, chokepoint, and write-rate-limit root-vitest suites pass (218 tests) — the clamp is a no-op on a forward clock.
  • Rebased onto the latest main immediately before pushing — no base conflict.

If any required check was skipped, explain why:

  • actionlint, test:workers, ui:*, npm audit were not run — this changes one engine source line + a test; no workflow, worker, UI, or dependency surface. The full npm run test:ci runs them on CI. (One local unit test, miner-mcp-governor-decisions, fails on this Windows box with EPERM on temp dirs — a filesystem env flake that does not import rate-limit and passes on Linux CI.)

Safety

  • No secrets, wallet details, hotkeys, coldkeys, PATs, private keys, raw trust scores, private rankings, or private maintainer evidence exposed. Pure numeric-math change to a side-effect-free calculator; no I/O, no persistence.
  • Public GitHub text stays sanitized and low-noise.
  • No changelog edited.

Auth/CORS/session, API/OpenAPI/MCP, and UI safety boxes are not applicable.

… backward clock

evaluateLocalRateLimit's windowElapsed check only detects a FORWARD clock, so if
nowMs steps backward relative to a bucket's windowStartMs (an NTP correction or
container/VM clock reset), resetAtMs - now grows by the jump distance on top of
windowMs -- a caller blocked right after a half-second backward step on a 60s
window could be told to wait minutes (JSONbored#5829). Clamp retryAfterMs to windowMs so a
rolling-window limiter never reports a wait longer than its own window; forward
behavior is unchanged (the clamp is a no-op when resetAtMs - now <= windowMs). Add
a dedicated test (the module had none) covering the allowed, blocked-forward, and
backward-clock-clamp cases.

Closes JSONbored#5829
@real-venus
real-venus requested a review from JSONbored as a code owner July 14, 2026 19:55
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@codecov

codecov Bot commented Jul 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.11%. Comparing base (ad011d3) to head (6e5b913).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #5855   +/-   ##
=======================================
  Coverage   95.11%   95.11%           
=======================================
  Files         587      587           
  Lines       46511    46511           
  Branches    14870    14870           
=======================================
  Hits        44240    44240           
  Misses       1515     1515           
  Partials      756      756           
Flag Coverage Δ
shard-1 43.76% <0.00%> (ø)
shard-2 36.18% <100.00%> (ø)
shard-3 32.13% <0.00%> (ø)
shard-4 32.81% <100.00%> (ø)
shard-5 31.62% <100.00%> (+<0.01%) ⬆️
shard-6 44.51% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ackages/loopover-engine/src/governor/rate-limit.ts 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 14, 2026
@loopover-orb

loopover-orb Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Tip

🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩

✅ LoopOver review result - approve/merge recommended

Review updated: 2026-07-14 20:11:33 UTC

2 files · 1 AI reviewer · no blockers · readiness 100/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
This is a minimal, correct fix: clamping `retryAfterMs` to `Math.min(windowMs, ...)` bounds the reported wait to at most one window even when `now` steps backward relative to `windowStartMs`, and the forward-clock path is unchanged since `resetAtMs - now <= windowMs` there already. The added test file exercises exactly the three branches (allowed, forward-blocked no-op clamp, backward-jump clamped) and the backward-jump case is verified by hand against the pre-fix arithmetic (160,000 vs clamped 60,000). It closes the linked issue #5829 with a single-line change plus dedicated regression tests, matching the existing test file's conventions in test/unit/governor-rate-limit.test.ts.

Nits — 3 non-blocking
  • packages/loopover-engine/src/governor/rate-limit.ts:71 — `resetAtMs` itself is still returned uninflated (e.g. 160,000 in the backward-jump case) even though `retryAfterMs` is now clamped; a caller that computes its own wait from `resetAtMs - now` instead of using `retryAfterMs` directly would still see the inflated value — worth a one-line doc note that `retryAfterMs` is the authoritative field.
  • test/unit/governor-rate-limit-backoff.test.ts overlaps somewhat with the pre-existing test/unit/governor-rate-limit.test.ts (same function, same config shape) — consider whether the three new cases could instead be added to the existing describe block rather than a new file, per repo convention of one test file per module.
  • Consider adding a brief JSDoc note on `LocalRateLimitDecision.resetAtMs` clarifying it is not clock-jump-clamped and callers should prefer `retryAfterMs` for wait duration (rate-limit.ts:26-27).
Signal Result Evidence
Code review ✅ No blockers 1 reviewer
Linked issue ✅ Linked #5829
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 112 registered-repo PR(s), 59 merged, 17 issue(s).
Contributor context ✅ Confirmed Gittensor contributor real-venus; Gittensor profile; 112 PR(s), 17 issue(s).
Gate result ✅ Passing No configured blocker found.
Improvement ✅ Minor risk: clean · value: minor — Code changes are accompanied by test evidence. LLM value judgment: minor — It's a correct, well-tested one-line clamp fix for a real but narrow edge case (backward clock jumps) closing an explicitly linked open issue, so it's a small but legitimate improvement rather than a significant one.
Linked issue satisfaction

Partially addressed
The core clamp fix and backward-clock-skew test are correctly implemented, matching the requirement to bound retryAfterMs to windowMs, but the test file was placed at test/unit/governor-rate-limit-backoff.test.ts rather than the explicitly requested packages/loopover-engine/test/rate-limit.test.ts path, and the doc comment change is an inline comment rather than an update to the function's existin

Review context
  • Author: real-venus
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: not available
  • Official Gittensor activity: 112 PR(s), 17 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
[BETA] Chat with Gittensory

Ask Gittensory a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @gittensory ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @gittensory chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @gittensory mention with a real question is routed to the closest matching read-only command automatically -- no exact syntax required.

Full command reference: https://gittensory.aethereal.dev/docs/gittensory-commands

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@loopover-orb loopover-orb 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.

Gittensory approves — the gate is satisfied and CI is green.

@loopover-orb
loopover-orb Bot merged commit f35e354 into JSONbored:main Jul 14, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(engine): rate-limit.ts retryAfterMs unbounded under backward clock skew

1 participant