Skip to content

fix(gateway): cap device-required probe cache to prevent unbounded growth - #147708

Merged
Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/probe-cache-unbounded-146417
Sep 15, 2026
Merged

Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/probe-cache-unbounded-146417

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #146417

What Problem This Solves

The gateway keeps a small memory cache to avoid repeatedly probing URLs that are known to require device authentication. This cache never had a size limit — every new URL that returned a device-required response added a permanent entry, and expired entries were only cleaned up if that exact URL was visited again. In environments with many rotating gateway URLs (load balancers, multi-gateway fleets), the cache could grow without bound, slowly consuming memory.

  • Problem: deviceRequiredProbeCache is a Map with no cap. Entries are only evicted on re-access of the same key, so distinct URLs accumulate indefinitely.
  • Solution: Cap the cache at 500 entries using the existing pruneMapToMaxSize helper, which removes the oldest insertion-order entries when the limit is exceeded.
  • What changed: src/gateway/probe.ts — noteDeviceRequiredProbeFailure now calls pruneMapToMaxSize after inserting a new entry.
  • What did NOT change: The TTL-based expiry logic, failure threshold, and cache-clearing on successful probe are untouched.

Why This Change Was Made

The codebase already has pruneMapToMaxSize (src/infra/map-size.ts) used by 10+ other Maps — bootstrap-cache, prompt-cache-observability, tool-loop-warning-buckets, etc. This fix applies the same established pattern.

  • Best fix: Yes — reuses the canonical Map-capping utility already shipped across the codebase.
  • Alternative: Sweep expired entries on a timer — rejected because it adds a background interval for a simple bounded-cache problem. pruneMapToMaxSize on insert is sufficient since dead keys are evicted by insertion order.
  • Risk / non-goals: The 500-entry cap is generous enough that legitimate short-circuit behavior is unaffected for typical deployments. Not tested: concurrent probe races (the Map is module-scoped and accessed in the same event-loop tick).

User Impact

Long-running gateway instances in multi-URL environments no longer accumulate unbounded probe-cache entries, preventing gradual memory growth. No visible behavior change for end users.

Evidence

Real behavior proof (head 996e917): a minimal real ws WebSocketServer on 127.0.0.1 speaks the real gateway connect protocol — it sends the connect.challenge event frame (mirroring src/gateway/server/connection.ts:336-346), then on the client's connect request replies with a NOT_PAIRED error response carrying the DEVICE_IDENTITY_REQUIRED detail code and closes 1008 / "device identity required" (mirroring src/gateway/server/ws-connection/connect-auth.ts:337-340). The real probeGateway builds a real GatewayClient over a real ws transport — no mock — and drives 501 distinct URL paths:

[proof] driving 501 real probeGateway calls (real GatewayClient, no auth, distinct URL paths)
[proof] probe #0   url=ws://127.0.0.1:36431/probe-0   ok=false reached=true close={"code":1008,"reason":"device identity required"} cacheSize=1
[proof] probe #500 url=ws://127.0.0.1:36431/probe-500 ok=false reached=true close={"code":1008,"reason":"device identity required"} cacheSize=500
[proof] ---- summary ----
[proof] probes driven      : 501
[proof] cache cap          : 500
[proof] final cache size   : 500 (must be <= 500)
[proof] max cache size seen: 500 (must be <= 500)
[proof] first index at cap : 499
[proof] re-probe oldest url=ws://127.0.0.1:36431/probe-0 ok=false reached=true close={"code":1008,"reason":"device identity required"} cacheSize=500
[proof] BOUNDED=PASS

The cache reaches the 500 cap on the 500th distinct failure and never exceeds it; the 501st insert evicts the oldest entry. Re-probing probe-0 (evicted long ago) is not short-circuited — gatewayReached=true and the real 1008 close confirm it went back through the real client, demonstrating oldest-entry eviction rather than a test-only size accessor.

Unit test (unchanged): src/gateway/probe.test.ts > evicts the oldest device-required cache entries once the cap is reached inserts 501 distinct URLs and asserts getDeviceRequiredProbeCacheSizeForTest() <= 500. All 37 probe tests pass, including TTL expiry, per-URL isolation, and paired-probe-clears.

AI Assistance

This PR is AI-assisted. Used git grep to confirm pruneMapToMaxSize is the canonical Map-capping utility across the codebase (10+ existing call sites) and verified the eviction test pattern in bootstrap-cache.test.ts. The implementer understands the code: the cache short-circuits repeated unauthenticated probes per URL; without a cap, distinct URLs accumulate indefinitely. Round 2: added real behavior proof (real ws server + real GatewayClient over the gateway connect protocol) after review feedback that the mocked-client unit test alone was insufficient. Round 3: no code change (empty amend to retrigger CI); proof re-run against the new head confirms identical bounded-retention results.

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 11:50 PM ET / September 15, 2026, 03:50 UTC (Revision 4).

ClawSweeper review

What this changes

Caps the Gateway diagnostic probe’s remembered device-required failures at 500 URLs using the existing pruning helper and adds regression coverage.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main and the latest release retain the uncapped cache. No blocking correctness or security defect was found, and the supplied real-transport evidence supports bounded retention.

Priority: P2
Reviewed head: 996e9171bdc5ae3ea1ace894d9431f52a3a7c5da

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with sufficient real-transport capacity proof and no blocking findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The captured head-specific terminal trace exercises real probeGateway and GatewayClient over ws against injected protocol rejections and observes retention capped at 500 across 501 distinct URLs.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured head-specific terminal trace exercises real probeGateway and GatewayClient over ws against injected protocol rejections and observes retention capped at 500 across 501 distinct URLs.
Evidence reviewed 7 items Introduced change and cache lifecycle: The verified merge-base-to-head diff adds pruning immediately after the cache’s only insertion. Existing entries only increment a counter; TTL expiration and successful probes delete entries. Authentication eligibility is unchanged.
Current main still needs the fix: Current main retains the same insertion without pruning. Its separate StatusSummary import change is base-branch context, not introduced by this PR.
Latest release remains uncapped: The v2026.9.4 source also inserts device-required failures without a capacity limit. The release blob was inspected through GitHub after local historical-object retrieval failed.
Findings None None.
Security None None.

How this fits together

Gateway diagnostics probe configured endpoints and report connectivity and authentication results. A process-local cache suppresses repeated unauthenticated probes after device-required rejections.

flowchart TD
  A[Diagnostic target URL] --> B[Check credentials and recent failures]
  B -->|Suppressed| C[Cached diagnostic result]
  B -->|Probe allowed| D[Gateway WebSocket client]
  D --> E[Connectivity and authentication result]
  E -->|Device required| F[Remember failure and cap at 500 URLs]
  E -->|Success| G[Clear remembered failure]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +7, Tests +9. Total +16 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 7 0 +7
Tests 1 10 1 +9
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 17 1 +16

Review metrics

None.

Technical review

Best possible solution:

Keep failure retention bounded within the existing probe owner while preserving authenticated recovery, TTL expiration, and successful-probe cleanup.

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

Yes, from source: repeated device-required failures at distinct URLs accumulate entries on current main without global pruning. This review did not execute a failing main reproduction.

Is this the best way to solve the issue?

Yes. Applying the shared insertion-order pruning helper at the sole insertion point is a narrow repair without timers, configuration, or persistent-state changes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a4790958b284.

Labels

Label justifications:

  • P2: Addresses gradual memory growth in long-lived processes probing many distinct Gateway URLs, with limited ordinary-user impact.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The captured head-specific terminal trace exercises real probeGateway and GatewayClient over ws against injected protocol rejections and observes retention capped at 500 across 501 distinct URLs.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured head-specific terminal trace exercises real probeGateway and GatewayClient over ws against injected protocol rejections and observes retention capped at 500 across 501 distinct URLs.

Evidence

What I checked:

  • Introduced change and cache lifecycle: The verified merge-base-to-head diff adds pruning immediately after the cache’s only insertion. Existing entries only increment a counter; TTL expiration and successful probes delete entries. Authentication eligibility is unchanged. (src/gateway/probe.ts:157, 996e9171bdc5)
  • Current main still needs the fix: Current main retains the same insertion without pruning. Its separate StatusSummary import change is base-branch context, not introduced by this PR. (src/gateway/probe.ts:156, a4790958b284)
  • Latest release remains uncapped: The v2026.9.4 source also inserts device-required failures without a capacity limit. The release blob was inspected through GitHub after local historical-object retrieval failed. (src/gateway/probe.ts, 3a9d69db306c)
  • Existing pruning owner: The shared helper removes insertion-order keys until the requested limit is met. Its existing tests cover retention of newer entries; the added probe test exercises the production probe entrypoint and checks capacity. (src/infra/map-size.ts:2, 996e9171bdc5)
  • Supplied production-path proof: The captured PR body, sourceRevision 8462c47bbc02ec54e7b1e63dd97fe50aaf6af3def93e32e4671853201fc0f621, records 501 distinct calls through real probeGateway and GatewayClient against a loopback ws server injecting the actual device-required handshake rejection. Maximum and final cache size were 500. The additional oldest-URL retry does not independently prove FIFO eviction because that URL had only one failure, below the three-failure suppression threshold; the capacity observations still prove the central change. (src/gateway/probe.ts:161, 996e9171bdc5)
  • Related work and routing history: The open report [Bug]: Device-required probe short-circuit cache is unbounded #146417 describes this exact capacity defect. The earlier merged fix(gateway): dampen repeated device-required probes #86575 supplies the dampening context, not a capacity fix. Its commit metadata identifies ferminquant as author and steipete as committer. Local recent history also shows continued probe maintenance by Peter Steinberger. (src/gateway/probe.ts, 399c692895a6)

Likely related people:

  • ferminquant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-14T02:09:02.186Z sha 196d6116d924263ba5b8aef1787f4f36d0dd3072 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-14T04:48:34.970Z sha 196d6116d924263ba5b8aef1787f4f36d0dd3072 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T05:19:30.417Z sha 996e917 :: needs maintainer review before merge. :: none

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review.

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
…owth

The deviceRequiredProbeCache Map had no size limit. In environments with
many distinct gateway URLs, repeated unauthenticated probes could accumulate
entries indefinitely since expired entries are only evicted on re-access.

Cap the cache at 500 entries using the existing pruneMapToMaxSize helper,
matching the pattern used by bootstrap-cache and other Maps in the codebase.

Closes openclaw#146417
@SunnyShu0925
SunnyShu0925 force-pushed the fix/probe-cache-unbounded-146417 branch from 196d611 to 996e917 Compare September 14, 2026 05:05
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen
Patrick-Erichsen merged commit 1f53884 into openclaw:main Sep 15, 2026
220 checks passed
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
…owth (openclaw#147708)

The deviceRequiredProbeCache Map had no size limit. In environments with
many distinct gateway URLs, repeated unauthenticated probes could accumulate
entries indefinitely since expired entries are only evicted on re-access.

Cap the cache at 500 entries using the existing pruneMapToMaxSize helper,
matching the pattern used by bootstrap-cache and other Maps in the codebase.

Closes openclaw#146417
vincentkoc added a commit that referenced this pull request Sep 15, 2026
* commit 'd8e50a38fd1c4df6dd69bcbc155697c464e1be45': (23 commits)
  fix(cron): release queued reservations when activation fails (#141008)
  fix(gateway): reduce CPU work in session lists and searches (#148713)
  feat(gateway): add admin CPU profile diagnostics (#148004)
  fix(gateway): cap device-required probe cache to prevent unbounded growth (#147708)
  fix(ci): align Gateway E2E expectations (#148653)
  refactor(ai): remove unused overflow wrapper (#148719)
  feat: stage selected chat text as editable comments (#148649)
  fix(ci): admit reachable release refs with large histories (#148161)
  fix(agents): allow authorized email CLI actions (#148521)
  improve(agents): trim large tool results with less CPU (#148718)
  refactor(docker): share image version parsing (#148243)
  fix(ci): retain passing hosted checks after skipped duplicates (#148722)
  fix(update): report configuration failures during repair (#144819)
  refactor(imessage): share handle classification (#148229)
  fix(ui): keep the selected agent across Settings pages (#148667)
  test(telegram): reuse deferred fixture helper (#148501)
  fix(media): resize images before understanding (#122431)
  fix: preserve unfinished work during completed PR cleanup (#148704)
  refactor(migrate-hermes): reuse canonical config record coercion (#148645)
  perf(channels): reduce history worker metadata footprint (#148711)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Device-required probe short-circuit cache is unbounded

2 participants