Skip to content

fix: gateway probe reports incorrect duration after clock changes - #190853

Closed
Alix-007 wants to merge 2 commits into
openclaw:mainfrom
Alix-007:fix/alix-gateway-probe-clock-20261102
Closed

Alix-007 wants to merge 2 commits into
openclaw:mainfrom
Alix-007:fix/alix-gateway-probe-clock-20261102

Conversation

@Alix-007

@Alix-007 Alix-007 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: gateway probe duration and connection latency become negative or inflate by a minute when the system clock changes during a probe.

User Impact

User impact: gateway diagnostics report actual elapsed probe and connection time through successful and refused connections, so automation receives meaningful timing values.

Why This Change Was Made

Measure the command aggregate and both handshake-result timing paths with the monotonic clock, keeping the JSON ts field as an epoch timestamp.

Evidence

Base bc097bf6404f34be1e57cdee8bd0b2d7f59a3070 → product head ea7829917718dcaded9d9c449081d1647ec9ab36. Linux, Node v26.12.1, pnpm 12.15.0; normally built openclaw.mjs, isolated HOME/config/state for every CLI invocation. Clock correction is injected only after the independent receiver sees the request. Product owners, transport, provider dispatch, and JSON rendering are not replaced. Ordinary, -60 s, +60 s, and -60 s/refusal cases use the same collector on both frozen revisions.

Case Base duration (ms) Head duration (ms) Result
ordinary 1929 1986 success
backward -57961 1839 success
forward 62122 1803 success
failure-control -57959 1796 refusal preserved
Connection latency Base (ms) Head (ms)
ordinary 720 743
backward -59181 761
forward 60849 773
failure-control -59241 757

All 4 cases reach the independent receiver; 3 successful cases and 1 explicit refusal retain correct classification; successful cases exit 0 and the explicit refusal exits 1; all signals are null, all watchdog flags false, all configs unchanged, all peers closed.

  • Production entry: node openclaw.mjs gateway probe --url ws://127.0.0.1:$PORT --token clock-fixture --timeout 5000 --json.
  • Canonical owner exercised: src/commands/gateway-status.ts and src/gateway/probe.ts.
  • Recorder/readback: Parent process reads actual CLI stdout JSON, stderr, and exit status; separate loopback WebSocket receiver records real product requests and synthetic credential matching.
  • Same proof command on base/head: node proof-probes.mjs "$CHECKOUT" "$OUTPUT" gateway "$EXPECT".
  • Normal build: node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup, exit 0 (217.14 s on head); clean build stamp matches the product commit.
  • Tests: pnpm test src/commands/gateway-status.test.ts src/gateway/probe.test.ts src/gateway/probe.close-drain.test.ts src/gateway/probe.tls.test.ts src/gateway/probe.device-auth-scope.test.ts src/gateway/probe.auth.integration.test.ts --maxWorkers=1: 74 tests across 6 files, exit 0, 97.02 s.
  • Test cost: Single-worker full command wall clock 97.02 s; the command includes both changed test files and their consumers. Native runner measured the four new regression cases: ✓ |gateway-core| src/gateway/probe.test.ts > probeGateway > measures hello connection time across wall-clock steps 13534ms; ✓ |gateway-core| src/gateway/probe.test.ts > probeGateway > measures close connection time across wall-clock steps 8ms; ✓ |commands| src/commands/gateway-status.test.ts > gateway-status command > reports elapsed probe time across a -60000 ms clock step 63ms; ✓ |commands| src/commands/gateway-status.test.ts > gateway-status command > reports elapsed probe time across a 60000 ms clock step 6ms. Compiled-worker preparation and native state/TLS fixtures explain the batch exceeding 30 s; case times are not reported as standalone file wall time.
  • Touched-file typed lint, formatting, test-line budget, and normal commit hooks passed.
  • Scope: 5 files; production +5/−5 LOC; tests +50/−0 LOC; separate allocation +2 lines for exactly 50 net new test lines.
  • Existing-solutions preflight: use the existing owner and standard monotonic clock; current main still reproduced the gap, and all-state symbol/title/history scans found no viable competing fix. Gateway command, probe handshake/close, TLS pinning, device-auth scope, close drain, and auth integration tests pass; both connection timing writers are covered.
  • Not tested: Loopback peer implements the normal Gateway wire protocol; no production Gateway, SSH tunnel, remote deployment, or native macOS/Windows was exercised. No public configuration/schema/default, security policy, or persisted migration changes.
  • AI-assisted; code and evidence reviewed independently using the user-authorized adversarial review fallback. The official autoreview helper was not run because its configured official authentication is unavailable.
Actual stdout/RPC readbacks and cleanup records (fixture paths normalized)
{
  "base": {
    "head": "bc097bf6404f34be1e57cdee8bd0b2d7f59a3070",
    "cleanBuild": true,
    "cases": [
      {
        "case": "ordinary",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:41329",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": 0,
        "summary": {
          "ok": true,
          "ts": 1793590812251,
          "durationMs": 1929,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:41329",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": 720,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793590812246
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 0,
            "at": 7032.621448
          }
        ]
      },
      {
        "case": "backward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:35077",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "ok": true,
          "ts": 1793590759267,
          "durationMs": -57961,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:35077",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": -59181,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793590819262
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6833.463267
          }
        ]
      },
      {
        "case": "forward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:37245",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": 60000,
        "summary": {
          "ok": true,
          "ts": 1793590886369,
          "durationMs": 62122,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:37245",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": 60849,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793590826364
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 60000,
            "at": 6920.991176
          }
        ]
      },
      {
        "case": "failure-control",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:35563",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "ok": false,
          "ts": 1793590773934,
          "durationMs": -57959,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:35563",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": false,
                "rpcOk": false,
                "scopeLimited": false,
                "latencyMs": -59241,
                "error": "gateway closed (1008): Synthetic refusal",
                "close": {
                  "code": 1008,
                  "reason": "Synthetic refusal"
                }
              },
              "auth": {
                "role": null,
                "scopes": [],
                "capability": "unknown"
              },
              "server": {
                "version": null,
                "connId": null
              },
              "self": null,
              "config": null,
              "health": null,
              "summary": null,
              "presence": null
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          }
        ],
        "terminal": {
          "code": 1,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 7364.2323
          }
        ]
      }
    ]
  },
  "head": {
    "head": "ea7829917718dcaded9d9c449081d1647ec9ab36",
    "cleanBuild": true,
    "cases": [
      {
        "case": "ordinary",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-repair-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:37541",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": 0,
        "summary": {
          "ok": true,
          "ts": 1793593996226,
          "durationMs": 1986,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:37541",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": 743,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793593996221
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 0,
            "at": 6650.723809
          }
        ]
      },
      {
        "case": "backward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-repair-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:41039",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "ok": true,
          "ts": 1793593942499,
          "durationMs": 1839,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:41039",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": 761,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793594002494
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6075.060292
          }
        ]
      },
      {
        "case": "forward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-repair-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:39199",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": 60000,
        "summary": {
          "ok": true,
          "ts": 1793594068927,
          "durationMs": 1803,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:39199",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": true,
                "rpcOk": true,
                "scopeLimited": false,
                "latencyMs": 773,
                "error": null,
                "close": null
              },
              "auth": {
                "role": "operator",
                "scopes": [
                  "operator.admin"
                ],
                "capability": "admin_capable"
              },
              "server": {
                "version": "fixture",
                "connId": "fixture"
              },
              "self": {
                "host": "fixture"
              },
              "config": {
                "path": "fixture.json",
                "exists": true,
                "valid": true,
                "issues": [],
                "legacyIssues": [],
                "gateway": {
                  "mode": "local",
                  "bind": null,
                  "port": null,
                  "controlUiEnabled": null,
                  "controlUiBasePath": null,
                  "authMode": null,
                  "authTokenConfigured": false,
                  "authPasswordConfigured": false,
                  "remoteUrl": null,
                  "remoteTokenConfigured": false,
                  "remotePasswordConfigured": false,
                  "tailscaleMode": null
                },
                "discovery": {
                  "wideAreaEnabled": null
                }
              },
              "health": {
                "ok": true
              },
              "summary": {
                "ok": true
              },
              "presence": [
                {
                  "mode": "gateway",
                  "reason": "self",
                  "host": "fixture",
                  "text": "Synthetic Gateway",
                  "ts": 1793594008923
                }
              ]
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          },
          {
            "method": "health"
          },
          {
            "method": "status"
          },
          {
            "method": "system-presence"
          },
          {
            "method": "config.get"
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 60000,
            "at": 6237.999998
          }
        ]
      },
      {
        "case": "failure-control",
        "command": [
          "node",
          "--import",
          "$TASK/proof-gateway-repair-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "gateway",
          "probe",
          "--url",
          "ws://127.0.0.1:42297",
          "--token",
          "clock-fixture",
          "--timeout",
          "5000",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "ok": false,
          "ts": 1793593955474,
          "durationMs": 1796,
          "targets": [
            {
              "id": "explicit",
              "kind": "explicit",
              "url": "ws://127.0.0.1:42297",
              "active": true,
              "tunnel": null,
              "connect": {
                "ok": false,
                "rpcOk": false,
                "scopeLimited": false,
                "latencyMs": 757,
                "error": "gateway closed (1008): Synthetic refusal",
                "close": {
                  "code": 1008,
                  "reason": "Synthetic refusal"
                }
              },
              "auth": {
                "role": null,
                "scopes": [],
                "capability": "unknown"
              },
              "server": {
                "version": null,
                "connId": null
              },
              "self": null,
              "config": null,
              "health": null,
              "summary": null,
              "presence": null
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "connect",
            "tokenIsFixture": true
          }
        ],
        "terminal": {
          "code": 1,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6352.40918
          }
        ]
      }
    ]
  }
}
Complete proof collector source

proof-probes.mjs (sha256 731dd989365d840db4ffd98deb9bae030342e4fa01c6a3231953cc66dca5c889):

import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import assert from 'node:assert/strict';
import {spawn,execFileSync} from 'node:child_process';
import {createHash,randomUUID} from 'node:crypto';
import {createRequire} from 'node:module';
const [checkoutArg,outputArg,kind,expected]=process.argv.slice(2);
assert.ok(['gateway','models'].includes(kind)&&['base','head'].includes(expected));
const checkout=path.resolve(checkoutArg),out=path.resolve(outputArg),hash=v=>createHash('sha256').update(v).digest('hex');
assert.equal(execFileSync('git',['status','--porcelain'],{cwd:checkout,encoding:'utf8'}),'');
const head=execFileSync('git',['rev-parse','HEAD'],{cwd:checkout,encoding:'utf8'}).trim();
const stamp=JSON.parse(fs.readFileSync(path.join(checkout,'dist/.buildstamp')));assert.equal(stamp.head,head);assert.equal(stamp.inputsClean,true);
fs.mkdirSync(out,{recursive:false});
const record={kind,expected,head,at:new Date().toISOString(),buildStamp:stamp,collectorSha256:hash(fs.readFileSync(new URL(import.meta.url))),cases:[]};
const save=()=>fs.writeFileSync(path.join(out,'receipt.json'),JSON.stringify(record,null,2));
const preload=`import fs from 'node:fs';const original=Date.now.bind(Date);let shifted=false;Date.now=()=>{if(!shifted&&fs.existsSync(process.env.CLOCK_MARKER)){shifted=true;fs.appendFileSync(process.env.CLOCK_RECORD,JSON.stringify({offsetMs:Number(process.env.CLOCK_OFFSET),at:performance.now()})+'\\n');}return original()+(shifted?Number(process.env.CLOCK_OFFSET):0);};`;
const preloadFile=path.join(out,'clock-step.mjs');fs.writeFileSync(preloadFile,preload);record.preloadSha256=hash(preload);
const {WebSocketServer}=createRequire(path.join(checkout,'package.json'))('ws');
for(const [name,offsetMs,fail] of [['ordinary',0,false],['backward',-60000,false],['forward',60000,false],['failure-control',-60000,true]]){
 const root=path.join(out,name);fs.mkdirSync(root);for(const sub of ['home','state','workspace'])fs.mkdirSync(path.join(root,sub));
 const marker=path.join(root,'request-marker'),clockRecord=path.join(root,'clock.jsonl'),requests=[];
 let peer,ws;
 const step=()=>{fs.writeFileSync(marker,'request reached external peer');};
 const response=(res,body)=>{res.writeHead(200,{'content-type':'application/json'});res.end(JSON.stringify(body));};
 if(kind==='models'){
  peer=http.createServer((req,res)=>{let body='';req.on('data',b=>body+=b);req.on('end',()=>{const parsed=body?JSON.parse(body):null;requests.push({method:req.method,path:req.url,prompt:parsed?.messages,model:parsed?.model,stream:parsed?.stream,authorizationIsFixture:req.headers.authorization==='Bearer clock-fixture'});step();setTimeout(()=>{if(fail){res.writeHead(403,{'content-type':'application/json'});res.end(JSON.stringify({error:{message:'Synthetic provider refusal',type:'permission_error'}}));return;}if(parsed?.stream){res.writeHead(200,{'content-type':'text/event-stream'});const common={id:'fixture',object:'chat.completion.chunk',created:1,model:'fixture'};res.end('data: '+JSON.stringify({...common,choices:[{index:0,delta:{role:'assistant',content:'OK'},finish_reason:null}]})+'\n\ndata: '+JSON.stringify({...common,choices:[{index:0,delta:{},finish_reason:'stop'}],usage:{prompt_tokens:1,completion_tokens:1,total_tokens:2}})+'\n\ndata: [DONE]\n\n');}else response(res,{id:'fixture',object:'chat.completion',created:1,model:'fixture',choices:[{index:0,message:{role:'assistant',content:'OK'},finish_reason:'stop'}],usage:{prompt_tokens:1,completion_tokens:1,total_tokens:2}});},150);});});
 }else{
  peer=http.createServer();ws=new WebSocketServer({server:peer});
  ws.on('connection',socket=>{socket.send(JSON.stringify({type:'event',event:'connect.challenge',payload:{nonce:randomUUID(),ts:Date.now()}}));socket.on('message',raw=>{const r=JSON.parse(raw);if(r.type!=='req')return;requests.push({method:r.method,tokenIsFixture:r.method==='connect'?r.params?.auth?.token==='clock-fixture':undefined});
   const send=payload=>socket.readyState===1&&socket.send(JSON.stringify({type:'res',id:r.id,ok:true,payload}));
   if(r.method==='connect'){step();setTimeout(()=>{if(fail){socket.close(1008,'Synthetic refusal');return;}send({type:'hello-ok',protocol:4,server:{version:'fixture',connId:'fixture'},features:{methods:['health','status','system-presence','config.get'],events:[]},snapshot:{},auth:{role:'operator',scopes:['operator.admin']},policy:{maxPayload:1000000,maxBufferedBytes:1000000,tickIntervalMs:60000}});},150);}
   else if(r.method==='system-presence')send([{mode:'gateway',reason:'self',host:'fixture',text:'Synthetic Gateway',ts:Date.now()}]);
   else if(r.method==='config.get')send({path:'fixture.json',exists:true,valid:true,config:{gateway:{mode:'local'}},issues:[],legacyIssues:[]});
   else send({ok:true});
  });});
 }
 await new Promise(r=>peer.listen(0,'127.0.0.1',r));const port=peer.address().port;
 const cfg={gateway:{mode:'local',port,auth:{mode:'token',token:'clock-fixture'}},logging:{level:'silent',consoleLevel:'silent'},plugins:{allow:kind==='models'?['openai']:[]},agents:{defaults:{workspace:path.join(root,'workspace'),model:{primary:'openai/fixture'}}}};
 if(kind==='models')cfg.models={providers:{openai:{baseUrl:`http://127.0.0.1:${port}/v1`,api:'openai-completions',apiKey:'clock-fixture',models:[{id:'fixture',name:'Fixture',reasoning:false,input:['text'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:16000,maxTokens:1024}]}}};
 const configPath=path.join(root,'config.json');fs.writeFileSync(configPath,JSON.stringify(cfg));const beforeHash=hash(fs.readFileSync(configPath));
 const env={PATH:path.dirname(process.execPath)+':/usr/bin:/bin',HOME:path.join(root,'home'),USERPROFILE:path.join(root,'home'),OPENCLAW_STATE_DIR:path.join(root,'state'),OPENCLAW_CONFIG_PATH:configPath,OPENCLAW_NO_RESPAWN:'1',NODE_DISABLE_COMPILE_CACHE:'1',NO_COLOR:'1',CLOCK_MARKER:marker,CLOCK_RECORD:clockRecord,CLOCK_OFFSET:String(offsetMs)};
 const args=['--import',preloadFile,path.join(checkout,'openclaw.mjs'),...(kind==='gateway'?['gateway','probe','--url',`ws://127.0.0.1:${port}`,'--token','clock-fixture','--timeout','5000','--json']:['models','status','--probe','--probe-provider','openai','--probe-timeout','10000','--probe-max-tokens','8','--json'])];
 const started=performance.now();const child=spawn(process.execPath,args,{cwd:checkout,env,stdio:['ignore','pipe','pipe']});let stdout='',stderr='',watchdog=false;child.stdout.on('data',b=>stdout+=b);child.stderr.on('data',b=>stderr+=b);const timer=setTimeout(()=>{watchdog=true;child.kill('SIGKILL');},65000);
 const terminal=await new Promise(r=>child.on('close',(code,signal)=>r({code,signal})));clearTimeout(timer);
 fs.writeFileSync(path.join(root,'stdout.json'),stdout);fs.writeFileSync(path.join(root,'stderr.log'),stderr);
 const row={name,offsetMs,fail,command:[process.execPath,...args],terminal,watchdog,elapsedMs:performance.now()-started,requests,stdout,stderr,configUnchanged:hash(fs.readFileSync(configPath))===beforeHash,clock:fs.existsSync(clockRecord)?fs.readFileSync(clockRecord,'utf8').trim().split('\n').map(JSON.parse):[]};record.cases.push(row);save();
 try{
  assert.equal(watchdog,false,'Watchdog is not product RED');assert.ok(requests.length>0,'Real peer must be reached');assert.equal(row.configUnchanged,true);assert.ok(row.clock.length===1,'One external clock step observed');
  const parsed=JSON.parse(stdout);const probe=kind==='models'?parsed.auth?.probes:parsed;row.summary=probe;assert.ok(probe&&typeof probe.durationMs==='number','Probe summary with real elapsed duration required');
  if(kind==='models'){assert.equal(probe.totalTargets,1);assert.equal(probe.results[0].status,fail?'auth':'ok');assert.ok(requests.every(r=>r.authorizationIsFixture));}
  else{assert.equal(parsed.ok,!fail);assert.ok(requests.filter(r=>r.method==='connect').every(r=>r.tokenIsFixture));}
  if(offsetMs===0||expected==='head'){assert.ok(probe.durationMs>=100&&probe.durationMs<15000,'Elapsed duration incorrect: '+probe.durationMs);}else if(offsetMs>0){assert.ok(probe.durationMs>=60000);}else assert.ok(probe.durationMs<0);
  if(kind==='gateway'){const latency=parsed.targets[0].connect.latencyMs;assert.equal(typeof latency,'number');if(offsetMs===0||expected==='head')assert(latency>=100&&latency<15000,'Connection latency invalid '+latency);else if(offsetMs>0)assert(latency>=60000);else assert(latency<0);row.connectLatencyMs=latency;}
  row.result='PASS';save();console.log(JSON.stringify({kind,name,durationMs:probe.durationMs,elapsedMs:row.elapsedMs,result:row.result}));
 }finally{for(const socket of ws?.clients??[])socket.terminate();if(ws)await new Promise(r=>ws.close(r));peer.closeAllConnections();await new Promise(r=>peer.close(r));row.peerClosed=!peer.listening;save();}
}
record.result='PASS';record.observation=expected==='base'?'RED: wall-clock jumps corrupt reported elapsed duration':'GREEN: duration follows monotonic elapsed time while epoch timestamps remain wall time';save();

@clawsweeper

clawsweeper Bot commented Nov 2, 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 commands Command implementations size: S labels Nov 2, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR measures Gateway probe duration and connection latency with a monotonic clock while preserving epoch timestamps.

Example: The clock moves backward 60 seconds during a successful Gateway probe.

  • Before: The supplied base CLI reports durationMs -57961 and connection latency -59181 ms.
  • After: The supplied patched CLI reports durationMs 1761 and connection latency 740 ms.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, minimal timing repair with shipped CLI proof; the failed CI gate is not yet fully attributable.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Inspected built-CLI stdout and collector source exercise gateway probe through the real command owner and WebSocket client on Linux, with clock steps injected after an independent peer receives connect; ordinary, backward, forward, and refusal cases preserve outcomes and produce correct head timings without replacing the changed owners.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Gateway diagnostics can report negative or greatly inflated elapsed times after a system-clock correction.
Reason: Accurate elapsed diagnostics are a defined expectation, and the repair introduces no option, policy, or additional runtime machinery.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current diagnostic bug with a focused change and credible CLI evidence; no introduced correctness defect was found.

Priority: P2
Reviewed head: 8e6e6cb34d2b59f52ea5af4fd505b2a340be55cf

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway probe command discovers targets, invokes the shared WebSocket probe, and renders reachability, capabilities, and timing diagnostics.

flowchart LR
  A[Gateway probe CLI] --> B[Target discovery]
  B --> C[Shared Gateway probe]
  C --> D[WebSocket client]
  D --> E[Gateway endpoint]
  C --> F[Timing and reachability output]
Loading

Technical review

Best possible solution:

Retain the existing probe owners and use rounded monotonic differences for elapsed milliseconds.

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

Current-main wall-clock subtraction directly explains the failure, and the contributor supplies matching built-CLI base/head observations; this review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete fix: replace the elapsed-time clock at both existing owners, preserve integer milliseconds and epoch timestamps, and cover aggregate, success, and refusal paths.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 7bd7a3a adds src/commands/gateway-status.ts:146 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7bd7a3afd2c2; files: src/commands/gateway-status.ts)
  • Peter Lee: Raw commit 6256ad8 adds src/gateway/probe.ts:385 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6256ad86c9e6; files: src/gateway/probe.ts)
  • Alix-007: Raw commit b44c771 adds src/commands/gateway-status.ts:137 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b44c771f3640; files: src/commands/gateway-status.ts)

PR surface

Source 0, Tests +51, Other +2. Total +53 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 5 5 0
Tests 2 51 0 +51
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 5 58 5 +53

Labels

Label changes:

  • add P2: Clock corrections can corrupt diagnostic timing values, while connection behavior remains functional.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Clock corrections can corrupt diagnostic timing values, while connection behavior remains functional.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 November 1, 2026, 11:19 PM ET / November 2, 2026, 04:19 UTC.

@Alix-007

Alix-007 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Thanks for the review! Fixed the test lint failure; the updated exact-head CLI proof and required CI are green.

@clawsweeper

clawsweeper Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

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

commands Command implementations 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: 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