Repository navigation
fix(cli): avoid writable session open during fallback - #156703
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 5:31 PM ET / 21:31 UTC (Revision 8). ClawSweeper reviewWhat this changesMoves CLI fallback session reads to the existing read-only worker, rechecks placement before CLI execution, adds contention regressions, and isolates updater output test fixtures from shared service locks. Merge readiness✅ Ready for maintainer review Current main still makes a writable session lookup during CLI fallback. The merged cold-admission repair addresses an earlier step, so this distinct fix remains useful. I found no blocking defect in the pinned patch. Priority: P1 Review scores
Verification
How this fits togetherAn agent turn can select a CLI backend after fallback. The runner reads session metadata and placement authority before invoking that backend and returning a reply or a terminal abort. flowchart LR
A[User turn] --> B[Fallback selection]
B --> C[Placement admission]
C --> D[Read-only session worker]
D --> E{Placement current?}
E -->|Yes| F[CLI backend and reply]
E -->|No| G[Superseded abort]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +10, Tests +132. Total +142 across 3 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Use the read-only session owner for fallback metadata and retain the live placement check before CLI execution, then land through the normal exact-head gates. Do we have a high-confidence way to reproduce the issue? Yes. Current main still uses the writable accessor, and the supplied real-SQLite negative controls report its lock failure; I did not execute the case in this read-only checkout. Is this the best way to solve the issue? Yes. The existing read-only worker avoids the unnecessary writable admission, while settlement revalidation protects the added asynchronous gap. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against da2bcd699bc1. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
Preserve the author main merge. Read post-placement session metadata with the canonical read-only worker and revalidate settlement authority after the await. Exercise cold fallback reads with a real shared-state SQLite write transaction and retain main/global and retired-placement boundaries. Keep expired schema admission distinct from recoverable resident-cache invalidation, fixing the reproduced current-head CI failure while retaining valid publication across ordinary read retirement. Give the updater output fixture its own unavailable service observations without weakening polling, timeout, report or mutation assertions. Include the exact canonical generated Workboard Control UI asset-path refresh from Peter Steinberger commit 559b4f8. Normal asset generation reproduces these bytes after the already-merged protocol activity change; no browser source, styles, capabilities or permissions changed. Co-authored-by: VACInc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Jason (Json) <[email protected]>
|
Updated head: The updated candidate retains main's canonical conflict resolutions and the original contributor ancestry. The read-only fallback and fixture-isolation repairs were reviewed with the repository P3 helper; final source review was scoped-clean. The requested contended Gateway stale-session outcome is now observed on candidate Sanitized result: {"placementCallbacks":1,"writableAccessorRejected":true,"candidateError":"AbortError: agent run superseded by a newer session writer","agentWait":{"status":"error","stopReason":"superseded"},"chatAbortEvents":1,"cliExecutableInvocations":0}The patched harness passed in 28.17s. Gateway history also contains its own failure notice; this is a safe abort, not a successful model reply. Restoring only the candidate production file from main Isolated proof harness (temporary, outside per-PR suites)Save under import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { expect, it, vi } from 'vitest';
import { testing as cliBackendsTesting } from '../src/agents/cli-backends.test-support.js';
import { loadSessionEntry, loadSessionEntryReadOnly, replaceSessionEntry } from '../src/config/sessions/session-accessor.js';
import { resolveSessionStorePathCore } from '../src/config/sessions/paths.js';
import { resolveSqliteScope } from '../src/config/sessions/session-accessor.sqlite-scope.js';
import { closeOpenClawAgentDatabaseByPathAsync } from '../src/state/openclaw-agent-db-lifecycle.js';
import { resolveOpenClawAgentSqlitePath } from '../src/state/openclaw-agent-db.paths.js';
import { resolveOpenClawStateSqlitePath } from '../src/state/openclaw-state-db.paths.js';
import { createGatewayConfigPath, setupGatewayTempHome, removeGatewayTempHome, resetGatewayTestState } from '../src/gateway/gateway.test-support.js';
import { startGatewayWithClient, disconnectGatewayClient } from '../src/gateway/test-helpers.e2e.js';
import { runQaGatewayFixture } from '../test/helpers/qa-gateway-cleanup.js';
const probe = vi.hoisted(() => ({ armed: false, installed: 0, entered: 0, writableRejected: false, error: '', revision: '' }));
vi.mock('../src/agents/session-placement-admission.js', async (importOriginal) => {
const real = await importOriginal<typeof import('../src/agents/session-placement-admission.js')>();
return {
...real,
installSessionPlacementAdmissionProvider: (provider: Parameters<typeof real.installSessionPlacementAdmissionProvider>[0]) => { probe.installed++; return real.installSessionPlacementAdmissionProvider({
...provider,
executeLocalTurn: (claim, runLocal, assertCurrent) => provider.executeLocalTurn(claim, async () => {
if (!probe.armed || !claim.sessionKey?.includes('contention-proof')) return runLocal();
probe.entered++;
const target = {sessionKey: claim.sessionKey, agentId: claim.agentId ?? 'main', storePath: resolveSessionStorePathCore(undefined, {agentId: claim.agentId ?? 'main'})};
const original = loadSessionEntryReadOnly(target);
expect(original?.sessionId).toBe(claim.sessionId);
probe.revision = randomUUID();
await replaceSessionEntry(target, {...original!, lifecycleRevision: probe.revision});
await closeOpenClawAgentDatabaseByPathAsync(resolveOpenClawAgentSqlitePath(resolveSqliteScope(target)));
const holder = new DatabaseSync(resolveOpenClawStateSqlitePath());
holder.exec('BEGIN IMMEDIATE');
try {
expect(() => loadSessionEntry(target)).toThrow(/database is locked/iu);
probe.writableRejected = true;
try { return await runLocal(); }
catch (error) { probe.error = String(error); throw error; }
} finally {
if (holder.isTransaction) holder.exec('ROLLBACK');
holder.close();
}
}, assertCurrent),
}); },
};
});
it('real Gateway rejects stale CLI session under cold shared-state write contention', async () => {
resetGatewayTestState();
const home = await setupGatewayTempHome({prefix: 'openclaw-cli-contention-proof-'});
let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
const events: unknown[] = [];
const token = randomUUID();
const invoked = path.join(home.tempHome, 'cli-invoked');
const executable = path.join(home.tempHome, 'synthetic-cli.cjs');
await fs.writeFile(executable, `require('node:fs').writeFileSync(${JSON.stringify(invoked)},'invoked'); console.log('UNEXPECTED CLI REPLY');`);
const pluginDir = path.join(home.tempHome, 'proof-fixture');
await fs.mkdir(pluginDir);
await fs.writeFile(path.join(pluginDir,'openclaw.plugin.json'),JSON.stringify({id:'proof-fixture',name:'Isolated CLI proof',cliBackends:['proof-cli'],activation:{onStartup:true},configSchema:{type:'object',additionalProperties:false,properties:{}},contracts:{cliBackends:['proof-cli']}}));
await fs.writeFile(path.join(pluginDir,'index.js'),`export default {id:'proof-fixture',register(api){api.registerCliBackend({id:'proof-cli',modelProvider:'proof-cli',ownsNativeCompaction:false,config:{command:${JSON.stringify(process.execPath)},args:[${JSON.stringify(executable)}],output:'text',input:'arg',sessionMode:'none'}});}};`);
await runQaGatewayFixture(async () => {
gateway = await startGatewayWithClient({
token,
configPath: await createGatewayConfigPath(home.tempHome),
cfg: {
agents:{defaults:{workspace:home.workspaceDir,skipBootstrap:true,heartbeat:{every:'0m'},model:{primary:'proof-cli/proof'},models:{'proof-cli/proof':{agentRuntime:{id:'proof-cli'}}}}},
gateway:{auth:{mode:'token',token}}, hooks:{enabled:false},
plugins:{enabled:true,load:{paths:[pluginDir]},entries:{'proof-fixture':{enabled:true}}},
models:{mode:'replace',providers:{'proof-cli':{baseUrl:'http://127.0.0.1:1/v1',api:'openai-responses',apiKey:'synthetic',models:[{id:'proof',name:'Proof',reasoning:false,input:['text'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32000,maxTokens:1024}]}}},
},
onEvent: (event) => { if (event.event === 'chat') events.push(event.payload); },
});
await gateway.server.startupSettled;
console.log('PROBE_STARTED', JSON.stringify(probe));
probe.armed = true;
const sessionKey = `agent:main:contention-proof-${randomUUID()}`;
const accepted = await gateway.client.request<{runId:string;status:string}>('chat.send',{sessionKey,message:'Return one reply.',deliver:false,idempotencyKey:randomUUID()},{expectFinal:false});
expect(accepted.status).toBe('started');
const terminal = await gateway.client.request('agent.wait',{runId:accepted.runId,timeoutMs:120000},{timeoutMs:125000});
const history = await gateway.client.request<{messages:Array<{role:string;content:unknown}>}>('chat.history',{sessionKey,limit:100});
console.log('CONTENTION_PROOF', JSON.stringify({probe,terminal,chatStates:events.map((event:any)=>({state:event.state,stopReason:event.stopReason}))}));
expect(probe.entered).toBe(1);
expect(probe.writableRejected).toBe(true);
expect(probe.error).toMatch(/superseded/i);
expect(terminal).toMatchObject({status:'error',stopReason:'superseded',error:'agent run superseded by a newer session writer'});
expect(events.filter((event:any)=>event.state === 'aborted')).toEqual([expect.objectContaining({runId:accepted.runId,stopReason:'superseded'})]);
const assistant = history.messages.filter(message=>message.role === 'assistant');
expect(assistant).toHaveLength(1);
expect(assistant[0]).toMatchObject({provider:'openclaw',model:'gateway-injected',content:[{type:'text',text:expect.stringContaining("OpenClaw couldn't produce or deliver a reply")} ]});
expect(JSON.stringify(history.messages)).not.toContain('UNEXPECTED CLI REPLY');
await expect(fs.stat(invoked)).rejects.toMatchObject({code:'ENOENT'});
},
async () => { if (gateway) await disconnectGatewayClient(gateway.client); },
async () => { await gateway?.server.close({reason:'isolated contention proof complete'}); },
() => { cliBackendsTesting.resetDepsForTest(); home.envSnapshot.restore(); resetGatewayTestState(); },
() => removeGatewayTempHome(home.tempHome));
}, 180000);
import { createGatewayServerIsolatedVitestConfig } from '../test/vitest/vitest.gateway-server-isolated.config.ts';
const config = createGatewayServerIsolatedVitestConfig();
export default {...config, test:{...config.test, include:['.local/gateway-cli-contention.test.ts'], passWithNoTests:false, maxWorkers:1}};node scripts/run-vitest.mjs run --config .local/gateway-cli-contention.config.ts@clawsweeper re-review Please assess this exact head and the contended Gateway stale-session abort evidence above. Conflict resolution retains current main’s canonical subagent and generated asset changes. Review only; do not merge. |
|
🦞👀 Re-review progress:
|
Integrate current main without rewriting contributor ancestry. Keep its subagent admission failure propagation and generated Workboard assets. Preserve the CLI worker read, settlement fence, and contention regression. Keep updater output fixtures in their own secure runtime directory on POSIX and Windows so synthetic service locks cannot contend with another checkout or an operator service. Retain real lock and timeout behavior. Co-authored-by: VACInc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Jason (Json) <[email protected]>
cfe5361 to
794a477
Compare
|
Rebased to current main; published head CI run 36350918138 failed four cases in @clawsweeper re-review Review this exact head only; do not merge. |
|
🦞👀 Re-review progress:
|
* fix(cli): read fallback session state without writable open * fix(cli): keep fallback replies working during state contention Preserve the author main merge. Read post-placement session metadata with the canonical read-only worker and revalidate settlement authority after the await. Exercise cold fallback reads with a real shared-state SQLite write transaction and retain main/global and retired-placement boundaries. Keep expired schema admission distinct from recoverable resident-cache invalidation, fixing the reproduced current-head CI failure while retaining valid publication across ordinary read retirement. Give the updater output fixture its own unavailable service observations without weakening polling, timeout, report or mutation assertions. Include the exact canonical generated Workboard Control UI asset-path refresh from Peter Steinberger commit 4afb919. Normal asset generation reproduces these bytes after the already-merged protocol activity change; no browser source, styles, capabilities or permissions changed. Co-authored-by: VACInc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Jason (Json) <[email protected]> --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: RoboClaw <[email protected]> Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Jason (Json) <[email protected]>
Summary
High Level TLDR
CLI fallback can fail before producing a reply because its session metadata read opens a writable database. Read through the existing read-only worker, then recheck placement authority before executing the CLI.
What Problem This Solves
Fixes a reachable fallback failure when another connection holds a shared-state SQLite write transaction during a cold session read.
User Impact
A current session can reach CLI execution without this unnecessary writable-open contention. Replaced sessions and retired placement claims still abort before execution. This does not promise recovery from every database contention path or replay a whole turn.
Why This Change Was Made
The final delta against main contains three files: the canonical read-only worker call with placement revalidation; real SQLite contention, main/global session-key and retired-placement regressions; an updater output fixture repair. Current main independently includes the synchronized-frame TUI test repair; this PR has no TUI delta. Main was integrated while preserving the original contributor ancestry. The subagent admission and generated Workboard conflict resolutions take main's canonical implementations, leaving no net delta in either file. Main's newer media-task identity logic remains intact.
The updater fixture now owns unavailable-service observations and uses a per-case secure runtime directory. A verification run exposed that its synthetic service borrowed the operator's shared lifecycle lock, which another checkout legitimately held. Both preferred and Windows fallback temporary-directory paths now remain inside the fixture. Real lock acquisition, timeout budgets, recovery polling and report assertions are unchanged.
Root Cause
runCliFallbackCandidaterereads session metadata after placement admission. The previousloadSessionEntrycall enters writable agent-database admission although it only needs a committed row. The regression closes the agent handle, opens a separate real shared-state SQLite connection withBEGIN IMMEDIATE, and observes the old accessor throwdatabase is locked. The changed path useswithSessionEntryReadOnlyInWorker, propagates read errors, and revalidates settlement after the await.The earlier Telegram incident had no first-throw stack. It supports the original report but does not establish that this accessor caused every observed contention error. Initial reply admission is separate from this later fallback reread.
Evidence
Real behavior proof
At pushed head
14b848aafbcccfb78c35288c6dfd8f5687e20975, on Linux with Node 24.19.0 and pnpm 12.5.0:pnpm test src/auto-reply/reply/agent-runner-execution-cli-admission.test.ts --maxWorkers=1Result: 13 passed, 53.24 seconds wrapper wall time, 51.18 seconds Vitest duration. The cold-contention case took 8.431 seconds; it needs real SQLite and the read-worker boundary because an accessor mock would hide the original defect. It returns one reply payload through
executeAgentTurnand invokes the mocked CLI adapter once with the existing native binding. Retired placement and lifecycle revision changes abort before that invocation.Negative control: restoring only the production candidate file from merge base
574927f256fa1a5355985b3d657d357abdd3fffband running the cold-contention case fails: expectedkind: "success"with reply payload, receivedkind: "final". The production file was restored afterward. No assertions or deadlines were weakened.Isolated Gateway outcome on candidate
544af47211afba3df90760a58d07f347e6dd5312: A temporary CLI plugin was loaded normally and a real authenticatedchat.sendturn entered the real placement owner. At its callback boundary, the harness committed a newer session lifecycle revision, closed the agent handle, and heldBEGIN IMMEDIATEon the shared-state database. It first verified that the old writable accessor throwsdatabase is locked, then let the unchanged candidate proceed under that lock.The patched turn produced
agent.wait { status: "error", stopReason: "superseded" }, one clientchatevent withstate: "aborted"andstopReason: "superseded", and no invocation of the synthetic CLI executable. History contained the Gateway's own failure notice, not a model reply. The executable invocation marker stayed absent. The focused Gateway harness passed in 28.17 seconds. This is a safe stale-session abort through real Gateway RPC, not a claim of successful Telegram delivery.Negative control used the same Gateway harness with only the candidate production file restored from pinned main
8d4d13c9e4e446b7ad72d3744ce52bcdc3100b9a: it failed withdatabase is locked, without the expected superseded terminal outcome. The candidate file was restored and checkout verified clean. Initial harness attempts stopped at missing synthetic model/runtime registration; those attempts provide no product proof.Verification
794a477224066114b9b3e3aab75e36e24b5b0fba, treee0add6b6297133990a45d1e5995dc00b2ef8f5f1, based on mainda2bcd699bc. Remote head/tree verified. Contributor ancestry and trailers retained. The three changed files are byte-identical to the reviewed repair candidate.b459eb600f238d38f8b7156675e5868751f52c54. No product assertion was weakened in this PR. ClawSweeper cleared previous headcfe5361d967; exact new-head GitHub CI and refreshed review are pending. No readiness or complete current-head suite pass is claimed.63c5d45; these are prior proof, not new-head CI.544af472: 86 focused cases across five files passed in three original-order runs (185.3s, 134.1s, 138.2s wall); another 33 worker ownership/invalidation cases passed in 25.84s. The updater scenario passed 20 targeted invocations after fixture isolation. CLI admission file: 13 cases, 53.24s wrapper wall; cold contention: 8.431s. CI timing will be recorded when available.--no-lazy-fetch, and a TUI assertion reading accumulated source-session output. Matching Chromium and Git 2.47.3 corrected the environment; current main contains the TUI owner fix. The affected 344 Docker-helper, 72 TUI and 30 browser cases then passed. A subsequent whole-suite run was also stopped; neither run is reported as a complete pass.What was not tested
No live Telegram delivery, real external CLI invocation, complete full-suite pass, final-candidate CI pass, Windows execution, or comparative runtime benchmark is claimed. The isolated regression uses real SQLite and production turn dispatch with a mocked CLI adapter; it does not prove channel delivery. No live Gateway was changed during this continuation.
Contributor credit
Work sessions
Implementation and discussion