Skip to content

fix(gateway): keep usage result cache TTL across clock changes - #189160

Closed
chengzhichao-xydt wants to merge 1 commit into
openclaw:mainfrom
chengzhichao-xydt:fix/usage-cache-clock
Closed

chengzhichao-xydt wants to merge 1 commit into
openclaw:mainfrom
chengzhichao-xydt:fix/usage-cache-clock

Conversation

@chengzhichao-xydt

@chengzhichao-xydt chengzhichao-xydt commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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 updatedAt timestamps 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 canonical monotonicNow() clock and are renamed to say so (updatedAtMonotonic, lastAccessedMonotonic). The fields are module-internal: no consumer outside usage-cache.ts reads 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 suites usage.sessions-usage-cache.test.ts and models-auth-status.test.ts carry pre-existing failures that reproduce identically on the unmodified base (upstream breakage window, unrelated to this change). oxlint and oxfmt --check clean 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 in config/test-lines-allocations/chengzhichao-usage-cache-clock-20261031.txt.

Real behavior proof

Behavior addressed: The shipped loadUsageResultCached TTL 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 shipped loadSessionsUsageSnapshotCached — the cache entry the sessions.usage RPC methods call — with a real disk-reading snapshot loader (temp file); Date.now is stepped between calls while performance.now stays 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.mts and SCENARIO=backward (real 31s wait across the TTL), then the same two commands with src/gateway/server-methods/usage-cache.ts restored 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.ts keeps its own Date.now() TTL: its refreshedAt is a public RPC epoch (surfaced as usageRefreshAt and consumed as epoch by the Control UI), so it needs an epoch/monotonic split rather than this entry-internal swap — a justified separate change.
  • The value-level updatedAt fields on usage summaries (public epoch timestamps) — unchanged by design.

@clawsweeper

clawsweeper Bot commented Oct 31, 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: S labels Oct 31, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

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

  • Before: The expired result appears fresh until the wall clock catches up.
  • After: The expired result triggers a background refresh based on elapsed time.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and source-consistent; the supplied production-owner harness supports the fix but does not clear the required shipped-entry-point proof gate.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Usage results can remain stale after a backward clock correction or reload unnecessarily after a forward correction.
Reason: Elapsed-time freshness is an existing cache contract, and this narrow change preserves public timestamps, revision-only overview reuse, and cache lifecycle behavior.

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
Reviewed head: fb2af180595c1cb491e6c2edc4b6cdea178d3504

Before merge

  • Add real behavior proof - The updated body reports Node 24 Linux output through loadSessionsUsageSnapshotCached with native performance.now(), a disk-reading fixture, and contrasting base/head results for ±1-hour steps. This improves the earlier generic-helper evidence, but replaces the production snapshot loader and explicitly omits the running Gateway RPC boundary, so the prior request remains unresolved. The contributor should supply that RPC evidence, keeping overview revision-only reuse separate from TTL-governed detail or cost responses, and redact IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Provide base/head terminal output or redacted logs through an isolated running Gateway's TTL-governed usage RPC path for fresh-cache forward correction and expired-cache backward correction.
Agent review details

How this fits together

Gateway 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
Loading

Technical review

Best 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

  • Shared usage-cache ownership and freshness keeps the original intent (bff918a: Move the existing generic engine into an adjacent owner and keep domain Maps private without changing cache policy; this was a move, not proof of the original introduction of wall-clock freshness.)
  • Idle eviction and stable revision entries keeps the original intent (5ab3ae2: Release obsolete cached usage state while preserving active loads and same-query stale refreshes.)
  • Revision-only overview reuse keeps the original intent (7aae49e: Reuse completed overview snapshots until an owning revision changes.)
  • Detached refresh settlement keeps the original intent (c3924e7: Displaced refreshes may settle into their detached entry objects because they cannot overwrite the replacement Map entry.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +5, Tests +29, Other +2. Total +36 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 19 14 +5
Tests 1 31 2 +29
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 3 52 16 +36

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock corrections can prolong stale usage results or cause unnecessary reloads, with limited impact outside usage reporting.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦞 diamond lobster.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add the two clock-step comparisons through a running Gateway usage RPC using production loaders.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-31T07:14:37.422Z sha fb2af18 :: needs real behavior proof before merge. :: none

Reviewed October 31, 2026, 6:36 AM ET / 10:36 UTC (Revision 2).

@chengzhichao-xydt

Copy link
Copy Markdown
Contributor Author

Upgraded the proof to the shipped entry: a real subprocess now drives loadSessionsUsageSnapshotCached (the cache entry the sessions.usage RPC methods call) with a real disk-reading snapshot loader, stepping Date.now ±1h around real TTL waits. HEAD: forward serves the fresh snapshot (diskReads stays 1), backward still refreshes after 31 real seconds (diskReads 2, follow-up sees the new snapshot); BASE inverts both (2 re-fetch on a fresh entry / 1 with the stale entry resurrected). Full terminal output in the updated body. @clawsweeper re-review

@chengzhichao-xydt

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 31, 2026
@chengzhichao-xydt

Copy link
Copy Markdown
Contributor Author

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: loadSessionsUsageSnapshotCached keys entries by a revision composed of readSessionRowChangeRevision()/getSessionCostUsageUpdatedAt()/transcript/profile revisions, so any session write invalidates the entry outright — a TTL observation at the RPC layer can't be isolated from revision invalidation without real usage data (a live model turn), which I can't produce in this environment.

What's in the body instead: the shipped loadSessionsUsageSnapshotCached (the exact cache entry the sessions.usage RPC calls) driven in a real subprocess with a real disk-reading loader, native performance.now, and Date.now stepped ±1h — head serves fresh across the forward step and still refreshes after the real 30s TTL across the backward step, base inverts both. The patch itself is unchanged and review-clean.

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.

obviyus added a commit that referenced this pull request Nov 2, 2026
…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]>
@obviyus

obviyus commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Thank you! Your fix is included in #190894, landed in fca1c6e with your commit kept for credit.

@obviyus obviyus closed this Nov 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 3, 2026
…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]>
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants