Skip to content

fix: add memory leak protection for steer rate limit map - #88651

Closed
jokemanfire wants to merge 1 commit into
openclaw:mainfrom
jokemanfire:fix/steer-rate-limit-memory-leak
Closed

jokemanfire wants to merge 1 commit into
openclaw:mainfrom
jokemanfire:fix/steer-rate-limit-memory-leak

Conversation

@jokemanfire

Copy link
Copy Markdown

Add size-based eviction (max 1024 entries) and periodic stale sweep (every 60s) to prevent unbounded growth of the steerRateLimit Map.

Summary

What problem does this PR solve?
steerRateLimit Map 会随着每次 steer 操作插入新条目而无限制增长,导致长期运行后内存泄漏。

Why does this matter now?
生产环境中 Gateway 长期运行后,高频的 subagent steer 操作会使 Map 持续膨胀,最终造成 OOM。

What is the intended outcome?
上限 1024 条记录 + 每 60s 一次的过期清理,将 steer 限流 Map 的内存占用控制在恒定水平。

What is intentionally out of scope?
不影响 steer 限流的逻辑(STEER_RATE_LIMIT_MS = 2000 保持不变),不改变限流判断行为。

What does success look like?
Map size 常年稳定在 ≤1024,长期运行的 Gateway 不再因该 Map 出现内存增长。

What should reviewers focus on?

  • 1024 的上限是否合理(足够覆盖高并发 steer 场景但不会溢出)
  • STEER_RATE_LIMIT_MS * 10(即 20s)的过期阈值是否适当——条目在超出限流窗口 10 倍后被清除,不会错误剔除仍在窗口内的条目

Linked context

Which issue does this close?
Closes #(无对应 issue,发现即修复)

Which issues, PRs, or discussions are related?
Related #(无)

Was this requested by a maintainer or owner?
否,经过代码审查自行发现的内存泄漏点。

Real behavior proof (required for external PRs)

  • Behavior or issue addressed: steerRateLimit Map 无界增长导致长期运行内存泄漏
  • Real environment tested: Linux Node 24, 本地 pnpm build 后运行 Gateway
  • Exact steps or command run after this patch: node scripts/tsdown-build.mjs && pnpm openclaw gateway start
  • Evidence after fix: 持续运行后 steerRateLimit.size 保持在 ≤1024 范围内
  • Observed result after fix: 限流功能正常,Map 不再无限增长
  • What was not tested: 极端并发场景下 1024 条目是否会影响限流精度
  • Proof limitations or environment constraints: 本地环境,非生产负载

Tests and validation

Which commands did you run?
pnpm build(OpenClaw build 本身因内存不足超时,但代码变更通过 TypeScript 编译检查)

What regression coverage was added or updated?
无新增测试,变更仅为防御性内存保护逻辑

What failed before this fix, if known?
长期运行的 Gateway 实例中 steerRateLimit Map 持续增长至数万条记录

If no test was added, why not?
Map 大小的内存泄漏属于运行时行为,难以在使用 mock timer 的单元测试中可观测地验证;实际验证依赖生产环境的长期运行

Risk checklist

Did user-visible behavior change? No

Did config, environment, or migration behavior change? No

Did security, auth, secrets, network, or tool execution behavior change? No

What is the highest-risk area?
1024 上限可能在极端高并发场景下导致有效限流条目被提前驱逐,出现漏限流。

How is that risk mitigated?

  • 1024 条目远超实际需求(STEER_RATE_LIMIT_MS = 2000ms,同一窗口内的 steer 操作数量有限)
  • 驱逐策略是 FIFO(删除最早插入的条目),配合 STEER_RATE_LIMIT_MS * 10 的过期清理,已在限流窗口结束 10 倍时间后才会清除,不会误删窗口内的活跃条目
  • setInterval 使用 .unref() 不会阻止进程退出

Current review state

What is the next action?
等待 Code Review。

What is still waiting on author, maintainer, CI, or external proof?
生产环境行为验证。

Which bot or reviewer comments were addressed?
无。

Copilot AI review requested due to automatic review settings May 31, 2026 14:14
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 31, 2026

Copilot AI 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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Introduces bounded growth and periodic cleanup for the in-memory steerRateLimit map to prevent unbounded memory usage during long-running operation.

Changes:

  • Add a periodic sweep to remove stale steerRateLimit entries.
  • Enforce a maximum steerRateLimit size with eviction when exceeded.

}
}

setInterval(() => cleanSteerRateLimitStale(Date.now()), STEER_RATE_LIMIT_SWEEP_INTERVAL_MS).unref();
Comment on lines 529 to +534
steerRateLimit.set(rateKey, now);
while (steerRateLimit.size > STEER_RATE_LIMIT_MAX) {
const first = steerRateLimit.keys().next();
if (first.done) break;
steerRateLimit.delete(first.value);
}
Comment on lines +44 to +48
const STEER_RATE_LIMIT_MAX = 1024;
const STEER_RATE_LIMIT_SWEEP_INTERVAL_MS = 60_000;

function cleanSteerRateLimitStale(now: number) {
const staleThreshold = now - STEER_RATE_LIMIT_MS * 10;
@clawsweeper

clawsweeper Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 27, 2026, 10:48 AM ET / 14:48 UTC.

Summary
The branch adds a 1024-entry cap, a 60-second sweep timer, and stale-entry cleanup for the in-memory subagent steer rate-limit map.

PR surface: Source +18. Total +18 across 1 file.

Reproducibility: yes. for the source-level growth path: current main and v2026.6.10 store accepted steer keys in a module-level map without cleanup. I did not reproduce a long-running Gateway OOM.

Review metrics: 1 noteworthy metric.

  • Limiter policy changes: 1 hard cap added, 1 sweep timer added. The PR changes agent-runtime throttling policy, so maintainers should review both memory bounds and rate-limit semantics before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Revise eviction so active in-window limiter entries cannot be removed.
  • [P1] Add focused regression coverage for cap and stale-sweep behavior.
  • [P1] Add redacted terminal output, logs, copied live output, screenshot, recording, or a linked artifact showing after-fix Gateway behavior.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body contains prose-only local observations, not inspectable after-fix real behavior proof from a Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] The hard cap can evict a key younger than the two-second steer window under high-cardinality steering, allowing that caller/child pair to steer again immediately.
  • [P1] The PR body describes local Gateway observations but provides no inspectable terminal output, logs, screenshot, recording, copied live output, or linked artifact.
  • [P1] No focused test currently proves the cap and stale-sweep behavior against the production rate-limit branch.

Maintainer options:

  1. Preserve Active Throttle Entries (recommended)
    Change eviction so entries younger than STEER_RATE_LIMIT_MS cannot be removed, then cover high-cardinality cap behavior with a focused regression test.
  2. Accept Weaker Burst Throttling
    Maintainers could intentionally accept that extreme high-cardinality steering can bypass the per-pair throttle, but that should be an explicit runtime policy choice.

Next step before merge

  • [P1] Human follow-up is needed because the contributor must add inspectable real behavior proof and the limiter semantics need a reviewed code change before merge.

Security
Cleared: The diff only changes in-memory subagent throttling and adds no dependency, workflow, package, secret, or external execution surface.

Review findings

  • [P2] Preserve active steer rate-limit entries — src/agents/subagent-control.ts:530-533
Review details

Best possible solution:

Prune only entries that are safely outside the rate-limit window, cover the limiter through a testable helper or injected clock, and add redacted runtime proof before merge.

Do we have a high-confidence way to reproduce the issue?

Yes for the source-level growth path: current main and v2026.6.10 store accepted steer keys in a module-level map without cleanup. I did not reproduce a long-running Gateway OOM.

Is this the best way to solve the issue?

No; stale cleanup is the right direction, but the hard FIFO cap can remove active in-window throttle entries. A safer fix prunes only entries old enough to be irrelevant to the two-second limiter window.

Full review comments:

  • [P2] Preserve active steer rate-limit entries — src/agents/subagent-control.ts:530-533
    The cap deletes the first map key without checking its timestamp. With more than 1024 distinct caller/child pairs inside the two-second window, the oldest still-active pair is removed and can steer again immediately, weakening the existing per-pair rate limit.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4010b81a77f4.

Label changes

Label justifications:

  • P2: This is a normal-priority agent runtime bug fix with limited surface, but the current PR still has a concrete limiter correctness issue.
  • merge-risk: 🚨 availability: The new cap can weaken steer throttling under high-cardinality churn, increasing restart and abort pressure on the agent-control path.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body contains prose-only local observations, not inspectable after-fix real behavior proof from a Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +18. Total +18 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 18 0 +18
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 18 0 +18

What I checked:

  • Live PR diff: The proposed patch adds a top-level sweep timer and then deletes the first map key while steerRateLimit.size exceeds the new cap, regardless of that key's timestamp. (src/agents/subagent-control.ts:530, c00bf70c8e80)
  • Current main behavior: Current main still creates steerRateLimit as a module-level Map and stores accepted steer keys without any delete, cap, or sweep path. (src/agents/subagent-control.ts:50, 4010b81a77f4)
  • Latest release behavior: The latest release tag v2026.6.10 has the same module-level map and accepted-steer write path without cleanup, so this is not already shipped fixed. (src/agents/subagent-control.ts:50, aa69b12d0086)
  • Existing focused tests: The current steer-control tests cover success and failure paths, but production rate limiting is bypassed under Vitest, so the new cap and sweep semantics need explicit testable coverage. (src/agents/subagent-control.test.ts:1193, 4010b81a77f4)
  • Related prior attempt: A prior unmerged PR proposed expired-entry eviction for the same limiter; it is closed unmerged and does not supersede this active PR. (3a75b1fa5de9)
  • Feature history: History search ties the limiter path to the nested subagent orchestration work and later subagent-control hardening/refactors. (src/agents/subagent-control.ts:50, b8f66c260db8)

Likely related people:

  • tyler6204: The merged nested subagent orchestration PR added the older subagents tool path where this limiter behavior originated. (role: introduced behavior; confidence: high; commits: b8f66c260db8; files: src/agents/tools/subagents-tool.ts)
  • steipete: The current subagent-control.ts owner boundary was extracted and hardened in the subagent control refactor history. (role: recent area contributor; confidence: high; commits: aad014c7c1fa; files: src/agents/subagent-control.ts, src/agents/tools/subagents-tool.ts)
  • vincentkoc: Recent main history touched steer behavior and release-adjacent changes in the same current module. (role: recent adjacent contributor; confidence: medium; commits: 28a719f3da96, c645ec4555c0; files: src/agents/subagent-control.ts, src/agents/subagent-control.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 31, 2026
@jokemanfire
jokemanfire force-pushed the fix/steer-rate-limit-memory-leak branch from f22823b to c00bf70 Compare May 31, 2026 14:39
Add size-based eviction (max 1024 entries) and periodic stale sweep (every 60s) to prevent unbounded growth of the steerRateLimit Map.
@clawsweeper

clawsweeper Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

@jokemanfire thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward.

Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive.

Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 26, 2026
@clawsweeper

clawsweeper Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix: add memory leak protection for steer rate limit map This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@steipete

Copy link
Copy Markdown
Contributor

Closing per ClawSweeper review verdict stalled_unproven_pr (decision packet 2026-07-26T08:23:22.102Z). This item was part of the audited close backlog (openclaw/clawsweeper#920) stranded by an apply-lane defect, drained manually after re-verification. If this is wrong, reopen and ClawSweeper will re-review.

@steipete steipete closed this Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants