Skip to content

fix(cache): preserve freshness across wall-clock changes - #187703

Closed
Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-stale-cache-clock-20261029
Closed

Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-stale-cache-clock-20261029

Conversation

@Alix-007

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes premature cache refreshes and prolonged stale results when the host clock changes during reads such as project search.

User Impact

Cached reads keep their existing lifetimes during a wall-clock correction. Project search continues to reuse fresh pages and refresh normally after its unchanged 60-second lifetime. No configuration change or migration is required.

Why This Change Was Made

Use elapsed time for the shared process-local cache's private freshness and cached-error deadlines. The same owner serves core and plugin SDK consumers; existing durations, stale-refresh behavior, capacity and cancellation ownership remain intact.

Evidence

  • Scenario: Process-local stale-while-revalidate cache lifetimes follow elapsed time across wall-clock corrections; Project search avoids a premature refresh while retaining the existing 60000ms expiry, valid anonymous results and one shared refresh.
  • Entry: Actual built GatewayClient request projects.searchRemote with query; normal node --import clock-step.mjs openclaw.mjs gateway run in a private native Ubuntu24 container.; disputed owner ran unmocked: src/infra/stale-while-revalidate-cache.ts; actual projects.searchRemote handler→project-github-search→shared cache→native HTTPS→external peer recorder. No disputed owner is imported directly or replaced.
  • Same command on base 5598c3d and head 66c26e7: python3 swr-cache-clock-proof.py --checkout "$CHECKOUT" --node-dir "$NODE_DIR" --output "$OUTPUT" --expect "$PHASE"
    • Before (base): RED BASE returns stale:true for a millisecond-old page after one +3600000ms child wall step; the real peer sees jump-query GET count 1→2. Step RPC 4.812413ms; offset window 6.779824ms. Independent unshifted 60000ms TTL expires after 60002.437394ms with its own GET count2.
    • After (head): GREEN HEAD returns the same nonempty fresh page, no stale flag, with jump-query GET count remaining1 and zero additional jump GETs. Step RPC 11.437422ms; offset window 12.364440ms, then offset0. Independent unshifted original TTL still expires after 60001.210605ms with stale:true and its own GET count2.
  • Readback (http,websocket,network-recorder,config-file,subprocess): Actual external requests.jsonl equals the saved GET rows, raw clock.jsonl equals recorded offsets, whole public WebSocket responses contain the real peer project, configuration bytes stay equal and native Gateway/client/peer/container cleanup completes.
  • Proof harness: Identical frozen Python SHA256 c25bd40c0712eda7fe9d215898597c2127a6defca7c98ac48e398e8813500610 and Node collector SHA256 7fac5bbef2496fe956c03dfc9da4b76829237879d9f8f992134176b55202106e on both refs; PHASE only selects existing base/head assertions. Separate readback-only validator SHA256 e2326d376c84f92c6a5e6d95935893f7bb79163a9f2a0441c2774758ab050a36 executes no product code.
  • Control: Both refs: cold+warm share one GET per query; a new query after restoring offset0 makes exactly1 actual GET and returns one valid project. Separate normal-TTL query makes exactly2 GETs after the real 60s wait. Every one of the14 public RPC results is nonempty and credential:missing; every actual GET lacks Authorization. Total external GETs BASE5, HEAD4; the only removed request is the premature jump-query refresh.
  • Other callers checked: One shared owner covers all core and SDK consumers. Existing project search, native/OAuth identity, session GitHub reads, Actions, preview and OpenCode TTL fixtures keep all assertions with the controlled elapsed clock; raw Gateway proof covers project search only.
  • Tests: All 10 changed test files run individually via pnpm test FILE --maxWorkers=1; final owner 12/12 plus all existing consumers pass. An unchanged Feishu fake-timer TTL control also passes:241 cases across11 files. Targeted types 20.548s, typed lint 131.161s, format 0.293s, line-cap/max-lines/test-lines/mock-export/diff pass. Clean exact-HEAD normal cliStartup build exit 0 in 241.217s. (measured cost: Canonical owner 12 cases 7.471s; all per-file wall times appear below. Existing large consumer files retain their full assertions; first worker/package-boundary preparation dominates several runs. New owner rows use independent wall/elapsed clocks and no sleeps. Net test41 LF (owner32, fixtures9), one exact41 allocation; shared scalar and all existing TTLs/timeouts unchanged.)
  • Not tested: Actual OS/NTP clock changes, native macOS/Windows, live GitHub credentials/accounts, every SDK consumer at runtime, backward/error-TTL cases through the live Gateway, installed upgrades, full suite and hosted CI. Backward and cached-error behavior have independent owner regressions. The peer is a local native TLS GitHub-compatible fixture; this is no live-provider or benchmark claim.

BASE 5598c3d76bcb28cacaf864724d52ccb4c8ccdd26 and product HEAD 66c26e75478d8fe8877faf48c383ed8f81e551bf were clean normal node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup builds (262.108s and241.217s). Actual build-info and clean build stamps match both full commits. Native Linux x64/Ubuntu24, Node26.12.1; no source-server or copied dist substitute is used.

The same command and two immutable collectors ran on each ref. PHASE=base or head selects observations only; it does not alter fixtures, timeouts or product behavior. Use a fresh output directory outside both checkouts and the qualified local Ubuntu24 image tag named in the complete wrapper below (actual image ID sha256:39a6e6f0c5f1fc700b3eab6c19b973f8c01105e2a5efa37c264d0d8130353873).

python3 swr-cache-clock-proof.py --checkout "$CHECKOUT" --node-dir "$NODE_DIR" --output "$OUTPUT" --expect "$PHASE"
Observation BASE HEAD
Jump-query cold + warm one GET, fresh nonempty results one GET, fresh nonempty results
One +1h wall step before elapsed expiry stale:true; GET count2 fresh; GET count1, zero additional GETs
Offset exposure / step RPC 6.779824ms / 4.812413ms 12.364440ms / 11.437422ms
New query after restoration one actual GET, one valid project one actual GET, one valid project
Independent real 60000ms TTL 60002.437394ms; stale:true, GET count2 60001.210605ms; stale:true, GET count2
Actual totals 7 RPCs /5 GETs 7 RPCs /4 GETs

The child-only preload changes Date.now for exactly one RPC and restores offset0 in finally; native timers, performance.now, OS and parent clocks remain real. Each phase records offsets [0,3600000,0]. The normal-TTL control waits the full original duration, and the separate live query proves the same entry still reaches the real peer. Millisecond timings describe these observed runs and are not benchmarks.

The peer is a native private HTTPS server serving a valid nonempty GitHub-compatible response. It uses the existing gateway.github.host/apiBaseUrl contract (https://HOST/api/v3) and gateway.projects.nativeGitHubSearch:false, validated by official narrow Doctor. A generated private CA is checked with openssl verify and trusted through NODE_EXTRA_CA_CERTS; TLS verification and SSRF policy are not disabled. All actual requests are anonymous, all actual replies report credential:missing, and no live account/provider/channel is configured. The full response fixture and original endpoint setup are visible in the collector. This proof checks ordinary shared-cache behavior through the public RPC, not GitHub service behavior.

Both runs preserve config bytes. Client stop, Gateway exit0, forced=false, peer close, offset0 and absent owned container are recorded. Raw receipts, peer JSONL and clock JSONL match the readback-only validator. Startup hello/credential details and unrelated local paths are omitted from the public projection; all14 actual RPC values and all9 actual GET rows remain visible below.

Canonical test file Cases Actual process wall Actual input snapshot
src/infra/stale-while-revalidate-cache.test.ts 12 7.471s 7b22fbdb54fe
src/gateway/project-github-search.test.ts 17 17.049s dc0015d5ae82
src/agents/github-oauth-client.test.ts 23 142.432s 0af2989876df
src/agents/github-read-identity.test.ts 33 31.549s 0af2989876df
src/gateway/server-methods/sessions-github-read.test.ts 30 184.699s 0af2989876df
src/gateway/server-methods/sessions-github-read.target.test.ts 37 287.990s 0af2989876df
src/gateway/server-methods/board.github-actions.test.ts 27 51.013s 7b22fbdb54fe
src/gateway/server-methods/control-ui.github-preview-refresh.test.ts 3 40.449s 7b22fbdb54fe
extensions/github/src/preview.test.ts 34 26.130s 7b22fbdb54fe
extensions/opencode/session-catalog.test.ts 21 58.430s 7b22fbdb54fe
extensions/feishu/src/bot-group-name.test.ts 4 8.468s 7b22fbdb54fe

The owner retains all 8 existing rows and adds 4 rows crossing forward/backward wall steps with success/error TTLs. Each new row holds elapsed time fixed during the wall step, then verifies TTL-1 and the unchanged TTL boundary. Nine consumer test files keep their original assertions/durations while controlling the elapsed clock; the unchanged Feishu control verifies native fake-timer progression. In total 241 cases across 11 individually run files pass. Targeted types 20.548s, typed lint 131.161s and format 0.293s pass. Line-cap 1.373s, max-lines 16.601s, exact test-lines 3.286s, mock-export 43.625s and diff 0.191s pass. Test growth 41 LF (owner 32 + fixture 9) has one exact 41 allocation; no shared ceiling, timeout or TTL is widened.

The 31–288s consumer costs retain existing whole-file checks and include first worker/package-boundary preparation and shared artifact ownership. Original production fails all 4 new wall-step rows (9.844s, assertion RED). One initial typed-lint run (491.970s, including first declaration preparation) caught a new local catch-parameter shadow; renaming that parameter is test-only and final typed lint passes. An earlier TLS preflight had an invalid fixture CA, zero peer GETs and no wall step; it is retained as a harness failure and is excluded from product RED. The explicit valid CA recipe was frozen before both reported runs.

Source checks retain their actual dirty-BASE snapshot IDs in the table. Final owner/types/lint/format bind 7b22fbdb54fe134d746f46193613c537b1ab9dbf82e90b10b4c592788af211e6; earlier unchanged consumers/ratchets are reused only with exact relevant byte/line/inventory equivalence. All12 final source/test/allocation hashes equal committed HEAD. Normal build and runtime proof above actually ran on clean committed HEAD. Independent complete-candidate source review passed under the authorized delegated fallback; the unavailable standard helper is not represented as executed. Hosted CI remains NOT_RUN.

Uncovered: Actual OS/NTP clock changes, native macOS/Windows, live GitHub credentials/accounts, every SDK consumer at runtime, backward/error-TTL cases through the live Gateway, installed upgrades, full suite and hosted CI. Backward and cached-error behavior have independent owner regressions. The peer is a local native TLS GitHub-compatible fixture; this is no live-provider or benchmark claim.

Complete actual paired BASE and HEAD readback

The projection retains whole actual project-search RPC responses, actual external request rows, raw clock rows, timings, controls, build identities, original raw-file hashes and cleanup. It selects only stated relevant fields; it does not synthesize or rewrite observed response values.

{
  "base": "5598c3d76bcb28cacaf864724d52ccb4c8ccdd26",
  "head": "66c26e75478d8fe8877faf48c383ed8f81e551bf",
  "snapshot": "7b22fbdb54fe134d746f46193613c537b1ab9dbf82e90b10b4c592788af211e6",
  "fileSha256": {
    "config/test-lines-allocations/alix-stale-cache-clock-20261029.txt": "c6dfccf9203103d85dc496b552cf7fce76b17a576b764abe50c42284de477bc1",
    "extensions/github/src/preview.test.ts": "c30d5f79a83f365192981973deea60b90f91abe3051b35c2682e584fbc8e846f",
    "extensions/opencode/session-catalog.test.ts": "2e5001a59119e2f8218a19cfe81ecdbc875eb575000ab00eb61ce8c532ab0b12",
    "src/agents/github-oauth-client.test.ts": "1d15f611c0d5a6582f87f57c9b461133fcc4b9137e9c4c58305c7cfdcbe1b2e0",
    "src/agents/github-read-identity.test.ts": "25eee8c7732f9af587dcb237dbe33afe9e77e7268c9e2f6c33c8aaf887d857e5",
    "src/gateway/project-github-search.test.ts": "a8c3022c1d6041c28efe465c9174cbfd86ffd06b31998cbd763235bf41b46bd0",
    "src/gateway/server-methods/board.github-actions.test.ts": "67fdd220d8937293103af8b475147e282ebefaf095fb2c77620da57949e47a2c",
    "src/gateway/server-methods/control-ui.github-preview-refresh.test.ts": "bc7e46cb927e8fe77bae5cf9806f216128035d3ce9e04edfb0111348e4763345",
    "src/gateway/server-methods/sessions-github-read.target.test.ts": "4a41821968064d91bac3f6e0a996caa63fd91944026202853a39d7ec041b72f5",
    "src/gateway/server-methods/sessions-github-read.test.ts": "ff23e6ccba26a1f5d53efb320946e52046e0d744220cc59d8b37bf92947a624a",
    "src/infra/stale-while-revalidate-cache.test.ts": "952b276eb40cdad36b02a03db83b863de8d58d9b4a2a6555975654e5fe2376ef",
    "src/infra/stale-while-revalidate-cache.ts": "aa0949ffb020b886953e43e2f94189ebfef425ac7ce89c1086bfdf17030bd36a"
  },
  "collectorSha256": "c25bd40c0712eda7fe9d215898597c2127a6defca7c98ac48e398e8813500610",
  "innerSha256": "7fac5bbef2496fe956c03dfc9da4b76829237879d9f8f992134176b55202106e",
  "validatorSha256": "e2326d376c84f92c6a5e6d95935893f7bb79163a9f2a0441c2774758ab050a36",
  "baseBuild": {
    "receiptSha256": "876deea3ad4e005b5513df335aa2f050e54e54f1ccecabe0c9b4cc5f339d09a5",
    "logSha256": "3191393b63e87923d3851e5e9aa7a163303789abfd2976dfdb3ef44c920d82ff",
    "buildInfo": {
      "version": "2026.10.8",
      "commit": "5598c3d76bcb28cacaf864724d52ccb4c8ccdd26",
      "builtAt": "2026-10-29T10:34:34.652Z",
      "buildId": "2026.10.8-5598c3d76bcb-2026-10-29T10-34-34.652Z"
    },
    "buildStamp": {
      "builtAt": 1793270323412,
      "head": "5598c3d76bcb28cacaf864724d52ccb4c8ccdd26",
      "inputsClean": true,
      "inputSignature": "bdde04dceb0c48d460dce8a9c35c27571cf6c86bceb0cba3de84b2dab5179f6a"
    },
    "elapsedMs": 262108,
    "command": [
      "node",
      "--import",
      "./scripts/tsx.mjs",
      "scripts/build-all.mts",
      "cliStartup"
    ],
    "code": 0
  },
  "headBuild": {
    "receiptSha256": "b0d6883533b53283a5fa024bc21c2f0921ab8ed10d8012330410eb4518a55573",
    "logSha256": "92b737d29b419d4ca90d0573eb045cb7905919d07bb74fd84cd5a4c8ccb14b6c",
    "buildInfo": {
      "version": "2026.10.8",
      "commit": "66c26e75478d8fe8877faf48c383ed8f81e551bf",
      "builtAt": "2026-10-29T13:17:15.997Z",
      "buildId": "2026.10.8-66c26e75478d-2026-10-29T13-17-15.997Z"
    },
    "buildStamp": {
      "builtAt": 1793280064371,
      "head": "66c26e75478d8fe8877faf48c383ed8f81e551bf",
      "inputsClean": true,
      "inputSignature": "8146dfeea8f2a2830295fe4c0464b35ee56899632c7f46f30bf49df20e421288"
    },
    "elapsedMs": 241217,
    "command": [
      "node",
      "--import",
      "./scripts/tsx.mjs",
      "scripts/build-all.mts",
      "cliStartup"
    ],
    "code": 0
  },
  "rawSha256": {
    "base": {
      "receipt.json": "c8acd511dc864b819b62eb20ea1de1f7d773be9ad348be6eb39c7c4a4181f3f5",
      "wrapper.json": "6949ee19e3f14620120b1e0e8b641b442392a203043f88201c910bf951f9aff6",
      "requests.jsonl": "6610a4ccc95240dedbcc814ef86d3f9ae14b4828edd24cef100b0999fed6f1b9",
      "clock.jsonl": "482ced4ca0c9b64fedb52d1f8ea4eefa996b85489d36b21713863ab994f7b999",
      "clock-step.mjs": "b9dfbf57dda64b5e4696c66d83e8e72516e205aa337f085534cadd01dbcf6c7f",
      "gateway.stdout": "b3f9c3230403c14d8fcb1e7ffbd05c4707f29c8654e98de698c6ac2a893b09de",
      "gateway.stderr": "625b54de1b1627a55c5bfd0830c858bcfe88e9d60c8acb920d7ce748a1e0a667",
      "collector.stdout": "19a4001024146c98a85a0a1d14ffe3e1c13996aeedb1d47074b071410876c48a",
      "collector.stderr": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    },
    "head": {
      "receipt.json": "a9db169663c3efb9631bd0bc7d244a65d3f2c05b87e8b83c2b5f8ab2690be645",
      "wrapper.json": "b50dd5917b44e18de6e32bc5c43762b0e75623a382cb1844c055996c06307c96",
      "requests.jsonl": "6e4951a096c1cf2685c0b48ae822a091cdb78a14903cfe7396a3766005f4f56d",
      "clock.jsonl": "a3a6a3c3a2dae7ae4dcc0f1bd11b7fd115dc2c72af0a61e1a884011d55f55452",
      "clock-step.mjs": "b9dfbf57dda64b5e4696c66d83e8e72516e205aa337f085534cadd01dbcf6c7f",
      "gateway.stdout": "dc8b0541eab3a0cef8dd81b216d6ac13301af6a0a744b2817d221bb483f9df03",
      "gateway.stderr": "008318ce8159488204221f69839cab93a3bf2d0c0426895fe7e079d0dde823ec",
      "collector.stdout": "1c8997e34bdb1e07a3fd8531ec718fc4246b603a9112a73eff5661747381ceb4",
      "collector.stderr": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    }
  },
  "projection": "Whole actual project-search RPC values, external HTTPS GET rows, clock rows and cleanup are retained. Unrelated startup hello/credentials, local commands/paths and doctor details are omitted; doctor ok=true was verified. Only the stated fields are selected; actual values are not replaced.",
  "baseReadback": {
    "expected": "base",
    "observed": "RED_PREMATURE_REFRESH",
    "result": "PASS",
    "stages": [
      {
        "name": "official-narrow-doctor-completed",
        "elapsedMs": 2489.6152140000004
      },
      {
        "name": "normal-gateway-hello",
        "elapsedMs": 19719.452922
      },
      {
        "name": "cold-warm-one-GET-per-query",
        "elapsedMs": 19841.104298
      },
      {
        "name": "single-wall-step-readback-and-offset-restored",
        "elapsedMs": 19861.303226
      },
      {
        "name": "real-TTL-control-completed",
        "elapsedMs": 79855.519423
      }
    ],
    "requests": [
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-jump-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-jump-fixture in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19889.086646
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-ttl-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-ttl-fixture in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19914.171713
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-jump-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-jump-fixture in:name,description",
        "count": 2,
        "authorizationPresent": false,
        "at": 19938.016184
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-live-control+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-live-control in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19942.956861
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-ttl-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-ttl-fixture in:name,description",
        "count": 2,
        "authorizationPresent": false,
        "at": 79938.862318
      }
    ],
    "rpcs": [
      {
        "label": "jump-cold",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 99.48365899999772,
        "at": 19806.045246
      },
      {
        "label": "jump-warm",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 2.8196810000008554,
        "at": 19906.283733
      },
      {
        "label": "ttl-cold",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 7.655451999999059,
        "at": 19909.669676
      },
      {
        "label": "ttl-warm",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 8.177107999999862,
        "at": 19917.921809
      },
      {
        "label": "single-forward-wall-step",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ],
          "stale": true
        },
        "elapsedMs": 4.812412999999651,
        "at": 19929.125804
      },
      {
        "label": "restored-clock-new-query-positive-control",
        "query": "swr-live-control",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 6.612197999998898,
        "at": 19938.657865
      },
      {
        "label": "unshifted-real-60000ms-TTL",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ],
          "stale": true
        },
        "elapsedMs": 11.333214000012958,
        "at": 79920.384027
      }
    ],
    "clock": [
      {
        "offsetMs": 0,
        "at": 2637.110737
      },
      {
        "offsetMs": 3600000,
        "at": 17347.216262
      },
      {
        "offsetMs": 0,
        "at": 17357.037022
      }
    ],
    "wallStepWindowMs": 6.779824000001099,
    "jumpRequestsAtPositiveControl": 2,
    "realTtlElapsedMs": 60002.43739399999,
    "configInitialSha256": "1fbb8225fec13fb43765edfc86bdea4ef84bdef21d402c37a927eab9925dfdcf",
    "configBeforeReadsSha256": "1fbb8225fec13fb43765edfc86bdea4ef84bdef21d402c37a927eab9925dfdcf",
    "configReadsUnchanged": true,
    "cleanup": {
      "gateway": {
        "code": 0,
        "signal": null
      },
      "forced": false,
      "peerClosed": true,
      "offsetRestored": true
    },
    "elapsedMs": 80377.46000400001
  },
  "headReadback": {
    "expected": "head",
    "observed": "GREEN_ELAPSED_TTL",
    "result": "PASS",
    "stages": [
      {
        "name": "official-narrow-doctor-completed",
        "elapsedMs": 2684.540688
      },
      {
        "name": "normal-gateway-hello",
        "elapsedMs": 18792.624697
      },
      {
        "name": "cold-warm-one-GET-per-query",
        "elapsedMs": 18961.685384
      },
      {
        "name": "single-wall-step-readback-and-offset-restored",
        "elapsedMs": 18983.874751
      },
      {
        "name": "real-TTL-control-completed",
        "elapsedMs": 78976.393295
      }
    ],
    "requests": [
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-jump-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-jump-fixture in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19000.652213
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-ttl-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-ttl-fixture in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19038.607495
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-live-control+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-live-control in:name,description",
        "count": 1,
        "authorizationPresent": false,
        "at": 19073.370302
      },
      {
        "method": "GET",
        "path": "/api/v3/search/repositories?q=swr-ttl-fixture+in%3Aname%2Cdescription&per_page=10",
        "query": "swr-ttl-fixture in:name,description",
        "count": 2,
        "authorizationPresent": false,
        "at": 79066.022662
      }
    ],
    "rpcs": [
      {
        "label": "jump-cold",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 134.343875999999,
        "at": 18885.47509
      },
      {
        "label": "jump-warm",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 5.286417000002984,
        "at": 19020.611026
      },
      {
        "label": "ttl-cold",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 22.207854000000225,
        "at": 19026.517529
      },
      {
        "label": "ttl-warm",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 3.6152189999993425,
        "at": 19049.473823
      },
      {
        "label": "single-forward-wall-step",
        "query": "swr-jump-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 11.43742199999906,
        "at": 19055.360496
      },
      {
        "label": "restored-clock-new-query-positive-control",
        "query": "swr-live-control",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ]
        },
        "elapsedMs": 5.617254000000685,
        "at": 19069.759156
      },
      {
        "label": "unshifted-real-60000ms-TTL",
        "query": "swr-ttl-fixture",
        "value": {
          "credential": "missing",
          "projects": [
            {
              "name": "cache-clock",
              "fullName": "fixture-owner/cache-clock",
              "cloneUrl": "https://127.0.0.1/fixture-owner/cache-clock.git",
              "webUrl": "https://127.0.0.1/fixture-owner/cache-clock",
              "private": false,
              "description": "SAFE_CACHE_REPLY_1",
              "defaultBranch": "main"
            }
          ],
          "stale": true
        },
        "elapsedMs": 7.802329999991343,
        "at": 79050.710539
      }
    ],
    "clock": [
      {
        "offsetMs": 0,
        "at": 2668.475845
      },
      {
        "offsetMs": 3600000,
        "at": 16272.044932
      },
      {
        "offsetMs": 0,
        "at": 16286.820158
      }
    ],
    "wallStepWindowMs": 12.364440000001196,
    "jumpRequestsAtPositiveControl": 1,
    "realTtlElapsedMs": 60001.210605,
    "configInitialSha256": "a9d859067c4e704e6f807b03591716bd8b1e75d3687d203f732aa5c5c0c24a75",
    "configBeforeReadsSha256": "a9d859067c4e704e6f807b03591716bd8b1e75d3687d203f732aa5c5c0c24a75",
    "configReadsUnchanged": true,
    "cleanup": {
      "gateway": {
        "code": 0,
        "signal": null
      },
      "forced": false,
      "peerClosed": true,
      "offsetRestored": true
    },
    "elapsedMs": 79507.278512
  }
}
Complete frozen native wrapper

Save both collectors together outside the clean checkouts. The wrapper checks exact clean build metadata, creates the private native CA/leaf certificate and isolated directories, mounts the checkout and supported Node read-only, and removes only its own container. The native image is a local qualified Ubuntu24 resource; its exact tested ID is above.

#!/usr/bin/env python3
"""Run only the clean normal-built Gateway in the qualified private Ubuntu image."""
import argparse,hashlib,json,os,subprocess,time
from pathlib import Path

p=argparse.ArgumentParser();p.add_argument('--checkout',type=Path,required=True);p.add_argument('--node-dir',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--expect',choices=['base','head'],required=True);a=p.parse_args()
root=Path(__file__).resolve().parent; checkout=a.checkout.resolve();node=a.node_dir.resolve();out=a.output.resolve();out.mkdir(mode=0o700)
head=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
assert not subprocess.check_output(['git','status','--porcelain'],cwd=checkout)
info=json.loads((checkout/'dist/build-info.json').read_text());stamp=json.loads((checkout/'dist/.buildstamp').read_text());assert info['commit']==stamp['head']==head and stamp['inputsClean'] is True
for name in ['home','state','workspace']:(out/name).mkdir()
def sha(file):return hashlib.sha256(file.read_bytes()).hexdigest()
meta={'head':head,'buildInfo':info,'buildStamp':stamp,'expected':a.expect,'collectorSha256':sha(Path(__file__)),'innerSha256':sha(root/'swr-cache-clock-inner.mjs'),'startedAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())}
image='alix-openclaw-webkit:pw1.64.1-ubuntu24';meta['imageId']=subprocess.check_output(['docker','image','inspect',image,'--format','{{.Id}}'],text=True).strip()
(out/'ca.cnf').write_text('[req]\ndistinguished_name=dn\nx509_extensions=ca\nprompt=no\n[dn]\nCN=SWR-private-fixture-CA\n[ca]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n')
commands=[['openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(out/'ca.key'),'-out',str(out/'ca.pem'),'-config',str(out/'ca.cnf'),'-days','2'],['openssl','req','-newkey','rsa:2048','-nodes','-keyout',str(out/'server.key'),'-out',str(out/'server.csr'),'-subj','/CN=127.0.0.1'],['openssl','x509','-req','-in',str(out/'server.csr'),'-CA',str(out/'ca.pem'),'-CAkey',str(out/'ca.key'),'-CAcreateserial','-out',str(out/'server.pem'),'-days','2','-extfile',str(out/'server.ext')],['openssl','verify','-CAfile',str(out/'ca.pem'),str(out/'server.pem')]]
(out/'server.ext').write_text('subjectAltName=IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n')
for command in commands:subprocess.run(command,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,timeout=20)
name='alix-swr-cache-'+a.expect+'-'+str(os.getpid())
argv=['docker','run','--rm','--network','none','--security-opt','seccomp=unconfined','--user',f'{os.getuid()}:{os.getgid()}','--name',name,'--workdir',str(checkout)]
for directory in [checkout,node]:argv+=['--volume',f'{directory}:{directory}:ro']
argv+=['--volume',f'{root / "swr-cache-clock-inner.mjs"}:{root / "swr-cache-clock-inner.mjs"}:ro','--volume',f'{out}:{out}']
env={'HOME':str(out/'home'),'USERPROFILE':str(out/'home'),'OPENCLAW_STATE_DIR':str(out/'state'),'OPENCLAW_CONFIG_PATH':str(out/'state/openclaw.json'),'NODE_EXTRA_CA_CERTS':str(out/'ca.pem'),'OPENCLAW_NO_RESPAWN':'1','NODE_DISABLE_COMPILE_CACHE':'1','NO_COLOR':'1','PATH':str(node/'bin')+':/usr/local/bin:/usr/bin:/bin'}
for key,value in env.items():argv+=['--env',key+'='+value]
argv+=[image,str(node/'bin/node'),str(root/'swr-cache-clock-inner.mjs'),str(checkout),str(out),a.expect]
meta['argv']=argv;at=time.monotonic()
try:
 with (out/'collector.stdout').open('w') as stdout,(out/'collector.stderr').open('w') as stderr:
  result=subprocess.run(argv,stdout=stdout,stderr=stderr,timeout=220);meta['code']=result.returncode
finally:
 live=subprocess.run(['docker','container','inspect',name],capture_output=True)
 if live.returncode==0:subprocess.run(['docker','kill',name],capture_output=True,timeout=10)
 meta['containerAbsent']=subprocess.run(['docker','container','inspect',name],capture_output=True).returncode!=0
 meta['elapsedMs']=round((time.monotonic()-at)*1000);meta['finishedAt']=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime());meta['caSha256']=sha(out/'ca.pem');meta['certificateSha256']=sha(out/'server.pem')
 (out/'wrapper.json').write_text(json.dumps(meta,indent=2)+'\n');print(json.dumps({'output':str(out),'code':meta.get('code'),'elapsedMs':meta['elapsedMs'],'containerAbsent':meta['containerAbsent']}),flush=True)
assert meta['code']==0 and meta['containerAbsent']
Complete frozen public-Gateway and native-TLS collector

This imports the built public GatewayClient, starts the normal built Gateway, sends actual RPCs and reads the separate HTTPS peer. It does not import the cache or replace an owner/transport. All credentials are named synthetic fixture values.

import assert from 'node:assert/strict';
import { spawn, execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { promisify } from 'node:util';

const [checkout, output, expected] = process.argv.slice(2);
assert(['base', 'head'].includes(expected));
const { GatewayClient } = await import(pathToFileURL(path.join(checkout, 'packages/gateway-client/dist/index.mjs')).href);
const runFile = promisify(execFile);
const hash = (value) => createHash('sha256').update(value).digest('hex');
const bounded = async (promise, ms, label) => {
  let timer;
  try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label)), ms); })]); }
  finally { clearTimeout(timer); }
};
const started = performance.now();
const record = { expected, stages: [], requests: [], rpcs: [], cleanup: {} };
const save = () => fs.writeFileSync(path.join(output, 'receipt.json'), JSON.stringify(record, null, 2) + '\n');
const stage = (name) => { record.stages.push({ name, elapsedMs: performance.now() - started }); save(); console.log(JSON.stringify(record.stages.at(-1))); };
const offset = path.join(output, 'clock-offset');
fs.writeFileSync(offset, '0');
const clockLog = path.join(output, 'clock.jsonl');
const preload = `import fs from 'node:fs';
import {performance} from 'node:perf_hooks';
const original=Date.now.bind(Date); let last;
Date.now=()=>{const offset=Number(fs.readFileSync(process.env.SWR_CLOCK_OFFSET,'utf8'));
if(offset!==last){last=offset;fs.appendFileSync(process.env.SWR_CLOCK_LOG,JSON.stringify({offsetMs:offset,at:performance.now()})+'\\n');}
return original()+offset;};
`;
fs.writeFileSync(path.join(output, 'clock-step.mjs'), preload);
record.preloadSha256 = hash(preload);
const counts = new Map();
const barriers = new Map();
const peer = https.createServer({ key: fs.readFileSync(path.join(output, 'server.key')), cert: fs.readFileSync(path.join(output, 'server.pem')) }, (request, response) => {
  const url = new URL(request.url, 'https://127.0.0.1');
  const query = url.searchParams.get('q');
  const count = (counts.get(query) ?? 0) + 1;
  counts.set(query, count);
  const row = { method: request.method, path: request.url, query, count, authorizationPresent: request.headers.authorization !== undefined, at: performance.now() };
  record.requests.push(row);
  fs.appendFileSync(path.join(output, 'requests.jsonl'), JSON.stringify(row) + '\n');
  assert.equal(request.method, 'GET');
  assert.equal(url.pathname, '/api/v3/search/repositories');
  assert.equal(row.authorizationPresent, false);
  const body = JSON.stringify({ items: [{ name: 'cache-clock', full_name: 'fixture-owner/cache-clock', clone_url: 'https://127.0.0.1/fixture-owner/cache-clock.git', html_url: 'https://127.0.0.1/fixture-owner/cache-clock', description: `SAFE_CACHE_REPLY_${count}`, private: false, default_branch: 'main' }] });
  response.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) });
  response.end(body, () => {
    for (const [key, waiter] of barriers) if (key.startsWith(query + '\0') && count >= waiter.count) { waiter.resolve(); barriers.delete(key); }
  });
});
const countFor = (query) => counts.get(`${query} in:name,description`) ?? 0;
peer.on('tlsClientError', (error) => { record.tlsClientError = String(error); save(); });
const received = async (query, count) => {
  if (countFor(query) >= count) return;
  const pending = Promise.withResolvers();
  const key = `${query} in:name,description\0${count}`;
  barriers.set(key, { count, resolve: pending.resolve });
  try { await bounded(pending.promise, 8000, `No actual HTTP request ${query}/${count}`); }
  finally { barriers.delete(key); }
};
let gateway, client, gatewayClosed;
try {
  await new Promise((resolve, reject) => { peer.once('error', reject); peer.listen(0, '127.0.0.1', resolve); });
  const configPath = process.env.OPENCLAW_CONFIG_PATH;
  const config = { plugins: { enabled: false }, agents: { defaults: { workspace: path.join(output, 'workspace') } }, gateway: { mode: 'local', port: 19483, controlUi: { enabled: false }, auth: { mode: 'token', token: 'synthetic-cache-proof-only' }, github: { host: '127.0.0.1', apiBaseUrl: `https://127.0.0.1:${peer.address().port}/api/v3` }, projects: { nativeGitHubSearch: false } } };
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
  record.configInitialSha256 = hash(fs.readFileSync(configPath));
  const doctorArgs = [path.join(checkout, 'openclaw.mjs'), 'doctor', '--client-credentials', '--repair', '--non-interactive', '--json'];
  const doctorAt = performance.now();
  const doctor = await runFile(process.execPath, doctorArgs, { cwd: checkout, env: process.env, timeout: 60000, maxBuffer: 10_000_000 });
  fs.writeFileSync(path.join(output, 'doctor.stdout'), doctor.stdout); fs.writeFileSync(path.join(output, 'doctor.stderr'), doctor.stderr);
  record.doctor = { command: [process.execPath, ...doctorArgs], elapsedMs: performance.now() - doctorAt, output: JSON.parse(doctor.stdout) };
  assert.equal(record.doctor.output.ok, true);
  record.configBeforeReadsSha256 = hash(fs.readFileSync(configPath));
  stage('official-narrow-doctor-completed');
  const gatewayArgs = ['--import', path.join(output, 'clock-step.mjs'), path.join(checkout, 'openclaw.mjs'), 'gateway', 'run', '--bind', 'loopback', '--auth', 'token', '--token', 'synthetic-cache-proof-only', '--port', '19483'];
  const stdout = fs.openSync(path.join(output, 'gateway.stdout'), 'w'), stderr = fs.openSync(path.join(output, 'gateway.stderr'), 'w');
  gateway = spawn(process.execPath, gatewayArgs, { cwd: checkout, env: { ...process.env, SWR_CLOCK_OFFSET: offset, SWR_CLOCK_LOG: clockLog }, stdio: ['ignore', stdout, stderr] });
  fs.closeSync(stdout); fs.closeSync(stderr);
  gatewayClosed = new Promise((resolve) => gateway.once('close', (code, signal) => resolve({ code, signal })));
  record.gatewayCommand = [process.execPath, ...gatewayArgs];
  const hello = Promise.withResolvers();
  client = new GatewayClient({ url: 'ws://127.0.0.1:19483', token: 'synthetic-cache-proof-only', clientName: 'cli', mode: 'cli', scopes: ['operator.admin'], minProtocol: 4, maxProtocol: 4, requestTimeoutMs: 10000, onHelloOk: (value) => { record.hello = value; hello.resolve(); }, onConnectError: (error) => { record.lastConnectError = String(error); } });
  client.start();
  await bounded(Promise.race([hello.promise, gatewayClosed.then((value) => { throw new Error('Gateway exited before hello: ' + JSON.stringify(value)); })]), 50000, 'Normal Gateway readiness timeout');
  stage('normal-gateway-hello');
  const rpc = async (label, query) => {
    const at = performance.now();
    const value = await client.request('projects.searchRemote', { query });
    assert.equal(value.projects.length, 1, JSON.stringify(value));
    assert.equal(value.projects[0].fullName, 'fixture-owner/cache-clock');
    assert.equal(value.credential, 'missing');
    record.rpcs.push({ label, query, value, elapsedMs: performance.now() - at, at }); save();
    return value;
  };
  const jump = 'swr-jump-fixture', normal = 'swr-ttl-fixture';
  await rpc('jump-cold', jump); const warm = await rpc('jump-warm', jump);
  assert.equal(warm.stale, undefined); assert.equal(countFor(jump), 1);
  await rpc('ttl-cold', normal); const ttlWarmAt = performance.now();
  await rpc('ttl-warm', normal); assert.equal(countFor(normal), 1);
  stage('cold-warm-one-GET-per-query');
  let stepped;
  const stepAt = performance.now();
  try { fs.writeFileSync(offset, '3600000'); stepped = await rpc('single-forward-wall-step', jump); }
  finally { fs.writeFileSync(offset, '0'); record.wallStepWindowMs = performance.now() - stepAt; save(); }
  assert(record.wallStepWindowMs < 500, 'Clock perturbation window exceeded bounded single-RPC preflight');
  if (expected === 'base') { assert.equal(stepped.stale, true); await received(jump, 2); }
  else { assert.equal(stepped.stale, undefined); assert.equal(countFor(jump), 1); }
  await rpc('restored-clock-new-query-positive-control', 'swr-live-control');
  record.jumpRequestsAtPositiveControl = countFor(jump);
  assert.equal(record.jumpRequestsAtPositiveControl, expected === 'base' ? 2 : 1);
  stage('single-wall-step-readback-and-offset-restored');
  while (performance.now() - ttlWarmAt < 60000) await new Promise((resolve) => setTimeout(resolve, Math.min(5000, 60001 - (performance.now() - ttlWarmAt))));
  record.realTtlElapsedMs = performance.now() - ttlWarmAt;
  const expired = await rpc('unshifted-real-60000ms-TTL', normal);
  assert.equal(expired.stale, true); await received(normal, 2); assert.equal(countFor(normal), 2);
  assert.equal(hash(fs.readFileSync(configPath)), record.configBeforeReadsSha256);
  record.configReadsUnchanged = true;
  record.clock = fs.readFileSync(clockLog, 'utf8').trim().split('\n').map(JSON.parse);
  assert.deepEqual(record.clock.map((row) => row.offsetMs), [0, 3600000, 0]);
  record.observed = expected === 'base' ? 'RED_PREMATURE_REFRESH' : 'GREEN_ELAPSED_TTL';
  record.result = 'PASS'; stage('real-TTL-control-completed');
} catch (error) { record.result = 'HOLD'; record.error = error.stack ?? String(error); console.error(record.error); process.exitCode = 1; }
finally {
  fs.writeFileSync(offset, '0');
  if (client) await bounded(client.stopAndWait(), 5000, 'Client cleanup timeout').catch((error) => { record.cleanup.clientError = String(error); });
  if (gateway && gateway.exitCode === null) gateway.kill('SIGTERM');
  if (gatewayClosed) {
    try { record.cleanup.gateway = await bounded(gatewayClosed, 25000, 'Gateway cleanup timeout'); record.cleanup.forced = false; }
    catch { gateway.kill('SIGKILL'); record.cleanup.gateway = await bounded(gatewayClosed, 5000, 'Forced cleanup timeout'); record.cleanup.forced = true; }
  }
  peer.closeAllConnections(); await new Promise((resolve) => peer.close(resolve));
  record.cleanup.peerClosed = true; record.cleanup.offsetRestored = fs.readFileSync(offset, 'utf8') === '0';
  record.elapsedMs = performance.now() - started;
  if (record.result === 'PASS' && (record.cleanup.forced || record.cleanup.gateway?.code !== 0 || record.cleanup.clientError)) { record.result = 'HOLD'; record.error = 'Cleanup did not complete normally'; process.exitCode = 1; }
  save(); console.log(JSON.stringify({ result: record.result, observed: record.observed, elapsedMs: record.elapsedMs, cleanup: record.cleanup }));
}

@clawsweeper

clawsweeper Bot commented Oct 29, 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 agents Agent runtime and tooling extensions: opencode extensions: github GitHub plugin: link previews and reader size: S labels Oct 29, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 29, 2026
@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR uses monotonic elapsed time for process-local cache freshness and cached-error deadlines.

Example: A cached project search is read again after the host clock jumps forward one hour.

  • Before: The newly cached page is marked stale and triggers another HTTP request.
  • After: The page remains fresh until its original 60-second lifetime expires.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused shared-owner repair with inspected shipped-entry-point evidence, independent clock regressions and no actionable findings; CI completion remains outstanding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied clean-base and exact-head Linux builds exercise projects.searchRemote through the public GatewayClient and real HTTPS transport to a local TLS peer: the head prevents the premature refresh and preserves normal expiry; backward steps and cached errors have separate owner regressions.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Host clock corrections can make cached reads refresh prematurely or remain fresh beyond their intended lifetime.
Reason: This restores duration-based expiry within the established owner while preserving user-facing defaults, APIs and authority checks.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete cache-expiry defect still present on current main, with no actionable defects found; required CI remains pending.

Priority: P2
Reviewed head: 66c26e75478d8fe8877faf48c383ed8f81e551bf

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared in-memory cache serves core and plugin consumers, accepting keyed loaders and returning fresh or stale values while coordinating bounded refreshes.

flowchart LR
  A[Gateway and plugin callers] --> B[Shared cache]
  C[Monotonic elapsed clock] --> B
  B --> D[Existing loader]
  D --> E[External transport]
  B --> F[Fresh or stale result]
Loading

Technical review

Best possible solution:

Use the existing shared cache owner with monotonic deadlines and retain its current lifetimes and lifecycle contracts.

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

Current-main source directly exposes the wall-clock-dependent expiry path, supported by the contributor's paired base/head Gateway trace; this read-only review ran no target code.

Is this the best way to solve the issue?

The three clock substitutions are the smallest complete repair: deadline creation and comparison use one monotonic domain without adding another owner or changing caller policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Focused production repair: The introduced diff changes all three private deadline operations to performance.now(), preserving durations, cache keys, refresh ownership, capacity and invalidation. (src/infra/stale-while-revalidate-cache.ts:29, 66c26e75478d)
  • Current-main defect: Fetched main still compares and creates cache deadlines with Date.now(), allowing wall-clock corrections to shorten or extend freshness. (src/infra/stale-while-revalidate-cache.ts:29, 36383b8ce160)
  • Supplied shipped-entry-point proof: Inspected the paired built-Gateway RPC responses, native HTTPS request records and collectors in the full PR body. Base makes a premature second search request after the clock step; head retains one request, while both expire normally after 60 seconds. The retrieved body matches SHA256 9aebce61133dec530bbaaa4a816f7adf78a384a49fd9ddfb3f8ffd911327a2fa, and every recorded changed-file hash matches the checkout. No embedded collector was executed during review. (66c26e75478d)
  • Original cache contract: The merged perf(github): serve stale Control UI reads during bounded refresh #169143 introduced this shared owner to preserve bounded stale refreshes and strict publication verification; this PR retains those contracts. (src/infra/stale-while-revalidate-cache.ts:29, ea4b186dbfcf)
  • Independent clock regressions: Four owner cases independently vary wall and elapsed clocks for forward/backward steps and success/error TTLs, checking reuse before expiry and reload at the unchanged boundary; consumer edits preserve existing assertions. (src/infra/stale-while-revalidate-cache.test.ts:19, 66c26e75478d)
  • Policy and CI state: Applied root and scoped repository policies and simplification steps 1–3; no maintainer-notes directory exists. GitHub reports the reviewed head mergeable, with the baseline-ratchet check running and openclaw/ci-gate pending; inspected both check-run pages without finding a failed check. (AGENTS.md, 66c26e75478d)

PR surface

Source 0, Tests +41, Other +2. Total +43 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 3 3 0
Tests 10 45 4 +41
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 12 50 7 +43

Review metrics

Metric Value Why it matters
Production versus test LOC Production +3/-3; tests +45/-4 Test growth covers four distinct clock-step cases and adapts existing consumer clocks without adding production machinery.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock corrections can cause premature refreshes or delayed expiry across shared cache consumers, with limited demonstrated user impact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

Reviewed October 29, 2026, 10:07 AM ET / 14:07 UTC.

@Alix-007

Copy link
Copy Markdown
Contributor Author

Thanks @clawsweeper for reviewing the cache fix and its consumer coverage.

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

agents Agent runtime and tooling extensions: github GitHub plugin: link previews and reader extensions: opencode gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

2 participants