Skip to content

fix: Pi session catalog stays stale after clock changes - #190846

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

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

Conversation

@Alix-007

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

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: new Pi sessions remain missing from the session catalog beyond its 32-second refresh window when the system clock moves backward.

User Impact

User impact: newly created Pi sessions become discoverable after the existing refresh window despite clock corrections, without premature directory rescans after a forward correction.

Why This Change Was Made

Measure the process-local candidate snapshot lifetime with the monotonic clock. File timestamps, catalog rows, the existing 32-second policy, and continuation eligibility keep their existing contracts.

Evidence

Base bc097bf6404f34be1e57cdee8bd0b2d7f59a3070 → product head 2998500fa946349057da3b47820f194ed9ab270e. Ubuntu 24 Linux container, Node v26.12.1, built OpenClaw 2026.10.9. Network disabled at the container boundary; only isolated loopback WebSocket traffic. The published collector uses the pre-existing local test-image name; its exact image ID is sha256:39a6e6f0c5f1fc700b3eab6c19b973f8c01105e2a5efa37c264d0d8130353873. The inner Node collector is included separately and needs only the normal build and isolated HOME/state/workspace directories. At most one authenticated client is active; reconnects avoid the separate Gateway stale-while-revalidate page cache while retaining the same process-local Pi cache.

Readback Base thread IDs Head thread IDs
warm-original pi-clock-first pi-clock-first
within-ttl-control pi-clock-first pi-clock-first
backward-clock-after-real-ttl pi-clock-first pi-clock-first, pi-clock-second
restored-clock-positive-control pi-clock-first, pi-clock-second pi-clock-first, pi-clock-second

Warm and pre-expiry lists each contain 1 original thread and 0 new threads; restored-clock control contains 2 threads; both source files and config unchanged; Gateway exits 0 and port closes.

  • Production entry: Normally built openclaw.mjs gateway run; authenticated sessions.catalog.list with catalogId=pi, agentId=main, hostIds=[gateway], limitPerHost=20, allowPartialResults=false.
  • Canonical owner exercised: extensions/acpx/src/pi-session-store.ts (Pi candidate discovery cache).
  • Recorder/readback: Independent official GatewayClient reads native catalog JSON; synthetic Pi JSONL files and configuration are hashed before/after; actual Gateway exit and port closure recorded.
  • Same proof command on base/head: python3 proof-pi.py --checkout "$CHECKOUT" --node-dir "$NODE_DIR" --output "$OUTPUT" --expect "$EXPECT".
  • Normal build: node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup, exit 0 (251.74 s on head); clean build stamp matches the product commit.
  • Tests: pnpm test extensions/acpx/src/pi-session-catalog.test.ts --maxWorkers=1: 15 passed, 40.10 s; catalog plus upstream-activity consumer suite: 20 passed across 2 files, 34.06 s, exit 0.
  • Test cost: Touched file single-worker wall clock 40.10 s; cold compiled worker preparation dominates the >30 s command, individual cases run in milliseconds. Consumer batch 34.06 s.
  • Touched-file typed lint, formatting, test-line budget, and normal commit hooks passed.
  • Scope: 3 files; production +2/−2 LOC; tests +22/−2 LOC; separate allocation +2 lines for exactly 20 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. Catalog list/read and upstream activity baseline consume the shared candidate discovery owner; pi-session-catalog and pi-session-upstream-activity tests pass (20 tests across 2 files).
  • Not tested: Native Pi session-file discovery is exercised through the real built Gateway and bundled acpx plugin with synthetic valid Pi JSONL. The Pi CLI process, ACP continuation, paired-node execution, macOS/Windows, and UI rendering were not exercised. No provider calls, channel messages, public configuration/schema/default, 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,
    "realCacheAgeMs": 33002.796116,
    "rpcs": [
      {
        "name": "warm-original",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-base-v3/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793588854439.4705,
                      "recencyAt": 1793588854439.4705,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first"
        ],
        "elapsedMs": 418.52101799999946
      },
      {
        "name": "within-ttl-control",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-base-v3/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793588854439.4705,
                      "recencyAt": 1793588854439.4705,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first"
        ],
        "elapsedMs": 15.459656000002724
      },
      {
        "name": "backward-clock-after-real-ttl",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-base-v3/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793588854439.4705,
                      "recencyAt": 1793588854439.4705,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first"
        ],
        "elapsedMs": 5.951655999997456
      },
      {
        "name": "restored-clock-positive-control",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-second",
                      "name": "Synthetic pi-clock-second",
                      "cwd": "$TASK/proof-pi-base-v3/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793588875852.084,
                      "recencyAt": 1793588875852.084,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    },
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-base-v3/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793588854439.4705,
                      "recencyAt": 1793588854439.4705,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first",
          "pi-clock-second"
        ],
        "elapsedMs": 6.612996000003477
      }
    ],
    "sourceFilesUnchanged": true,
    "configReadsUnchanged": true,
    "cleanup": {
      "gateway": {
        "code": 0,
        "signal": null
      },
      "forced": false,
      "offsetRestored": true,
      "portClosed": true
    }
  },
  "head": {
    "head": "2998500fa946349057da3b47820f194ed9ab270e",
    "cleanBuild": true,
    "realCacheAgeMs": 33002.30611799999,
    "rpcs": [
      {
        "name": "warm-original",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590156576.611,
                      "recencyAt": 1793590156576.611,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first"
        ],
        "elapsedMs": 142.4966740000018
      },
      {
        "name": "within-ttl-control",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590156576.611,
                      "recencyAt": 1793590156576.611,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first"
        ],
        "elapsedMs": 3.6305470000006608
      },
      {
        "name": "backward-clock-after-real-ttl",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-second",
                      "name": "Synthetic pi-clock-second",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590176602.12,
                      "recencyAt": 1793590176602.12,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    },
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590156576.611,
                      "recencyAt": 1793590156576.611,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first",
          "pi-clock-second"
        ],
        "elapsedMs": 8.912336000001233
      },
      {
        "name": "restored-clock-positive-control",
        "method": "sessions.catalog.list",
        "params": {
          "catalogId": "pi",
          "agentId": "main",
          "hostIds": [
            "gateway"
          ],
          "limitPerHost": 20,
          "allowPartialResults": false
        },
        "value": {
          "catalogs": [
            {
              "id": "pi",
              "label": "Pi",
              "capabilities": {
                "continueSession": true,
                "archive": false,
                "openTerminal": true
              },
              "hosts": [
                {
                  "hostId": "gateway",
                  "label": "Local Pi",
                  "kind": "gateway",
                  "connected": true,
                  "sessions": [
                    {
                      "threadId": "pi-clock-second",
                      "name": "Synthetic pi-clock-second",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590176602.12,
                      "recencyAt": 1793590176602.12,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    },
                    {
                      "threadId": "pi-clock-first",
                      "name": "Synthetic pi-clock-first",
                      "cwd": "$TASK/proof-pi-head/workspace",
                      "status": "stored",
                      "createdAt": 1783936800000,
                      "updatedAt": 1793590156576.611,
                      "recencyAt": 1793590156576.611,
                      "source": "pi-cli",
                      "modelProvider": "pi",
                      "archived": false,
                      "canContinue": false,
                      "canArchive": false,
                      "canOpenTerminal": false
                    }
                  ]
                }
              ]
            }
          ]
        },
        "ids": [
          "pi-clock-first",
          "pi-clock-second"
        ],
        "elapsedMs": 4.4291119999979855
      }
    ],
    "sourceFilesUnchanged": true,
    "configReadsUnchanged": true,
    "cleanup": {
      "gateway": {
        "code": 0,
        "signal": null
      },
      "forced": false,
      "offsetRestored": true,
      "portClosed": true
    }
  }
}
Complete proof collector source

proof-pi-inner.mjs (sha256 e039b33adcd23d9186a83152fb4ed44249b375d954a327062e425df9faea0e9f):

import assert from 'node:assert/strict';
import {spawn,execFile} from 'node:child_process';
import {createHash} from 'node:crypto';
import fs from 'node:fs';
import net from 'node:net';
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 hash=x=>createHash('sha256').update(x).digest('hex');const runFile=promisify(execFile),started=performance.now();
const record={expected,rpcs:[],stages:[],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(name);};
const bounded=async(p,ms,label)=>{let t;try{return await Promise.race([p,new Promise((_,rej)=>{t=setTimeout(()=>rej(Error(label)),ms);})]);}finally{clearTimeout(t);}};
const offset=path.join(output,'clock-offset'),clockLog=path.join(output,'clock.jsonl');fs.writeFileSync(offset,'0');
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.PI_CLOCK_OFFSET,'utf8'));if(offset!==last){last=offset;fs.appendFileSync(process.env.PI_CLOCK_LOG,JSON.stringify({pid:process.pid,offsetMs:offset,at:performance.now()})+'\\n');}return original()+offset;};`;
fs.writeFileSync(path.join(output,'clock-step.mjs'),preload);record.preloadSha256=hash(preload);
const piRoot=path.join(output,'pi-sessions');fs.mkdirSync(piRoot);const files=new Map();
function addPi(id){const file=path.join(piRoot,id+'.jsonl');const content=[{type:'session',version:3,id,timestamp:'2026-07-13T10:00:00Z',cwd:path.join(output,'workspace')},{type:'session_info',id:'info-'+id,parentId:null,timestamp:'2026-07-13T10:00:01Z',name:'Synthetic '+id},{type:'message',id:'user-'+id,parentId:null,timestamp:'2026-07-13T10:00:02Z',message:{role:'user',content:'Synthetic catalog fixture'}}].map(JSON.stringify).join('\n')+'\n';fs.writeFileSync(file,content);files.set(file,hash(content));}
let gateway,client,gatewayClosed;
try{
 addPi('pi-clock-first');
 const configPath=process.env.OPENCLAW_CONFIG_PATH;const config={plugins:{allow:['acpx'],entries:{acpx:{enabled:true}}},cron:{enabled:false},agents:{defaults:{workspace:path.join(output,'workspace')}},gateway:{mode:'local',port:19486,controlUi:{enabled:false},auth:{mode:'token',token:'synthetic-pi-clock-fixture'}}};fs.writeFileSync(configPath,JSON.stringify(config,null,2)+'\n');
 const doctorArgs=[path.join(checkout,'openclaw.mjs'),'doctor','--client-credentials','--repair','--non-interactive','--json'];const d=await runFile(process.execPath,doctorArgs,{cwd:checkout,env:process.env,timeout:60000,maxBuffer:10000000});fs.writeFileSync(path.join(output,'doctor.stdout'),d.stdout);fs.writeFileSync(path.join(output,'doctor.stderr'),d.stderr);record.doctor=JSON.parse(d.stdout);assert.equal(record.doctor.ok,true);record.configBeforeReadsSha256=hash(fs.readFileSync(configPath));stage('official-client-bootstrap');
 const argv=['--import',path.join(output,'clock-step.mjs'),path.join(checkout,'openclaw.mjs'),'gateway','run','--bind','loopback','--auth','token','--token','synthetic-pi-clock-fixture','--port','19486'];const stdout=fs.openSync(path.join(output,'gateway.stdout'),'w'),stderr=fs.openSync(path.join(output,'gateway.stderr'),'w');gateway=spawn(process.execPath,argv,{cwd:checkout,env:{...process.env,PI_CODING_AGENT_SESSION_DIR:piRoot,PI_CLOCK_OFFSET:offset,PI_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,...argv];
 const hello=Promise.withResolvers();client=new GatewayClient({url:'ws://127.0.0.1:19486',token:'synthetic-pi-clock-fixture',clientName:'cli',mode:'cli',scopes:['operator.admin'],minProtocol:4,maxProtocol:4,requestTimeoutMs:20000,onHelloOk:x=>{record.hello=x;hello.resolve();},onConnectError:e=>{record.lastConnectError=String(e);}});client.start();await bounded(Promise.race([hello.promise,gatewayClosed.then(x=>{throw Error('Gateway exited '+JSON.stringify(x));})]),50000,'Gateway readiness');stage('normal-gateway-hello');
 const pluginReadyAt=performance.now();await bounded(new Promise((resolve,reject)=>{const timer=setInterval(()=>{const log=fs.readFileSync(path.join(output,'gateway.stdout'),'utf8');if(/embedded acpx runtime backend registered lazily/u.test(log)){clearInterval(timer);resolve();}else if(performance.now()-pluginReadyAt>55000){clearInterval(timer);reject(Error('ACPX startup did not finish'));}},250);}),60000,'ACPX startup');stage('native-acpx-plugin-ready');
 const list=async(name)=>{if(record.rpcs.length){await bounded(client.stopAndWait(),5000,'Previous client closed');const ready=Promise.withResolvers();client=new GatewayClient({url:'ws://127.0.0.1:19486',token:'synthetic-pi-clock-fixture',clientName:'cli',mode:'cli',scopes:['operator.admin'],minProtocol:4,maxProtocol:4,requestTimeoutMs:20000,onHelloOk:()=>ready.resolve(),onConnectError:e=>{record.lastConnectError=String(e);}});client.start();await bounded(ready.promise,10000,'Fresh connection readiness');}const params={catalogId:'pi',agentId:'main',hostIds:['gateway'],limitPerHost:20,allowPartialResults:false};const at=performance.now();const value=await client.request('sessions.catalog.list',params);const ids=value.catalogs.flatMap(c=>c.hosts.flatMap(h=>h.sessions.map(s=>s.threadId))).sort();record.rpcs.push({name,method:'sessions.catalog.list',params,value,ids,elapsedMs:performance.now()-at});save();return ids;};
 const warm=await list('warm-original');assert.deepEqual(warm,['pi-clock-first']);const warmedAt=performance.now();stage('warm-original');addPi('pi-clock-second');assert.deepEqual(await list('within-ttl-control'),['pi-clock-first']);
 fs.writeFileSync(offset,'-60000');const waitMs=Math.max(0,33000-(performance.now()-warmedAt));await new Promise(resolve=>setTimeout(resolve,waitMs));record.realCacheAgeMs=performance.now()-warmedAt;assert(record.realCacheAgeMs>=33000);const after=await list('backward-clock-after-real-ttl');assert.deepEqual(after,expected==='base'?['pi-clock-first']:['pi-clock-first','pi-clock-second']);stage('backward-clock-after-real-ttl');
 fs.writeFileSync(offset,'0');assert.deepEqual(await list('restored-clock-positive-control'),['pi-clock-first','pi-clock-second']);stage('restored-clock-positive-control');
 record.sourceFilesUnchanged=[...files].every(([f,h])=>hash(fs.readFileSync(f))===h);record.configReadsUnchanged=hash(fs.readFileSync(configPath))===record.configBeforeReadsSha256;assert(record.sourceFilesUnchanged&&record.configReadsUnchanged);record.clock=fs.readFileSync(clockLog,'utf8').trim().split('\n').map(JSON.parse);assert(record.clock.some(x=>x.offsetMs===-60000));record.result='PASS';record.observed=expected==='base'?'RED: new Pi session missing after actual 32s TTL':'GREEN: new Pi session appears after actual 32s TTL despite clock rollback';
}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').catch(e=>record.cleanup.clientError=String(e));if(gateway&&gateway.exitCode===null)gateway.kill('SIGTERM');if(gatewayClosed){try{record.cleanup.gateway=await bounded(gatewayClosed,25000,'Gateway cleanup');record.cleanup.forced=false;}catch{gateway.kill('SIGKILL');record.cleanup.gateway=await bounded(gatewayClosed,5000,'Forced cleanup');record.cleanup.forced=true;}}
 record.cleanup.offsetRestored=fs.readFileSync(offset,'utf8')==='0';record.cleanup.portClosed=await new Promise(resolve=>{const s=net.connect({host:'127.0.0.1',port:19486});s.once('error',()=>resolve(true));s.once('connect',()=>{s.destroy();resolve(false);});});record.elapsedMs=performance.now()-started;
 if(record.result==='PASS'&&(record.cleanup.forced||record.cleanup.gateway?.code!==0||record.cleanup.clientError||!record.cleanup.portClosed)){record.result='HOLD';record.error='Cleanup failure';process.exitCode=1;}save();console.log(JSON.stringify({result:record.result,observed:record.observed,cleanup:record.cleanup}));
}

proof-pi.py (sha256 d00ce59333544eccc1feb599572cbf66e2070b84d9a0f8d35401a55c88367c26):

#!/usr/bin/env python3
"""Run a frozen normal-built Gateway and native Pi catalog fixture in the existing private 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()
image='alix-openclaw-webkit:pw1.64.1-ubuntu24'
meta={'head':head,'buildInfo':info,'buildStamp':stamp,'expected':a.expect,'collectorSha256':sha(Path(__file__)),'innerSha256':sha(root/'proof-pi-inner.mjs'),'imageId':subprocess.check_output(['docker','image','inspect',image,'--format','{{.Id}}'],text=True).strip(),'startedAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())}
name='alix-pi-cache-clock-'+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/"proof-pi-inner.mjs"}:{root/"proof-pi-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'),'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/'proof-pi-inner.mjs'),str(checkout),str(out),a.expect]
meta['argv']=argv;started=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()-started)*1000);meta['finishedAt']=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
 (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']

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

@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

This PR measures the Pi session discovery cache lifetime with monotonic time so system-clock corrections do not change its refresh interval.

Example: Create pi-clock-second after warming the catalog, move the wall clock backward 60 seconds, and wait 33 seconds.

  • Before: The catalog still returns only pi-clock-first.
  • After: The catalog returns both pi-clock-first and pi-clock-second.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal owner-level repair with relevant regression coverage, supplied shipped-entry-point proof, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied Linux/Node evidence exercises the changed Pi candidate-cache owner through a normally built Gateway and authenticated catalog RPC: after a 60-second rollback and 33 seconds of elapsed time, the head discovers the second session while the base remains stale; warm-cache and restored-clock controls behave as expected.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: New native Pi sessions can remain missing beyond the catalog's refresh window after the system clock moves backward.
Reason: The patch restores the existing elapsed-time freshness contract while preserving the owner's scan cadence and public behavior.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Keep this PR open for merging: it fixes a concrete cache-expiry bug still present on current main, with no actionable defects found.

Priority: P2
Reviewed head: 2998500fa946349057da3b47820f194ed9ab270e

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: A red-on-base run of the committed clock-step tests is not recorded; the supplied shipped-Gateway scenario does demonstrate base failure and head success.
Agent review details

How this fits together

The bundled acpx plugin discovers native Pi session files and projects them into catalog responses; its process-local candidate cache bounds directory scanning.

flowchart LR
  A[Catalog client] --> B[Gateway catalog RPC]
  B --> C[Pi catalog provider]
  C --> D[Candidate cache]
  E[Monotonic clock] --> D
  D --> F[Pi session files]
  F --> G[Session summaries]
  G --> B
Loading

Technical review

Best possible solution:

Merge the focused monotonic-clock repair in the existing Pi candidate-cache owner.

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

Current-main source establishes the faulty wall-clock comparison, and supplied base/head Gateway readbacks demonstrate the failure and repair; no target code was executed during this review.

Is this the best way to solve the issue?

Yes: replacing both duration-clock reads fixes the cause without adding state, wrappers, configuration, or another cache owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Pi candidate snapshot lifetime keeps the original intent (9ae79ee: Avoid scanning the Pi session store on every catalog poll by retaining a bounded 32-second candidate snapshot.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main defect: Current main still creates and compares candidate-cache expiry using Date.now(), so a backward wall-clock correction extends the snapshot lifetime. (extensions/acpx/src/pi-session-store.ts:179, 5396fbf92a3f)
  • Smallest complete repair: The introduced production hunks replace both clock reads with performance.now(); cache identity, TTL, eviction, rejected-scan cleanup, and file timestamps remain intact. (extensions/acpx/src/pi-session-store.ts:179, 2998500fa946)
  • Original cache intent: Merged perf(catalog): cadence-proof provider caches and parallelize the Claude scan #115259 introduced the 32-second candidate snapshot to avoid repeated directory scans; this repair preserves that decision. (extensions/acpx/src/pi-session-store.ts:179, 9ae79eed2d06)
  • Shipped-entry-point proof: The fully retrieved PR body includes collector source and authenticated sessions.catalog.list readbacks from normally built base/head Gateways: rollback leaves the base stale after 33 seconds while the head discovers the new session, with unchanged fixture/config hashes and successful cleanup. Captured source-body SHA-256: 9411ecf329bc489811fab04647df077141b9119982b3213b774f2b68c031480e. (2998500fa946)
  • Head validation and merge state: GitHub reports the reviewed head cleanly mergeable; ci-gate, dependency-review, and security-sensitive-review statuses pass, and paginated check runs show only the cancelled auto-response job outside successful, skipped, or neutral conclusions. (2998500fa946)
  • History inspection limit: The rename-following history walk reached an unavailable creation-era object; the cache-introducing commit and its complete relevant patch were independently available. (extensions/acpx/src/pi-session-store.ts, 5396fbf92a3f)

PR surface

Source 0, Tests +20, Other +2. Total +22 across 3 files. Added test files: 0.

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

Review metrics

Metric Value Why it matters
Production versus test LOC Production +2/−2; tests +22/−2 Production remains the same size; test growth protects distinct backward-clock staleness and forward-clock premature-expiry failures.

Labels

Label changes:

  • add P2: Clock corrections can delay discovery of native Pi sessions, with limited impact confined to catalog freshness.
  • 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 can delay discovery of native Pi sessions, with limited impact confined to catalog freshness.
  • 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:07 PM ET / November 2, 2026, 04:07 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

extensions: acpx 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