Skip to content

fix: model probes report incorrect duration after clock changes - #190852

Closed
Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-models-probe-clock-20261102
Closed

Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-models-probe-clock-20261102

Conversation

@Alix-007

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

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: models status --probe reports negative or inflated total check time when the system clock changes during the check.

User Impact

User impact: operators receive a meaningful total check duration, while start/finish timestamps retain their wall-clock meaning and request-only latency remains a separate measurement.

Why This Change Was Made

Measure the existing probe batch interval with the monotonic clock. Keep the public startedAt and finishedAt fields as epoch timestamps.

Evidence

Base bc097bf6404f34be1e57cdee8bd0b2d7f59a3070 → product head ca10aa766851cde88622485a1a1d9a99f338879f. 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 1648 1717 success
backward -58620 1429 success
forward 61413 1465 success
failure-control -58474 1523 refusal preserved

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

  • Production entry: node openclaw.mjs models status --probe --probe-provider openai --probe-timeout 10000 --probe-max-tokens 8 --json.
  • Canonical owner exercised: src/commands/models/list.probe.ts (runAuthProbes aggregate summary).
  • Recorder/readback: Parent process reads actual CLI stdout JSON, stderr, and exit status; separate loopback HTTP/SSE receiver records real product requests and synthetic credential matching.
  • Same proof command on base/head: node proof-probes.mjs "$CHECKOUT" "$OUTPUT" models "$EXPECT".
  • Normal build: node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup, exit 0 (264.36 s on head); clean build stamp matches the product commit.
  • Tests: pnpm test src/commands/models/list.probe.test.ts src/commands/models/list.status.test.ts src/commands/models/list.probe.cleanup.test.ts src/commands/models/list.probe.resources.test.ts src/commands/models/list.refresh-secrets.test.ts --maxWorkers=1: 47 tests across 5 files, exit 0, 237.39 s.
  • Test cost: Single-worker command wall clock 237.39 s (cold compiled-worker preparation and native state/profile fixtures dominate >30 s). Touched probe file alone: 8 passed, 155.83 s, including its own compiled-worker preparation.
  • Touched-file typed lint, formatting, test-line budget, and normal commit hooks passed.
  • Scope: 3 files; production +3/−4 LOC; tests +17/−0 LOC; separate allocation +2 lines for exactly 17 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. CLI models status, Gateway model-probe RPC, aggregate summary formatter, cleanup/resource ownership, and refresh-secrets callers retain the same summary shape; focused consumer suites pass.
  • Not tested: The normally built CLI dispatches the real isolated-completion owner and SDK to a loopback OpenAI-compatible HTTP/SSE peer. No paid provider endpoint, external credentials, 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-models-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": 0,
        "summary": {
          "startedAt": 1793590781274,
          "finishedAt": 1793590782922,
          "durationMs": 1648,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 244
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 0,
            "at": 8741.079557
          }
        ]
      },
      {
        "case": "backward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "startedAt": 1793590788665,
          "finishedAt": 1793590730045,
          "durationMs": -58620,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 242
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6912.525447
          }
        ]
      },
      {
        "case": "forward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": 60000,
        "summary": {
          "startedAt": 1793590795769,
          "finishedAt": 1793590857182,
          "durationMs": 61413,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 249
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 60000,
            "at": 6858.84733
          }
        ]
      },
      {
        "case": "failure-control",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-base/clock-step.mjs",
          "$BASE_CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "startedAt": 1793590803188,
          "finishedAt": 1793590744714,
          "durationMs": -58474,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "auth",
              "error": "403 Synthetic provider refusal",
              "latencyMs": 242
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 7302.507479
          }
        ]
      }
    ]
  },
  "head": {
    "head": "ca10aa766851cde88622485a1a1d9a99f338879f",
    "cleanBuild": true,
    "cases": [
      {
        "case": "ordinary",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": 0,
        "summary": {
          "startedAt": 1793590598706,
          "finishedAt": 1793590600423,
          "durationMs": 1717,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 248
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 0,
            "at": 8593.243019
          }
        ]
      },
      {
        "case": "backward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "startedAt": 1793590606059,
          "finishedAt": 1793590547488,
          "durationMs": 1429,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 251
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6826.630406
          }
        ]
      },
      {
        "case": "forward",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": 60000,
        "summary": {
          "startedAt": 1793590613142,
          "finishedAt": 1793590674607,
          "durationMs": 1465,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "ok",
              "latencyMs": 264
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": 60000,
            "at": 6914.380174
          }
        ]
      },
      {
        "case": "failure-control",
        "command": [
          "node",
          "--import",
          "$TASK/proof-models-publish-head/clock-step.mjs",
          "$CHECKOUT/openclaw.mjs",
          "models",
          "status",
          "--probe",
          "--probe-provider",
          "openai",
          "--probe-timeout",
          "10000",
          "--probe-max-tokens",
          "8",
          "--json"
        ],
        "offsetMs": -60000,
        "summary": {
          "startedAt": 1793590620186,
          "finishedAt": 1793590561709,
          "durationMs": 1523,
          "totalTargets": 1,
          "options": {
            "provider": "openai",
            "profileIds": [],
            "timeoutMs": 10000,
            "concurrency": 2,
            "maxTokens": 8
          },
          "results": [
            {
              "provider": "openai",
              "model": "openai/fixture",
              "label": "models.json",
              "source": "models.json",
              "mode": "api_key",
              "status": "auth",
              "error": "403 Synthetic provider refusal",
              "latencyMs": 244
            }
          ]
        },
        "receiverRequests": [
          {
            "method": "POST",
            "path": "/v1/chat/completions",
            "model": "fixture",
            "stream": true,
            "authorizationIsFixture": true
          }
        ],
        "terminal": {
          "code": 0,
          "signal": null
        },
        "watchdog": false,
        "configUnchanged": true,
        "peerClosed": true,
        "clock": [
          {
            "offsetMs": -60000,
            "at": 6856.843075
          }
        ]
      }
    ]
  }
}
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 commands Command implementations size: XS 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: 🦞 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 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

Measure total model-probe duration with a monotonic clock while preserving epoch timestamps and request-only latency.

Example: The clock moves backward 60 seconds during an OpenAI model probe.

  • Before: The supplied base CLI trace reports durationMs: -58620.
  • After: The supplied head CLI trace reports durationMs: 1429 while retaining wall-clock start and finish timestamps.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused, complete repair supported by discriminating shipped-CLI evidence and useful regressions.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The full collector and base/head CLI readbacks exercise runAuthProbes through normally built models status --probe on Linux with real HTTP/SSE transport to an independent loopback peer; forward and backward clock injection produces meaningful head durations and preserves refusal classification.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Model diagnostics can report negative or minute-inflated elapsed durations after a system clock correction.
Reason: A small change restores meaningful diagnostic timing while preserving the established separation between total duration and provider request latency.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete diagnostic bug still present on current main, with a minimal implementation and no identified defects.

Priority: P2
Reviewed head: ca10aa766851cde88622485a1a1d9a99f338879f

Before merge

None.

Findings

None.

Agent review details

How this fits together

CLI model-status checks and Gateway model probes call runAuthProbes, which plans credential checks, dispatches isolated completions, and returns diagnostic results.

flowchart TD
  A[Models status CLI] --> C[runAuthProbes]
  B[Gateway model probe] --> C
  C --> D[Credential target planner]
  D --> E[Isolated completion]
  E --> F[Provider HTTP transport]
  F --> G[Probe results and elapsed summary]
Loading

Technical review

Best possible solution:

Use the existing probe owner’s monotonic clock for aggregate elapsed time, as this PR does.

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

Current-main source directly exposes wall-clock subtraction, and the contributor’s built-CLI base traces demonstrate negative and inflated durations; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete fix: elapsed duration becomes independent of clock corrections without changing timestamps, target selection, credential handling, cleanup, or request latency.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c518cbd adds src/commands/models/list.probe.ts:778 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c518cbdbd0e5; files: src/commands/models/list.probe.ts)
  • Ayaan Zaidi: Raw commit 7af9595 adds src/commands/models/list.probe.ts:317 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7af9595a5e49; files: src/commands/models/list.probe.ts)

PR surface

Source -1, Tests +17, Other +2. Total +18 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 3 4 -1
Tests 1 17 0 +17
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 3 22 4 +18

Labels

Label changes:

  • add P2: Clock corrections corrupt diagnostic duration values without breaking probe execution or ordinary model requests.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Clock corrections corrupt diagnostic duration values without breaking probe execution or ordinary model requests.
  • 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 November 1, 2026, 11:17 PM ET / November 2, 2026, 04:17 UTC.

@Alix-007

Alix-007 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper Thanks for the review!

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 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: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants