Repository navigation
fix(gateway): keep usage result cache TTL across clock changes - #189160
chengzhichao-xydt wants to merge 1 commit into
Conversation
Co-Authored-By: Claude Code <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR uses monotonic time for usage-result cache freshness and idle eviction while preserving public epoch timestamps. Example: A cached usage result is 31 seconds old when the wall clock moves backward one hour.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains This PR addresses a real clock-sensitive cache defect still present on current main with a focused repair; no actionable code defects were found. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherGateway usage RPCs obtain snapshots and cost summaries through domain caches backed by a shared, process-local cache engine. flowchart LR
A[Usage RPC request] --> B[Domain usage cache]
B --> C[Shared cache engine]
D[Monotonic clock] --> C
C --> E[Usage loader]
E --> F[Usage response]
C --> F
Technical reviewBest possible solution: Keep the existing cache owner and use the shared monotonic clock consistently for its process-local duration decisions. Do we have a high-confidence way to reproduce the issue? Current-main source directly shows wall-clock subtraction controlling the 30-second TTL; the contributor also supplies contrasting base/head output for both clock directions, but this read-only review ran no target code. Is this the best way to solve the issue? The patch is the smallest complete repair at the shared owner: it changes the clock without adding another cache, configuration option, or compatibility path. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3bc6c4c43fc4. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +5, Tests +29, Other +2. Total +36 across 3 files. Added test files: 0. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 31, 2026, 6:36 AM ET / 10:36 UTC (Revision 2). |
|
Upgraded the proof to the shipped entry: a real subprocess now drives |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Honest status on the remaining proof gate item: the re-review asks for evidence through a running Gateway's RPC. I dug into that path: What's in the body instead: the shipped If the RPC-boundary evidence is still required, I'm happy to leave this for a maintainer with a live environment, or pick it back up when one is available. No further churn from me until then. |
…ions (#190894) fix: measure durations, timeouts and cache ages with the monotonic clock Several timeouts, cache TTLs and retry backoffs measured elapsed time with the wall clock. When the system clock jumped (NTP correction, sleep and resume, manual change), they fired too early, never fired, or ignored server backoff. These callers now use the monotonic clock (`src/shared/monotonic-time.ts` in core, `performance.now()` in extensions). Stored and displayed timestamps stay on the wall clock, and SDK signatures and public epochs are unchanged. This sweep includes #190846, #190852, #190853, #187703, #187689, #187782, #187765, #189161, #189160 and #190098, with the contributors' commits kept for credit. Evidence: built Gateway, CLI and real Chromium, main twice and candidate twice, stepping only the process wall clock (`Date.now`); no system clock change. On main, a Discord deployment timeout aborted or overran after a 60-second step, the Chromium context popover retried after about 100 ms despite server backoff, and the `sessions.usage`, Pi session catalog and GitHub project caches refreshed too early or too late. With this change, each followed real elapsed time. Ordinary controls passed, and epoch timestamps were unchanged. Details: #190894 (comment). Thanks @Alix-007, @chengzhichao-xydt, @huwei-xydt. Co-authored-by: Alix-007 <[email protected]> Co-authored-by: chengzhichao-xydt <[email protected]> Co-authored-by: Claude Code <[email protected]> Co-authored-by: 胡伟0668000622 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
…ions (openclaw#190894) fix: measure durations, timeouts and cache ages with the monotonic clock Several timeouts, cache TTLs and retry backoffs measured elapsed time with the wall clock. When the system clock jumped (NTP correction, sleep and resume, manual change), they fired too early, never fired, or ignored server backoff. These callers now use the monotonic clock (`src/shared/monotonic-time.ts` in core, `performance.now()` in extensions). Stored and displayed timestamps stay on the wall clock, and SDK signatures and public epochs are unchanged. This sweep includes openclaw#190846, openclaw#190852, openclaw#190853, openclaw#187703, openclaw#187689, openclaw#187782, openclaw#187765, openclaw#189161, openclaw#189160 and openclaw#190098, with the contributors' commits kept for credit. Evidence: built Gateway, CLI and real Chromium, main twice and candidate twice, stepping only the process wall clock (`Date.now`); no system clock change. On main, a Discord deployment timeout aborted or overran after a 60-second step, the Chromium context popover retried after about 100 ms despite server backoff, and the `sessions.usage`, Pi session catalog and GitHub project caches refreshed too early or too late. With this change, each followed real elapsed time. Ordinary controls passed, and epoch timestamps were unchanged. Details: openclaw#190894 (comment). Thanks @Alix-007, @chengzhichao-xydt, @huwei-xydt. Co-authored-by: Alix-007 <[email protected]> Co-authored-by: chengzhichao-xydt <[email protected]> Co-authored-by: Claude Code <[email protected]> Co-authored-by: 胡伟0668000622 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
What Problem This Solves
Fixes: the gateway's sessions.usage result cache re-fetches fresh results, or keeps serving expired ones, when the system clock steps (NTP correction, manual change, VM snapshot restore). The cache's TTL freshness and eviction readings compare
Date.now()readings: a forward step expires every fresh entry (needless provider re-fetches), while a backward step resurrects expired entries (stale usage shown indefinitely).User Impact
Usage overview/cost responses respect the existing 30-second freshness window in real elapsed time, regardless of clock corrections. No configuration, public API, schema, or migration changes; the value-level
updatedAttimestamps surfaced in responses stay epoch-based and unchanged.Why This Change Was Made
TTL freshness and eviction ordering are in-process duration decisions, so the entry's two timing fields (
updatedAt,lastAccessedAt) now ride the canonicalmonotonicNow()clock and are renamed to say so (updatedAtMonotonic,lastAccessedMonotonic). The fields are module-internal: no consumer outsideusage-cache.tsreads them, and nothing in the entry is persisted or serialized. Existing tests now drive the monotonic clock, and two regressions pin a forward step on a fresh entry (still served) and a backward step past the TTL (background refresh still runs).Evidence
node scripts/run-vitest.mjs run src/gateway/server-methods/usage-cache.test.ts: 10/10 pass (both new wall-clock regressions are red against the base implementation). Consumer suitesusage.sessions-usage-cache.test.tsandmodels-auth-status.test.tscarry pre-existing failures that reproduce identically on the unmodified base (upstream breakage window, unrelated to this change).oxlintandoxfmt --checkclean on changed files. Local tsgo lane unavailable on this host (glibc 2.28 vs binary requirement 2.33+); type gates run in hosted CI. Net test growth +29 lines is recorded inconfig/test-lines-allocations/chengzhichao-usage-cache-clock-20261031.txt.Real behavior proof
Behavior addressed: The shipped
loadUsageResultCachedTTL must follow real elapsed time across wall-clock steps.Real environment tested: This branch at HEAD
fb2af180595c1cb491e6c2edc4b6cdea178d3504, Node v24.13.1, Linux x64. A real subprocess drives the shippedloadSessionsUsageSnapshotCached— the cache entry the sessions.usage RPC methods call — with a real disk-reading snapshot loader (temp file);Date.nowis stepped between calls whileperformance.nowstays native. The loader's real disk-read count and returned snapshot values are the observation boundary.Exact steps or command run after this patch:
WT=$PWD SCENARIO=forward OUT=/tmp/clock-proof/usage-shipped-head-fwd.json node --import tsx /tmp/clock-proof/usage-shipped.mtsandSCENARIO=backward(real 31s wait across the TTL), then the same two commands withsrc/gateway/server-methods/usage-cache.tsrestored to the base revision.Evidence after fix: HEAD: forward —
{"scenario":"forward","initialDiskReads":1,"diskReadsAfterForwardStep":1}(fresh snapshot served after a +1h step); backward —{"scenario":"backward","initialDiskReads":1,"diskReadsAfterBackwardStep":2,"followUpTokens":2}(refresh still ran after the real TTL despite a -1h step; follow-up sees the new snapshot). BASE: forward —{"diskReadsAfterForwardStep":2}(fresh entry wrongly re-fetched); backward —{"diskReadsAfterBackwardStep":1,"followUpTokens":1}(expired entry resurrected, new snapshot never loaded). Receipts:/tmp/clock-proof/usage-shipped-{head,base}-{fwd,bwd}.json.Observed result after fix: A +1h wall-clock step no longer expires fresh cache entries; a -1h step no longer freezes expiry. Base behavior inverts both.
What was not tested: A running Gateway's RPC round-trip end to end, OS/NTP clock adjustment, and provider-specific usage fetchers. Cache size limits, in-flight sharing, and partial-result semantics are unchanged.
Intentionally out of scope
models-auth-status-usage-cache.tskeeps its ownDate.now()TTL: itsrefreshedAtis a public RPC epoch (surfaced asusageRefreshAtand consumed as epoch by the Control UI), so it needs an epoch/monotonic split rather than this entry-internal swap — a justified separate change.updatedAtfields on usage summaries (public epoch timestamps) — unchanged by design.