Skip to content

fix(plugins): avoid blocking foreground work during reload recovery capture - #198262

Merged
RomneyDa merged 3 commits into
mainfrom
openclaw/retro-508-rollback-adaptation
Nov 16, 2026
Merged

RomneyDa merged 3 commits into
mainfrom
openclaw/retro-508-rollback-adaptation

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes foreground work being blocked while plugin reload captures rollback source.

User Impact

Plugin reload can acquire rollback custody without synchronously copying the entire source tree on the Gateway event loop. Existing cancellation, recovery, and custody policies are preserved; no configuration or migration is required. Existing per-entry metadata/native-reference operations remain synchronous, so this is not a universal latency guarantee.

Why This Change Was Made

Initial executable binding was merged in #198302, which moved executable artifacts and recovery ownership to the host. Merely resolving the test conflicts would leave this PR's old worker-only asynchronous wrapper unreachable.

This integration awaits asynchronous filesystem copying through the existing host-local source owner before the cancellation checkpoint and drain. Synchronous and asynchronous callers share copy, relocation, native-reference validation, and cleanup semantics. Frozen-source recovery applies the same frozen aliases and closure restrictions to both paths. Retained source custody and recovery forks remain synchronous. The obsolete worker wrapper is removed; there is no second capture owner, new transport, or new timeout policy.

Adapted from Wes (@akmad)'s work in #181491 (original head 7d13ecb8bb33dc7d0e2f96ad3dc287a60c8525e6). The contributor branch was not executed. This is a current-main adaptation, not a stacked PR.

Current Integration Evidence — November 16, 2026

Head ec3c8e4803c7adce0058f3f0641dabcb8d1287af integrates main d0e09e419d7e2446f13c0277bfaa8a733876c612.

  • Both conflicting test files resolved; main's physical-cleanup, retained-provider, native, and frozen-source assertions preserved.
  • 217 tests across 10 files passed: real host-local copy progress/cleanup, pre-drain cancellation, native and frozen recovery/forks, source-owner lifetime, and changed direct test consumers.
  • Red/green owner replay: substituting only the source-lookup owner from the pinned main commit made the real foreground-copy assertion fail: the recovery directory was already populated before foreground work ran. Restoring the repaired owner passed. This is an isolated owner replay, not a full-base end-to-end run.
  • Plugin-platform and Gateway-server test typechecks, scoped typed lint (19 source/test files), formatting, and git diff --check passed. Documentation link audit: 16,653 checked, zero broken.
  • Independent read-only implementation review against the pinned main found no blocking correctness issues. It checked the local copy owner, native cleanup, frozen wrapping, complete await chain, and preserved main regressions. This was a subagent review, not local ClawSweeper/autoreview; neither local reviewer CLI nor a bound autoreview tool is available in this session. The subsequent documentation-only correction describes the host-local owner.
  • The foreground assertion proves that real copying yields at its start, not a worst-case latency bound throughout a large copy. New-head CI is separate from the historical green checks below.

Historical Proof Before This Integration

The original head 6061ad40beacd4179a814a0d2a0729d50f70e64d had passing plugin/Gateway tests, runtime build, typechecks, lint/format/docs checks, independent reviews, and green exact-head CI. Those results are historical, not current-head CI.

November 15 sanitized traces, limitations, and reproducible harness:

  • Exercised that original head and pre-PR base 9d28854c4322988d1ad1443604e365547b224695 in isolated state through public plugins.reload, health, and a synthetic plugin RPC. No live Gateway was changed.
  • With an identical injected 1,500 ms hold at the then-existing worker recovery-copy boundary, base health took 1,563 ms and completed after capture. Candidate observations were 8 ms and 111 ms, before capture ended. These are instrumented scheduling observations, not an uninstrumented benchmark or measurements of the newly integrated head.
  • Failed replacement activation recovered the original frozen dependency in a fresh instance despite mutated disk source. The observed recovery directory was removed after acknowledged clean shutdown.
  • Candidate/base builds and 46 focused tests passed; independent proof review verified the evidence and limitations.
  • Remaining live-model gap: the real agent/model request returned credit_balance_exhausted / insufficient_quota. No successful model response is claimed, and the attempt was not replaced by a mock. A usable funded credential is needed for that portion of the proof.

Worked on by

RomneyDa and others added 2 commits November 13, 2026 12:40
…apture

Adapt the rollback capture approach from Wes (@akmad), #181491, to the current worker-owned recovery lifecycle. Preserve synchronous frozen-source and custody-fork contracts.

Co-authored-by: Wes <[email protected]>

Co-authored-by: vincentkoc <[email protected]>

Co-authored-by: RomneyDa <[email protected]>
…apture

Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 630a3a3a-acae-45ed-863a-3c57e7c36035
@clawsweeper

clawsweeper Bot commented Nov 13, 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 docs Improvements or additions to documentation gateway Gateway runtime size: M labels Nov 13, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes plugin reload await rollback-source capture through the existing worker transport.

Example: Reload the external plugin recovery-cleanup while foreground Gateway work is queued.

  • Before: The Gateway synchronously waits for the worker's rollback-source copy.
  • After: Foreground work can progress while reload awaits the copy before draining the plugin.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-consistent, but the required current-runtime behavior proof is absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Plugin reload can stall unrelated Gateway foreground work while copying previous plugin source for rollback.
Reason: The maintainer-authored direction repairs a concrete availability problem without new configuration, capture ownership, or timeout policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a blocking path still present on main, and no actionable correctness defect was found in the pinned diff.

Priority: P1
Reviewed head: 6061ad40beacd4179a814a0d2a0729d50f70e64d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide a redacted current-head isolated Gateway run showing foreground requests progressing during rollback capture and a successful subsequent plugin/model turn, with comparable baseline and candidate measurements.
Agent review details

How this fits together

The Gateway reload owner acquires previous-source custody from plugin instances before resource handoff; the retained preparation worker produces that custody for recovery or disposal.

flowchart TD
  A[Plugin reload request] --> B[Gateway reload owner]
  B --> C[Plugin instance cleanup lease]
  C --> D[Async worker transport]
  D --> E[Existing source capture owner]
  E --> F[Rollback custody]
  F --> G[Cancellation checkpoint and drain]
  F --> H[Recovery or disposal]
Loading

Technical review

Best possible solution:

Retain the existing capture owner and synchronous custody contracts while awaiting worker-backed rollback capture before draining.

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

Current-main source establishes the synchronous rollback-capture path into worker polling; the PR reports a regression that fails on base at the worker-reply assertion, but no target code was executed during this review.

Is this the best way to solve the issue?

The patch is a small root-cause repair: it selects the existing asynchronous worker transport, propagates promises through the internal callers, and preserves cleanup ownership and capture-before-drain ordering.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Rollback source and runtime recovery ownership keeps the original intent (967a868: Recover previous code and settings with fresh runtime resources after replacement fails, including when installed source has changed or disappeared.)
  • Worker-backed recovery transport changes intended behavior with a stated reason (a99f797: Retain external source preparation and recovery custody in a worker, with owner-controlled capture lifetimes; this PR explains why the Gateway must await rollback capture asynchronously.)
  • Asynchronous recovery disposal keeps the original intent (34fee3f: Keep foreground work responsive during cleanup while still joining physical snapshot release.)
  • Frozen-source recovery aliases and closure restrictions keeps the original intent (8e6129a: Preserve immutable installed-source identity, dependency closure, and independently retained reader custody.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current-main blocking path: Current main invokes captureRecoverySource synchronously from module-loader recovery; ordinary synchronous worker methods enter requestSync and its Atomics.wait loop. (src/plugins/plugin-module-loader-recovery.ts:119, f978e54df2d8)
  • Focused owner-preserving change: The introduced diff adds an asynchronous transport to the existing worker-owned capture operation and migrates its consumers without replacing synchronous custody and fork operations. (src/plugins/plugin-generation-preparation.worker.ts:406, 6061ad40beac)
  • Capture-before-drain ordering: Reload awaits capture before the existing cancellation checkpoint, resource handoff, and drain; the lifecycle finalizer joins recovery disposal on failure. (src/gateway/server-plugin-reload.ts:251, 6061ad40beac)
  • Regression coverage: The changed regression uses the real preparation worker to observe foreground progress before capture replies; separate coverage checks cancellation before drain, frozen-source aliases, custody forks, and owner-controlled capture deadlines. (src/gateway/server-plugin-reload-recovery.test.ts:68, 6061ad40beac)
  • Credited predecessor and proof limits: Wes (@akmad)'s predecessor supplies historical Gateway measurements and explicitly discloses first-turn latency increases; this PR credits that work and states that its current adaptation has no live Gateway/model-turn workload or large-package benchmark.
  • Earlier lifecycle intent: The original recovery work preserves previous code through resource teardown, while the later cleanup repair deliberately awaits physical disposal; this PR retains both contracts. (src/plugins/plugin-module-loader-recovery.ts:62, 34fee3f99fbe)

Likely related people:

  • Peter Steinberger: Raw commit dfb91dc adds src/plugins/plugin-generation-preparation.worker.ts:98 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dfb91dc29046; files: src/plugins/plugin-generation-preparation.worker.ts)
  • Hannes Rudolph: Raw commit 34fee3f adds src/plugins/plugin-module-loader-recovery.ts:83 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 34fee3f99fbe; files: src/plugins/plugin-module-loader-recovery.ts)
  • Krzysztof Kisiel: Raw commit a99f797 adds src/plugins/plugin-generation-preparation.worker.ts:82 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a99f797f39ce; files: src/plugins/plugin-generation-preparation.worker.ts)

PR surface

Source +12, Tests +74, Docs +3. Total +89 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 27 15 +12
Tests 10 138 64 +74
Docs 1 4 1 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 169 80 +89

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Rollback capture can block the Gateway event loop and delay unrelated foreground requests during plugin reload.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 13, 2026, 7:55 AM ET / 12:55 UTC.

@RomneyDa

Copy link
Copy Markdown
Member Author

Current-head isolated Gateway rollback proof — November 15, 2026

Focused capture/recovery proof passed; successful real-model completion remains blocked by provider credit. No production source changes. This exercises rollback capture, not initial binding (#198302).

Both executables were built with frozen-lockfile installs: candidate 6061ad4; actual pre-PR base 9d28854, archived into an independent build directory. Node v26.12.1, same synthetic external plugin, loopback WebSocket RPCs, isolated state/config/workspace, same 1,500 ms injected hold immediately before the existing worker's real recovery copy. No live Gateway or shared checkout permissions changed.

Observed trace Base Candidate Candidate repeat
Real recovery copy duration 1,510 ms 1,502 ms 1,502 ms
Health sent after capture began 1 ms 10 ms 10 ms
Foreground health round trip 1,563 ms 8 ms 111 ms
Health completed before copy ended No Yes Yes
Frozen marker restored in a fresh plugin instance Yes Yes Yes
Observed recovery directory removed after clean shutdown Yes Yes Yes

These are instrumented scheduling observations, not a natural large-package latency benchmark or production latency guarantee. The copy ran on worker thread 14 in all runs; the base's synchronous wait still blocked the main event loop. Candidate repeat overlapped the independent baseline build, so round trips are illustrative; the asserted before/after-copy ordering is the invariant. Base success means the harness reproduced expected blocking, not that base meets the responsiveness requirement.

Executed product flow and sanitized trace

  1. Start the built real Gateway, reach readiness, connect the operator WebSocket, and call the synthetic plugin's registered rollback.probe: frozen-original.
  2. Inspect plugin for its capability acknowledgment token; mutate its on-disk dependency to mutated-disk and replacement entry to throw EXPECTED_ROLLBACK_PROOF_REPLACEMENT_FAILURE. Arm the observer only now, after initial loading.
  3. Invoke public plugins.reload. The observer selects only fs.cpSync called from production copyRecoverySource; it records begin/end, injects the fixed hold, and still executes the original copy. Send public health after begin and assert its completion ordering.
  4. Reload returns UNAVAILABLE, phase activate, committed:false, expected replacement error. A subsequent real plugin RPC succeeds, returning frozen-original with a different module-level UUID: newly executed frozen code, not a stale callable. The captured target physically contains the original dependency despite the disk mutation and remains present after rollback.
  5. Request supported IPC shutdown, require acknowledgment and clean exit, then assert that the intercepted recovery target directory is absent. This does not claim every unrelated cache/reference was enumerated.

A separate real agent/model request was attempted through public sessions.create, agent, and agent.wait using the live benchmark verifier. The provider returned credit_balance_exhausted / insufficient_quota; the live-result assertion failed. It was not retried or replaced by a mock. Later focused runs explicitly skipped that step. A funded/usable provider credential is still required to close the successful-model-turn portion of the review request. No successful model response is claimed.

Four earlier boots failed before readiness on secure temporary/log-root setup; they establish nothing about rollback. The real logger preflight passed once the fixture used an explicit task-owned logging.file; only task-owned scratch permissions were changed.

Fresh validation: runtime builds passed for candidate and base; current-head focused regression suites passed 46 tests in 3 files (Gateway recovery, runtime recovery, source-snapshot artifact); git diff --check passed. An independent read-only review validated candidate capture/frozen-source/cleanup claims and narrowed the limitations above. Exact-head checks currently show 72 successful CheckRuns, 87 skipped, 1 neutral, and 3 successful status contexts; no failures/pending. Existing author attribution and source are unchanged.

Reproduce: complete harness and observer (no credentials, private paths, or raw logs)

Run from an isolated checkout at the candidate SHA. The code uses existing repository benchmark helpers, a synthetic plugin, and fresh loopback ports. It does not invoke the live Gateway. Save the two files below at the stated paths. Commands intentionally skip billing-dependent model proof; omitting ROLLBACK_PROOF_SKIP_MODEL makes a real provider request and can incur usage.

umask 077
mkdir -p .openclaw/tmp/198262
chmod 700 .openclaw/tmp/198262
pnpm install --frozen-lockfile
pnpm build:runtime
mkdir .openclaw/tmp/198262/baseline
git archive 9d28854c4322988d1ad1443604e365547b224695 | tar -x -C .openclaw/tmp/198262/baseline
(cd .openclaw/tmp/198262/baseline && pnpm install --frozen-lockfile && pnpm build:runtime)
ROLLBACK_PROOF_SKIP_MODEL=1 node --import ./scripts/tsx.mjs .openclaw/tmp/198262/proof.ts candidate
ROLLBACK_PROOF_SKIP_MODEL=1 ROLLBACK_PROOF_REPO="$PWD/.openclaw/tmp/198262/baseline" ROLLBACK_PROOF_HEAD=9d28854c4322988d1ad1443604e365547b224695 node --import ./scripts/tsx.mjs .openclaw/tmp/198262/proof.ts baseline-proof

Each run name must be fresh. Reports are written under that run directory. capture-target.json, config, logs, and local state are private local evidence, not intended for public upload. The printed skip-model field records this run's historical provider blocker, not an attempted request in each skipped run. Build provenance is established by pinned checkout/archive commands; the JSON SHA field is a supplied label, not independent executable attestation.

.openclaw/tmp/198262/observe.mjs

import fs from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import { isMainThread, threadId } from 'node:worker_threads';
const root=process.env.ROLLBACK_PROOF_ROOT;
if(root){
 const cp=fs.cpSync;
 fs.cpSync=function(...args){
  const armed=root+'/armed';
  const selected=fs.existsSync(armed) && new Error().stack.includes('copyRecoverySource');
  if(!selected) return cp.apply(this,args);
  fs.unlinkSync(armed);
  fs.writeFileSync(root+'/capture-target.json',JSON.stringify({source:args[0],target:args[1]}));
  fs.writeFileSync(root+'/capture-begin.json',JSON.stringify({time:Date.now(),isMainThread,threadId}));
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,1500);
  try{return cp.apply(this,args);}finally{
   fs.writeFileSync(root+'/capture-end.json',JSON.stringify({time:Date.now(),isMainThread,threadId}));
  }
 };
 syncBuiltinESMExports();
}

.openclaw/tmp/198262/proof.ts

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { pathToFileURL } from 'node:url';
import { getFreePort } from '../../../scripts/lib/gateway-bench-probes.ts';
import { BASE_GATEWAY_BENCH_CONFIG, createGatewayBenchEnv, writeGatewayBenchConfig, buildGatewayBenchChildArgs, waitForInitialProbe } from '../../../scripts/lib/gateway-bench-runtime.ts';
import { configureLiveGatewayBenchmark, createLiveGatewayEvidence } from '../../../scripts/lib/gateway-bench-live.ts';
import { createGatewayWsClient } from '../../../scripts/lib/gateway-ws-client.ts';
import { stopChild, stopGatewayGracefully } from '../../../scripts/lib/gateway-bench-child.ts';
import { PROTOCOL_VERSION } from '../../../packages/gateway-protocol/src/version.ts';
process.umask(0o077);
const toolsRepo=process.cwd(), repo=process.env.ROLLBACK_PROOF_REPO??toolsRepo, mode=process.argv[2]??'candidate';
const root=path.resolve('.openclaw/tmp/198262/'+mode);
fs.mkdirSync(root); fs.mkdirSync(root+'/workspace'); fs.mkdirSync(root+'/tmp'); fs.mkdirSync(root+'/plugin');
const plugin='rollback-proof';
fs.writeFileSync(root+'/plugin/openclaw.plugin.json',JSON.stringify({id:plugin,activation:{onStartup:true},contracts:{gatewayMethods:['rollback.probe']},configSchema:{type:'object',additionalProperties:false}}));
fs.writeFileSync(root+'/plugin/package.json',JSON.stringify({name:plugin,version:'1.0.0',openclaw:{extensions:['./index.cjs']}}));
fs.writeFileSync(root+'/plugin/value.cjs','module.exports="frozen-original";');
fs.writeFileSync(root+'/plugin/index.cjs','const marker=require("./value.cjs"); const instance=require("node:crypto").randomUUID(); module.exports={id:"rollback-proof", register(api){api.registerGatewayMethod("rollback.probe",({respond})=>respond(true,{marker,instance}));}};');
const cfg=structuredClone(BASE_GATEWAY_BENCH_CONFIG) as Record<string,any>;
configureLiveGatewayBenchmark(cfg,root,1);
cfg.agents.defaults.skipBootstrap=true;
cfg.plugins={enabled:true,allow:[plugin,'openai'],load:{paths:[root+'/plugin']},slots:{memory:'none'},entries:{[plugin]:{enabled:true}}};
cfg.gateway.reload={mode:'off'};
// Explicit task-owned log target avoids default state/logs temp-root ancestry.
cfg.logging={file:root+'/runtime.log'};
const config=writeGatewayBenchConfig(root,cfg,{agentList:[{id:'main',workspace:root+'/workspace'}]});
const port=await getFreePort(); const entry=repo+'/dist/entry.js';
const stop=pathToFileURL(repo+'/scripts/lib/gateway-bench-stop-preload.mjs'); stop.searchParams.set('parentPid',String(process.pid));stop.searchParams.set('entry',entry);
const observer=toolsRepo+'/.openclaw/tmp/198262/observe.mjs';
const env=createGatewayBenchEnv(root,config,{caseEnv:{TMPDIR:'/tmp',OPENAI_API_KEY:process.env.OPENAI_API_KEY!,ROLLBACK_PROOF_ROOT:root,NODE_OPTIONS:'--import='+observer,OPENCLAW_SKIP_CHANNELS:'1',OPENCLAW_SKIP_GMAIL_WATCHER:'1',OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:'1',OPENCLAW_SKIP_CANVAS_HOST:'1'}});
let client:ReturnType<typeof createGatewayWsClient>|undefined;
const log=fs.createWriteStream(root+'/gateway.log');
const child=spawn(process.execPath,buildGatewayBenchChildArgs(entry,port,['--import',stop.href]),{cwd:repo,env,detached:true,stdio:['ignore','pipe','pipe','ipc']});
child.stdout!.pipe(log,{end:false});child.stderr!.pipe(log,{end:false});
const evidence:any={head:process.env.ROLLBACK_PROOF_HEAD??'6061ad40beacd4179a814a0d2a0729d50f70e64d',mode,node:process.version,holdMs:1500};
const live=createLiveGatewayEvidence(['main'],1);
async function rpc(method:string,params:any){const r=await client!.request(method,params,120000,{retryStartup:true});assert.ok(r.ok,method+': '+JSON.stringify(r.error));return r.payload as any;}
try{
 const ready=await waitForInitialProbe({port,path:'/readyz',startAt:performance.now(),deadlineAt:performance.now()+180000,isDone:()=>child.exitCode!==null});assert.equal(ready.status,200,'ready');
 client=createGatewayWsClient({url:'ws://127.0.0.1:'+port,onEvent:e=>live.onEvent(e)});await client.waitOpen();
 await rpc('connect',{minProtocol:PROTOCOL_VERSION,maxProtocol:PROTOCOL_VERSION,client:{id:'gateway-client',version:'1.0.0',platform:process.platform,mode:'backend'},role:'operator',scopes:['operator.read','operator.write','operator.admin'],caps:[]});
 evidence.before=await rpc('rollback.probe',{});assert.equal(evidence.before.marker,'frozen-original');
 const inspection=await rpc('plugins.inspect',{pluginId:plugin});fs.writeFileSync(root+'/inspection.json',JSON.stringify(inspection));
 fs.writeFileSync(root+'/plugin/value.cjs','module.exports="mutated-disk";');
 fs.writeFileSync(root+'/plugin/index.cjs','throw new Error("EXPECTED_ROLLBACK_PROOF_REPLACEMENT_FAILURE");');
 fs.writeFileSync(root+'/armed','capture');
 const start=Date.now();const reload=client.request('plugins.reload',{plugins:[{pluginId:plugin}],...(inspection.reviewToken?{acknowledgeCapabilities:{reviewToken:inspection.reviewToken}}:{})},120000);
 const deadline=Date.now()+30000;
 while(!fs.existsSync(root+'/capture-begin.json')&&Date.now()<deadline){await new Promise(r=>setTimeout(r,10));}
 assert.ok(fs.existsSync(root+'/capture-begin.json'),'real recovery copy began');
 const began=JSON.parse(fs.readFileSync(root+'/capture-begin.json','utf8'));
 const sent=Date.now(); const health=await rpc('health',{}); const completed=Date.now();
 evidence.foreground={sentAfterBeginMs:sent-began.time,latencyMs:completed-sent,ok:!!health,completedBeforeCaptureEnd:!fs.existsSync(root+'/capture-end.json')};
 const result=await reload;evidence.reload={ok:result.ok,error:result.error,totalMs:Date.now()-start};
 evidence.capture={...began,...{durationMs:JSON.parse(fs.readFileSync(root+'/capture-end.json','utf8')).time-began.time}};
 evidence.after=await rpc('rollback.probe',{});assert.equal(evidence.after.marker,'frozen-original');
 assert.equal(result.ok,false,'replacement must fail');
 assert.match(JSON.stringify(result.error),/EXPECTED_ROLLBACK_PROOF_REPLACEMENT_FAILURE/);
 assert.equal(evidence.foreground.completedBeforeCaptureEnd,mode!=='baseline-proof','foreground/capture ordering');
 assert.notEqual(evidence.before.instance,evidence.after.instance,'rollback must construct a fresh instance');
 const target=JSON.parse(fs.readFileSync(root+'/capture-target.json','utf8')).target;
 const findValue=(dir:string):string[]=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(entry=>entry.isDirectory()?findValue(path.join(dir,entry.name)):entry.name==='value.cjs'?[fs.readFileSync(path.join(dir,entry.name),'utf8')]:[]);
 evidence.custody={retainedAfterRollback:fs.existsSync(target),frozenDependencyRestored:findValue(target).includes('module.exports="frozen-original";'),freshInstance:true};
 assert.ok(evidence.custody.frozenDependencyRestored);
 if(!process.env.ROLLBACK_PROOF_SKIP_MODEL){
 await rpc('sessions.create',{key:'agent:main:rollback-proof',agentId:'main'});
 const id=randomUUID();const message=live.register(id,'agent:main:rollback-proof',0);
 const started=await rpc('agent',{sessionKey:'agent:main:rollback-proof',message,deliver:false,idempotencyKey:id});live.accept(id,started);
 live.complete(id,await rpc('agent.wait',{runId:id,timeoutMs:90000}));
 await live.captureHistories(rpc);evidence.live=live.snapshot();
 }else evidence.live={blocked:'prior real OpenAI request returned credit_balance_exhausted; not retried'};
 client.close(); client=undefined;evidence.shutdown=await stopGatewayGracefully(child,45000);
 evidence.custody.removedAfterShutdown=!fs.existsSync(target);assert.ok(evidence.custody.removedAfterShutdown,'joined physical custody cleanup');
 evidence.success=true;
}catch(e){evidence.failure=String(e);throw e;}finally{
 client?.close();if(child.exitCode===null&&child.signalCode===null)evidence.forcedCleanup=await stopChild(child);
 log.end();fs.writeFileSync(root+'/result.json',JSON.stringify(evidence,null,2));console.log(JSON.stringify(evidence,null,2));
}

Integrate main and resolve reload recovery conflicts without reviving the obsolete worker capture path. Keep source-copy and frozen recovery semantics at the existing host-local owner.

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
@RomneyDa
RomneyDa merged commit 51f2fde into main Nov 16, 2026
137 checks passed
@RomneyDa
RomneyDa deleted the openclaw/retro-508-rollback-adaptation branch November 16, 2026 02:51
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…apture (openclaw#198262)

* fix(plugins): avoid blocking foreground work during reload recovery capture

Adapt the rollback capture approach from Wes (@akmad), openclaw#181491, to the current worker-owned recovery lifecycle. Preserve synchronous frozen-source and custody-fork contracts.

Co-authored-by: Wes <[email protected]>

Co-authored-by: vincentkoc <[email protected]>

Co-authored-by: RomneyDa <[email protected]>

* fix(plugins): avoid blocking foreground work during reload recovery capture

Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 630a3a3a-acae-45ed-863a-3c57e7c36035

---------

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
steipete added a commit that referenced this pull request Nov 17, 2026
…200374)

* fix(plugins): keep reload recovery metadata off the Gateway thread

Move the complete asynchronous recovery copy into the existing capture
broker, including root creation, copy filtering, native link validation,
and cleanup. Reuse one physical copy algorithm for the retained sync fork.

Follow up on #198262 and Wes (@akmad)'s original #181491 recovery work.
Preserve the independent native leases established by #200320.

A synthetic two-second create delay reduces the median MAIN heartbeat
gap from 2010 to 10 ms. Cold owner time rises 94.750 to 124.388 ms;
that cost and the remaining synchronous fork/import contracts are recorded
in the PR evidence. No configuration or schema changes.

* fix(tooling): include recovery imports in the PR wrapper

* test: prepare runtime build graph workers before test launch

A cold full Vitest worker compilation took 76 seconds inside the first 60-second heartbeat build-graph test. Enroll this selection in the existing runner preparation owner; preserve graph selection, test limits and assertions. Direct and projects runner regressions fail before the correction and all 55 runner cases pass afterward. Changed checks retain only the previously attributed Slack/UI dead exports.

* test: provide compiler artifacts for eager tooling admission

Use the existing controlled compiler for the unrestricted tooling selection. The eight-case admission table reproduces the missing manifest before this fixture migration and passes after it; retain the compiler count, receipt and selection assertions. No production behavior or timeout changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…penclaw#200374)

* fix(plugins): keep reload recovery metadata off the Gateway thread

Move the complete asynchronous recovery copy into the existing capture
broker, including root creation, copy filtering, native link validation,
and cleanup. Reuse one physical copy algorithm for the retained sync fork.

Follow up on openclaw#198262 and Wes (@akmad)'s original openclaw#181491 recovery work.
Preserve the independent native leases established by openclaw#200320.

A synthetic two-second create delay reduces the median MAIN heartbeat
gap from 2010 to 10 ms. Cold owner time rises 94.750 to 124.388 ms;
that cost and the remaining synchronous fork/import contracts are recorded
in the PR evidence. No configuration or schema changes.

* fix(tooling): include recovery imports in the PR wrapper

* test: prepare runtime build graph workers before test launch

A cold full Vitest worker compilation took 76 seconds inside the first 60-second heartbeat build-graph test. Enroll this selection in the existing runner preparation owner; preserve graph selection, test limits and assertions. Direct and projects runner regressions fail before the correction and all 55 runner cases pass afterward. Changed checks retain only the previously attributed Slack/UI dead exports.

* test: provide compiler artifacts for eager tooling admission

Use the existing controlled compiler for the unrestricted tooling selection. The eight-case admission table reproduces the missing manifest before this fixture migration and passes after it; retain the compiler count, receipt and selection assertions. No production behavior or timeout changes.
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Backport #198262 to the retained stable generation owner. Preserve synchronous source custody and fork contracts; await recovery through the owning instance and worker transport.

(cherry picked from commit 51f2fde)
Co-authored-by: Wes <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…200374)

* fix(plugins): keep reload recovery metadata off the Gateway thread

Move the complete asynchronous recovery copy into the existing capture
broker, including root creation, copy filtering, native link validation,
and cleanup. Reuse one physical copy algorithm for the retained sync fork.

Follow up on #198262 and Wes (@akmad)'s original #181491 recovery work.
Preserve the independent native leases established by #200320.

A synthetic two-second create delay reduces the median MAIN heartbeat
gap from 2010 to 10 ms. Cold owner time rises 94.750 to 124.388 ms;
that cost and the remaining synchronous fork/import contracts are recorded
in the PR evidence. No configuration or schema changes.

* fix(tooling): include recovery imports in the PR wrapper

* test: prepare runtime build graph workers before test launch

A cold full Vitest worker compilation took 76 seconds inside the first 60-second heartbeat build-graph test. Enroll this selection in the existing runner preparation owner; preserve graph selection, test limits and assertions. Direct and projects runner regressions fail before the correction and all 55 runner cases pass afterward. Changed checks retain only the previously attributed Slack/UI dead exports.

* test: provide compiler artifacts for eager tooling admission

Use the existing controlled compiler for the unrestricted tooling selection. The eight-case admission table reproduces the missing manifest before this fixture migration and passes after it; retain the compiler count, receipt and selection assertions. No production behavior or timeout changes.

(cherry picked from commit 5275f43)
Co-authored-by: RomneyDa <[email protected]>
Release adaptation: apply after #200320 native capture owner prerequisite; retain source recovery copy and regression contracts unchanged. Follow-up #200571 detaches the independent owner from retired caller context.:
(cherry picked from commit b1d97f0a472874e12bbfb3a0e429f97f509d3710)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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.

1 participant